Compare commits
85 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 68800815c4 | |||
| 67b806fc5c | |||
| b0d2069b15 | |||
| ca704a55a0 | |||
| 2f6b1e23ec | |||
| b4fb7b3881 | |||
| f4a35afbc9 | |||
| 5bc899eef3 | |||
| 0c51ddc4df | |||
| 85ddf5ea22 | |||
| ca08f93eeb | |||
| 5b66c75917 | |||
| 8fd229641a | |||
| c2b907b544 | |||
| 376dc3d59a | |||
| e32e54e7aa | |||
| 6b451d4de7 | |||
| 7e16b33ff6 | |||
| 922219748e | |||
| 38b3e07cfe | |||
| b489c59980 | |||
| f34959026a | |||
| 38d8e2c4b9 | |||
| a46ecf142a | |||
| 809ce3bda8 | |||
| c25e42c005 | |||
| a62acf8241 | |||
| e1ef420b2d | |||
| 51a030fa60 | |||
| f5dcb12a93 | |||
| e090be2f8d | |||
| 27aaa313b4 | |||
| 9759a0e21e | |||
| fe9ece1cc9 | |||
| bad56988b7 | |||
| e5855ac800 | |||
| f4f6d8b9c9 | |||
| 61139c61bf | |||
| 9f727427a7 | |||
| 151a2ffff8 | |||
| cb3af9d06a | |||
| 89bff0c36a | |||
| 89e21eb4b2 | |||
| 3332a7f264 | |||
| 6b0b20cee1 | |||
| 0c5fe12d0a | |||
| 8684d9d60c | |||
| 7f7d39b748 | |||
| e3978d4df2 | |||
| 579fc6b105 | |||
| c2158af6d3 | |||
| 0592c9993d | |||
| f831839a90 | |||
| f0ad84fe74 | |||
| 1e6d035d6d | |||
| 1a88ab3199 | |||
| d35695e5fa | |||
| ac65f3ab92 | |||
| 1ba8a11189 | |||
| 4a6856711f | |||
| 9d120450da | |||
| 9c8837eb45 | |||
| dc00a4f8f5 | |||
| 06f049ba37 | |||
| c242808137 | |||
| 99da159866 | |||
| 85be77188f | |||
| 93502f9daf | |||
| 4e662f1d03 | |||
| 57c65d7a12 | |||
| cc968d93ff | |||
| 6adf0fd20c | |||
| 59b21b484d | |||
| d27706abeb | |||
| 02d324b896 | |||
| 9692712e63 | |||
| 660fb471cc | |||
| ae12f01998 | |||
| 63f9a0fc59 | |||
| 69811f953b | |||
| ba0afa757a | |||
| bbcb84ec6c | |||
| cda6ab1936 | |||
| efeaece465 | |||
| e2f3dbdc11 |
@@ -11,7 +11,7 @@ Nextcraft is a TypeScript monorepo (pnpm workspaces + turborepo) with a Next.js
|
||||
### v0.6 Research Conclusions (Phase 0 RESEARCH)
|
||||
|
||||
32. **D-048 Marketplace module layout mirrors D-031** — one new engine module `ai_service/marketplace/` inside apps/ai-service (no new apps, no new ports): `base.py` (pydantic contracts: `Posting`, `Employer`, `PostingTags`, `IngestPosting`), `store.py` (6th D-027 store family, D-049), `ingest.py` (PostingSource adapters, D-050), `tagging.py` (D-052), `embedding/` (protocol + mock + openai_compat + factory, D-051), `search.py` (hybrid facet+cosine ranking, A-405), `enrichment.py` (D-053), `resume.py` (D-054), with the HTTP surface in `ai_service/api/marketplace.py` (`/v1/marketplace/*` router) + `api/marketplace_admin.py` (`/v1/marketplace/admin/*`, D-057) composed via `deps.py` app.state DI (`get_marketplace_store`, `get_embedding_provider`). Boundary rules identical to identity/voice: `marketplace/` never imports `agents/` or `api/`; settings in `config.py` (backend-engineer territory); the G-18 stub MOVES from `api/identity.py` into the new router and becomes real (D-058) — `identity/` keeps only the `require_verified_adult` gate dependency it exports today.
|
||||
33. **D-049 Sixth store = one SQLite DB, five tables, DefenseStore conventions** — the marketplace store joins the shared `~/.nextcraft/data/nextcraft.db` (all 5 prior stores already share it; `Settings().db_path`). Tables: `posting` (id PK, source, external_id, employer_id, title, description, skills/seniority/category/location/remote/salary JSON+portable columns, status `draft|published|closed`, posted_at, unique constraint on (source, external_id) for idempotent upsert per A-402); `employer` (id PK, ingested raw fields, unique per source); `embedding` (posting_id PK, `vector` BLOB of struct-packed little-endian float32, `model`, `dim` — A-403/A-404 per-row provenance so lazy re-embed on provider change works); `application` (id PK, posting_id, learner_id, status `submitted`, created_at, unique (posting_id, learner_id) for A-408 idempotent apply); `employer_enrichment` (append-only: id PK, employer_id, field, value, source `llm|manual`, model, created_at — A-409). All tables mirror the probe-verified identity/store.py mechanics: WAL/synchronous=NORMAL/busy_timeout/foreign_keys pragmas, `sa_type=String/JSON` portable columns, `_validate()` hooks, Protocol + SQLite impl pair, surfaced IntegrityError, tz normalization. `VectorStore` is a protocol method-group on the marketplace store (pgvector-swap-ready, D-019/D-027 pattern).
|
||||
33. **D-049 Sixth store = one SQLite DB, five tables, DefenseStore conventions** — the marketplace store joins the shared `~/.nextcraft/data/nextcraft.db` (all 5 prior stores already share it; `Settings().db_path`). Tables: `posting` (id PK, source, external_id, employer_id, title, description, skills/seniority/category/location/remote/salary JSON+portable columns, status `draft|published|closed`, posted_at, unique constraint on (source, external_id) for idempotent upsert per A-402); `employer` (id PK, ingested raw fields, unique per source); `embedding` (posting_id PK, `vector` BLOB of struct-packed little-endian float32, `model`, `dim` — A-403/A-404 per-row provenance so lazy re-embed on provider change works); `application` (id PK, posting_id, learner_id, status `submitted`, created_at, unique (posting_id, learner_id) for A-408 idempotent apply); `employer_enrichment` (append-only: id PK, employer_id, field, value, source `llm|manual`, model, created_at — A-409). **[AMENDED by grill G-104: SIX tables — the `learner_profile` table (learner_id PK, profile JSON, confirmed_at, model) replaces the filesystem sidecar the plan draft proposed; the D-027 store family is the only persistence mechanism. Shipped six-table in P1.]** All tables mirror the probe-verified identity/store.py mechanics: WAL/synchronous=NORMAL/busy_timeout/foreign_keys pragmas, `sa_type=String/JSON` portable columns, `_validate()` hooks, Protocol + SQLite impl pair, surfaced IntegrityError, tz normalization. `VectorStore` is a protocol method-group on the marketplace store (pgvector-swap-ready, D-019/D-027 pattern).
|
||||
34. **D-050 PostingSource = protocol + two adapters, no scheduler** — `PostingSource` protocol: `fetch() -> Iterable[IngestPosting]` (pydantic, A-402 shape: source, external_id, employer + posting fields). Two v0.6 implementations: `seeded_corpus` (in-repo JSON seed ported ONCE from `packages/mock-data/jobs.ts` (20 jobs) + `employers.ts` (10 employers) per D-021 convention — shared IDs, mock `matchScore` DROPPED since D-051 computes real ones) and `admin_api` (the founder-authored path; the admin router calls ingest directly rather than an HTTP hop). Ingest upserts idempotent on (source, external_id); a `POST /v1/marketplace/admin/ingest` route triggers a source run explicitly (founder-invoked — no cron/crawler, A-401/A-402). The 3M+ external corpus lands later as a third adapter with zero store/route changes.
|
||||
35. **D-051 EmbeddingProvider = D-030 mirror with a corrected real path** — protocol `embed(texts: list[str]) -> list[EmbeddingVector]` (frozen pydantic: `values: list[float]`, `model`, `dim`) in `marketplace/embedding/base.py`. Deterministic mock: 256-dim feature-hash of normalized tokens (pure stdlib, similarity deterministic — tests never call the cloud). Real: `OpenAIEmbedProvider` on the shared httpx pool posting `{"model", "input": [texts]}` to `{AI_EMBED_BASE_URL}/embeddings` (OpenAI-compatible; `_sanitize` key redaction mirroring `openai_audio.py`). **Probe correction to A-404:** ollama-cloud does NOT expose `/v1/embeddings` (404 path-not-found; chat/completions auth-gates 401) — so `AI_EMBED_BASE_URL` must point at a different OpenAI-compatible endpoint (local ollama `:11434/v1` supports it, or any embeddings cloud); provider selection `AI_EMBED_PROVIDER=mock|openai-embed` (default mock, G-11 boot-safe fallback with loud log — exact `voice/factory.py` pattern, `AI_EMBED_MODEL`/`AI_EMBED_API_KEY` env-only). Storage per A-403: struct-packed `<{dim}f` float32 BLOB + model + dim per row; cosine in pure Python (sum of products / norm product, ≤10⁴ postings); candidate side embeds competency-profile text on demand, never stored. Confidence in A-404's parenthetical drops it to ~0.5 but the protocol design is unaffected (endpoint-agnostic by config is the D-014 pattern anyway).
|
||||
36. **D-052 Tagging = D-020 structured_completion, no new agent** — `marketplace/tagging.py` composes the EXISTING `structured_completion(provider, messages, model, schema, schema_hint)` (agents/structured.py, all 4 layers) with a `PostingTags` pydantic schema (skills: list[str] ≤10, seniority enum, category enum) + a versioned prompt constant in `prompts/` (or module-local, matching variants' pattern); no BaseAgent needed — tagging is a one-shot extraction like grading's rubric call. Mock-first for free: `settings.provider` defaults to `mock` and `structured_completion` runs against `MockLLMProvider.chat`, so tests stay cloud-free. Tags persisted as a JSON column on the posting row (D-049); tag facets feed the search filter sidebar (A-405 hard filters); re-tagging on posting update overwrites the tags column (single source of truth, no append-only need — unlike enrichment D-053, tags are derived data).
|
||||
@@ -33,6 +33,83 @@ Nextcraft is a TypeScript monorepo (pnpm workspaces + turborepo) with a Next.js
|
||||
30. **D-045 Seq-ack protocol (D-R06/D-R07)** — new WS frame `{"type":"seq_ack","seq":N}` emitted per successful append from `IngestSession._append` (durable `latest_seq`; O(1); advisory — gap detection stays authoritative, G-3/G-4 unchanged). The capture agent's supervisor loop (which today discards all non-close frames) parses text frames and trims spool+pending to `seq > ack` under `_emit_lock` via atomic `Spool.rewrite` — closing the one-line replay-margin gap (`_flush_locked` pops N in-flight frames but `replay_margin()` requeues only `_last_sent`). An explicit spool bound is added (A-309's "spool cap exists" premise was factually wrong on disk). Regression test: mid-burst kill in the test_durability.py real-server harness (uvicorn + KillableProxy) — the exact scenario the P07 de-flake documented as uncovered.
|
||||
31. **D-046 v0.5 wave order (D-R08)** — P1 seq-lease (smallest, protocol-only, fixes transport before env phases add reconnecting producers), P2 voice, P3 identity, P4 environments, P5 final. Phase numbers renumbered accordingly (was 1=voice..4=seq-lease in the initial ROADMAP draft).
|
||||
|
||||
### v0.7 Research Conclusions (Phase 0 RESEARCH — Test Harness Review, NFR)
|
||||
|
||||
44. **Harness baseline (probe-verified, 2026-09-26)** — 785 tests all green: pytest 671 (64 files, ~15.4K LOC), web node:test 53 (7 files, 1,379 LOC), CLI node:test 61 (11 files, 1,284 LOC). Zero coverage tooling, zero framework timeouts (ad-hoc 20-30s polling deadlines + a 600s CLI bootstrap), zero markers despite a real three-tier split (fast-unit / real-uvicorn / real-userns), zero `filterwarnings` policy. Web tests are OUTSIDE the turbo pipeline (no `@nextcraft/web#test` task; no root test/web:test script). PLAN.md verification counts stale (488/22/61 vs actual 671/53/61). `packages/{types,mock-data,ui}` have zero tests (cross-package contracts pinned only via other apps' source-read tests).
|
||||
45. **Warning census (probe-verified)** — 1,716 warnings per pytest run: ~99% from 14 `session.query()` sites (SQLModel deprecation: `marketplace/store.py` ×12 lines 490-952, `identity/store.py` ×2 lines 172/189); 14 ResourceWarning sites (unclosed `UploadFile` multipart ×10 from `api/defense.py:214` + `api/marketplace.py:446`; unclosed sockets ×3 `scripts/sandbox-agent.py:559`; unclosed file ×1 `tests/grading/test_engine.py:428`); 2 upstream import-time deprecations (fastapi/starlette TestClient httpx, anyio BlockingPortal). First-party deprecated-API audit CLEAN: no `datetime.utcnow`, no distutils/pkg_resources, no pydantic-v1 idioms, no legacy Next APIs. `next build` warning-free; no `ignoreBuildErrors`/`ignoreDuringBuilds` flags; ruff passes clean; all 5 tsc projects pass.
|
||||
46. **Suppression census** — 81 Python `# noqa` ALL inert (RUF100: suppressed codes not in the enabled select-set — SLF001 ×57, ANN001 ×12, E402 ×5 stale-positions, rest scattered); 5 orphaned `eslint-disable` comments (no ESLint exists — turbo lint is a no-op for 5 of 6 packages; `next lint` deprecated); 27 Python `# type: ignore` (11 src, 16 tests) with no type checker; zero `@ts-ignore`/`any` in TS. Dead exports: `packages/mock-data/ai-scenarios.ts` module, `NavItem`/`ThemeConfig` types, `Spawn` type, unused `MicControl` primitive. `FastAPI(version="0.3.0")` hardcoded vs pyproject "0.2.0" vs shipped v0.6 — version drift.
|
||||
47. **Duplicated harness infrastructure** — `KillableProxy` ×2 (`tests/sandbox/test_sandbox_agent.py:275`, `tests/telemetry/test_durability.py:45`); `_free_port()` ×4; userns probe ×4; real-uvicorn serve-loop boilerplate ×5; full-app state-injection boilerplate ×6; `wirePosting()` ×2 (web). 18 one-off MockProvider scripted subclasses (some consolidation possible, low priority). Flakiness already documented in-tree: `test_sandbox_agent.py:542` "8s was flaky" — timeout-widening is the current mitigation strategy, replaced by D-054's bounds + deterministic waits where possible.
|
||||
48. **Low-value test census** — web: 21/53 are source-text regex pins (`readFileSync` + literal-string asserts, e.g. "openGraph exists in a file"), triaged per D-057 (keep iff documented regression lesson or invisible cross-boundary wiring; cut tautologies); `test_budget_constant_defined` asserts a literal defined in its own file; `tests/llm/test_mock.py` + `identity/test_identity.py::TestMockProvider` are mock-meta tests (defensible: the mock is the suite-wide engine — keep). Silent skips: `apps/cli/tests/path-invocation.test.ts:14` returns early (passes silently when binary missing); `doctor.integration.test.ts` accepts either exit code. Env leak: `tests/conftest.py:80` mutates `os.environ["AI_PROVIDER"]` without restore; `seed_verified_identity` swallows all exceptions (`conftest.py:74-75`). Web source-pin tests depend on CWD = `apps/web` (breaks from monorepo root).
|
||||
49. **D-052 tooling conclusions** — coverage: pytest-cov (Python) + c8 wrapped around existing `tsx --test` (no runner swap, no vitest); markers `fast`/`real_server`/`userns` under `--strict-markers`, unmarked defaults to fast, fast run = `-m "not real_server and not userns"`; pytest-timeout `signal` method, 60s global / 180s real-server+userns via collection hook (D-054); CLI fresh-clone E2E env-gated (`CLI_E2E=1`) into `cli:test:e2e` with a 900s budget (D-055); `filterwarnings = ["error", <narrow module+message-scoped upstream ignores>]` (D-056); mypy relaxed-first baseline (`check_untyped_defs`, `warn_unused_ignores`, no full strict) (D-058); recharts 2→3 verified by tsc + static build + existing tests (D-059); shared Python helpers in `tests/helpers/` package, fixtures stay in conftest (D-060); pyproject.toml is the single version source, `FastAPI(version=)` reads package metadata (D-061).
|
||||
50. **D-062 v0.7 wave order = dependency-ordered: wiring before composition before elimination before hardening** — P1 harness wiring (coverage/timeout/markers/turbo tasks/leak fixes) MUST precede P2 suite composition because the cut/consolidate decisions are evidence-based (P1's coverage data tells P2 what to cut); P3 warning elimination is independent of P1/P2 but ordered after them to avoid rebasing `session.exec()` conversions over moved test files; P4 lint hygiene (ESLint + noqa RUF100) after P3 so the eslint-disable resolutions happen under a warning-clean tree; P5 type+dependency hardening last (mypy adoption and recharts 3 are the riskiest changes — they run against a fully-stabilized harness, and recharts gets the fresh coverage/ESLint net as its safety net); P6 final review. ESLint adoption (D-048) rides P4 because the orphaned eslint-disable comments only become meaningful once a config exists.
|
||||
|
||||
### v0.9 Payment Engine Architecture (Phase 0 RESEARCH — Payment Engine, D-075..D-084 binding)
|
||||
|
||||
**Module:** `ai_service/billing/` (7th domain module, D-031 pattern — extend ai-service, no new apps). Boundary rule (family discipline): `billing/` never imports `agents/` or `api/`; it imports `config` + its own `base.py` only. Files: `base.py` (PaymentProvider protocol + pydantic contracts + normalized event names), `store.py` (7th D-027 SQLite store), `mock.py` (deterministic provider, Stripe-shaped ids/signatures per R-36/R-48), `stripe.py` (Stripe-compatible REST impl — form-encoded bodies, Basic auth, Idempotency-Key per R-33/R-49), `factory.py` (env-gated selection, UnknownPaymentProviderError → G-11 loud mock fallback), `catalog.py` (seeded catalog constant + idempotent seed).
|
||||
|
||||
**Provider protocol (D-075):** `create_checkout_session(spec) -> CheckoutSession`, `retrieve_session(id)`, `cancel_subscription(id, *, at_period_end)`, `update_subscription(id, new_price_ref, ...)` (resolves subscription_item id inside the provider — R-47 dual-charge guard), `verify_webhook(raw_body: bytes, signature_header: str, *, now=None) -> VerifiedEvent` (HMAC-SHA256 over `"{t}.{raw_body}"`, compare_digest, all-v1 iteration for secret rolls, ±300s replay window, ignore non-v1 schemes — R-38..R-40), `normalize_event(provider_event) -> CanonicalBillingEvent` (R-43 mapping).
|
||||
|
||||
**Store (D-080, 7 tables):** `packages` (one-time: posts_limit, price_cents, duration_days), `plans` (recurring: interval, price_cents), `purchases` (posts_limit/posts_used/expires_at snapshot + price snapshot — D-078), `subscriptions` (state machine: trialing/active/past_due/cancelled/expired — G-305: no `upgraded` status, upgrade is a plan_id transition within `active` recorded as a billing_event; expires_at, provider ref), `subscription_events` (provider event log, verbatim ids, UniqueConstraint event_id — dedupe), `checkout_sessions` (client_reference_id reconciliation), `billing_events` (full audit: provider events + manual admin actions with provenance). Same SQLite file (`Settings().db_path`), WAL pragmas, Protocol + SQLiteBillingStore pair, main.py lifespan wiring with state-injection override.
|
||||
|
||||
**Routes:** `api/billing.py` (`/v1/billing/catalog` public GET; `/v1/billing/webhook` public POST — raw-body-first HMAC verify, then parse, then idempotent process, 200-fast) + `api/billing_admin.py` (`/v1/billing/admin/*` — require_admin dep verbatim R-51: checkout on behalf of employer (D-076), entitlement view, manual grant/revoke, event log query) + mock-only confirm route (D-082 as amended by G-301: mounted only when provider=mock AND composed with require_admin — no unauthenticated completion route on a payment surface). Entitlement enforcement composes into `create_posting` AFTER require_admin: billing store's `consume_posting(employer_id)` → domain error → route translates to `HTTPException(402, detail={reason, posts_used, posts_limit, upgrade_cta})` (dict-detail precedent = require_verified_age).
|
||||
|
||||
**Settings (R-53):** `payment_provider: str = "mock"`, `payment_api_key: SecretStr`, `webhook_secret: str = ""` (unset → per-boot random → webhooks fail closed — correct for a payment surface). Env: `AI_PAYMENT_PROVIDER`, `AI_PAYMENT_API_KEY`, `AI_WEBHOOK_SECRET`.
|
||||
|
||||
**Web (REQ-9-002):** pricing page → server shell (metadata retained, A-411/pins) + `PricingClient` component fetching `/v1/billing/catalog` (A-406 board-client pattern, AbortController + honest loading/error/empty states); `engine-client.ts` gains `listBillingCatalog()` + `PaymentRequiredError` (402 dict-detail discrimination); types in `packages/types/billing.ts` dual-schema-pinned in pins.test.ts. Admin entitlement view: moderation surface gains per-employer entitlement state (client fetch, same pattern).
|
||||
|
||||
**Money (D-081):** integer cents end-to-end; pydantic `int ge=0`; TS `number` documented as cents; currency `usd` fixed.
|
||||
|
||||
### v0.10 B2B Employer Network Architecture (Phase 0 RESEARCH — B2B Employer Network, D-086..D-097 binding)
|
||||
|
||||
**Module:** `ai_service/employers/` (8th domain module, D-031 pattern — extend ai-service, no new apps). Boundary rule (family discipline): `employers/` never imports `agents/` or `api/`; it imports `config` + its own files only. Files: `base.py` (pydantic contracts: EmployerAccount, EmployerClaim, session/token response shapes — dual-schema-pinned against packages/types/employer.ts, D-093; PostingSummary reused from marketplace.ts, never duplicated), `store.py` (8th D-027 SQLite store, 4 tables, D-095), `passwords.py` (stdlib scrypt KDF core — the billing/webhooks.py crypto-core precedent; D-086 params N=2^14/r=8/p=1/dklen=32 as module constants pinned by test, self-describing `scrypt$16384$8$1$<salt_b64>$<hash_b64>` rows, `hmac.compare_digest` verify; per-password `secrets.token_bytes(16)` salt; zero new deps), `claim_evidence.py` (stdlib registrable-domain normalization — urlsplit hostname + suffix match; the advisory match signal, D-089). HTTP surface in `api/employers.py` (`/v1/employers/*` — session-gated) + `api/employers_admin.py` (`/v1/employers/admin/*` — require_admin imported from marketplace_admin, the billing_admin.py:27 precedent, D-094). No service.py — routes compose the store via `deps.py` app.state DI (`get_employer_store`, the "routes never import stores directly" territory rule).
|
||||
|
||||
**Store (D-087/D-089/D-095, 4 tables on the shared `Settings().db_path`):** `employer_accounts` (id PK, email UNIQUE indexed, password_hash self-describing scrypt string, employer_id UNIQUE nullable-until-claim-approval, created_at), `employer_sessions` (id PK, token_hash UNIQUE — stores ONLY sha256(token), never the token; account_id indexed, created_at, expires_at = login + SESSION_TTL_DAYS), `employer_claims` (id, account_id, employer_id indexed, status pending|approved|rejected, evidence JSON `{account_email_domain, entity_website_domain, match}`, created_at, decided_by, decided_at), `employer_audit_events` (auto id PK, account_id/employer_id nullable indexed, kind/name, detail JSON, operator, created_at — the BillingEventRow audit shape). Mechanics mirror billing/store.py exactly (WAL / synchronous=NORMAL / busy_timeout / foreign_keys pragmas, `sa_type=String/JSON` portable columns, `_validate()`/`_normalize()` hooks, `_as_utc` tz re-labeling, Protocol + SQLiteEmployerStore pair, surfaced IntegrityError, check-first unique patterns — the insert_application precedent; G-304-style single-statement writes where concurrency matters). The `employer_` prefix is mandatory — bare `employer` is marketplace's EmployerRow table. `SQLModel.metadata.create_all` is idempotent: zero migration, the 4 tables join existing DBs at next boot (the proven billing-store compat).
|
||||
|
||||
**Session flow (D-087/D-090):** register (email+password, UNVERIFIED per D-097 — no learner gates, no email verification; scrypt hash via passwords.py) → login mints `secrets.token_urlsafe(32)`; the row stores `sha256(token)` + expires_at = now + 7-day module constant (lazy TTL at read — G-306, no timer); the client persists the opaque token in sessionStorage `nc-employer-session` (the G-308 adminToken wrapper pattern) and attaches `Authorization: Bearer <token>` on every fetch (CSRF-immune by construction — no ambient credential; D-039 static export has no Next middleware). The `require_employer_session` dependency (the require_admin extract→verify→return shape): **401** on missing/expired/unknown token (credential failure), **403** reserved for cross-entity authorization; returns session + account + claimed employer_id. logout DELETEs the row + audit event (revoke = lookup miss → 401); multiple concurrent sessions per account allowed. Token namespaces cannot collide: admin routes compare against the env token, employer routes hash-lookup.
|
||||
|
||||
**Auth throttling (D-088, G-5 in-memory pattern):** (a) per-EMAIL failed-login window — Settings knob, default 5 failures / rolling 15 min → 429, successful login clears the email's window; (b) global per-min cap on login+register attempts (the `_check_global_create_rate` deque) → 429. Keyed by SUBMITTED EMAIL, never client IP (behind HAProxy the proxy owns request.client.host). Both copy the proven deque/monotonic-window mechanics (identity _SubmitRateLimiter + sandboxes global cap); test fixtures reset the module state.
|
||||
|
||||
**Claim flow (D-089):** authenticated `POST /v1/employers/claims {employer_id}` → claim row status=pending with computed evidence (stdlib domain normalization; every seeded employer website is an example.com placeholder → match=false corpus-wide — the signal is advisory, A-304) → operator reviews in the admin queue → approve sets employer_accounts.employer_id (UNIQUE — one account : one entity) + decided_by/decided_at + audit event; reject frees the entity for a new claim. One PENDING claim per entity + one APPROVED owner per entity enforced check-first in the store. Auto-approval deferred: without email verification the match is forgeable — the operator decision activates.
|
||||
|
||||
**Entitlement composition (D-091) — one shared helper, two principal gates:**
|
||||
|
||||
```
|
||||
admin arm: require_admin ──▶ consume_posting_entitlement(store, employer_id, admin-CTA) ──▶ insert
|
||||
employer arm: require_employer_session ──▶ claim check (403) ──▶ same helper(session employer, employer-CTA) ──▶ insert
|
||||
|
||||
helper: store-missing → 503 fail-closed
|
||||
NoActivePackage → 402 {reason: no_active_package, posts_used: 0, posts_limit: 0, upgrade_cta}
|
||||
PackageExhausted → 402 {reason: posting_limit_reached, posts_used: 0, posts_limit: 0, upgrade_cta}
|
||||
(posts_used/posts_limit hardcoded 0 in BOTH arms — the v0.9 wire contract, byte-identical;
|
||||
UpgradeRequiredError consumes reason + upgrade_cta unchanged; gate runs BEFORE insert)
|
||||
```
|
||||
|
||||
`consume_posting` (G-304 single conditional UPDATE) is untouched; the helper lives in api/ beside both callers (no billing/→api/ boundary violation).
|
||||
|
||||
**Employer checkout (D-091, transposes billing_admin.create_checkout):** `POST /v1/employers/billing/checkout {item_id}` — session-gated; unclaimed → 403 + claim-CTA; buyer = the session's claimed entity (supersedes D-076 operator mediation); catalog snapshot + unique-pending placeholder + CheckoutSessionSpec metadata employer_id=claimed entity, operator_ref→account provenance; success/cancel URLs from public_base_url (G-310); employer mock-complete arm mounted only under provider=mock, employer-session-gated, completing one's OWN session (403 cross-session), minting the signed event through the REAL webhook path (D-082 transposed). The v0.9 provider protocol/webhooks/store grants serve employer checkouts verbatim — only principal derivation changes.
|
||||
|
||||
**Web (D-092/D-093, engine-client employer section — no new client module):** `engine-client.ts` gains register/login/logout/me, claim, own-postings CRUD/publish/close, own-checkout, own-entitlement + a `SessionRequiredError` (401 discrimination — parseError today has no 401 arm; honest logged-out state, never a retry loop) + the `nc-employer-session` sessionStorage wrapper (the adminToken pattern; logout clears storage + calls revoke; AbortController everywhere). Conversion scope: postings page (own-postings lifecycle), overview page (real active-postings count + per-posting applicant counts from the applications table; talent-match/placement metrics stay mock-labeled), employer profile (claimed entity via the existing public GET), new /employer/login + /employer/register (greenfield — no login page exists in any route group); **talent search + candidate profile stay the v0.1 mock** (no candidate backend — D-092). Wire types in `packages/types/employer.ts` dual-schema-pinned in pins.test.ts (the billing.ts pin block template, D-093). Pricing CTAs convert from contact-path to employer-login path (supersedes D-079).
|
||||
|
||||
**Admin network overview (D-094):** the moderation page (app/(admin)/admin/moderation/page.tsx — where the v0.9 EmployerEntitlementPanel landed) gains sibling sections below it: employer accounts list (email, claimed entity, entitlement state), claim queue (evidence + domain-match signal, approve/reject), audit — fed by operator routes in api/employers_admin.py (require_admin + audit events): GET /v1/employers/admin/accounts, GET …/claims, POST …/claims/{id}/approve|reject, GET …/audit; web transport via the existing adminToken() G-308 wrapper + honest 403 locked states (the entitlement panel's locked-state pattern).
|
||||
|
||||
**Settings/wiring (D-095/R-60):** throttle knobs as Settings ints (the identity_submits_per_min shape) + .env.example entries beside AI_ADMIN_TOKEN; session TTL is a module constant (no env). main.py: employer_store lifespan wiring (the billing_store getattr-guard template, ~line 182-190) + close() in the finally block; employers + employers_admin routers mount beside the billing block (inline-import pattern); CORS `allow_headers` gains "Authorization" (main.py:341) with a tests/api/test_cors.py preflight pin — the E87 lesson applied before it ships this time. scrypt probe-verified in the shipped venv (3.11.2): ~50 ms/hash at D-086 params, default maxmem admits the 16 MiB working set.
|
||||
|
||||
### v0.8 Distribution & Release Architecture (Phase 0 RESEARCH — Ship Anywhere, D-063..D-072 binding)
|
||||
|
||||
**Runner fleet topology (CT 113, 10.0.0.113):** three org-level gitea-runner containers (official image `docker.io/gitea/runner:3` — the Docker Hub `gitea/act_runner` repo is deprecated, renamed `gitea/runner`) in **sibling-container mode**: each mounts the host `/var/run/docker.sock`, has its OWN `/data` volume holding the `.runner` registration file (identity + credentials; shared state = re-registration), registers once against `https://git.coreci.dev` (Gitea 1.26.1, probe-verified) with the founder-provided org-level registration token (chat-only, reset after fleet green). Hybrid labels via `GITEA_RUNNER_LABELS`: `node` → `docker://node:24-bookworm`, `python` → `docker://python:3.11-bookworm`, `release` → `docker://node:24-bookworm`, `ubuntu-latest` → `docker://docker.gitea.com/runner-images:ubuntu-latest` (label format `name[:schema[:args]]`; a job's `runs-on` matches label names, the `docker://` image selects the job container). Per-runner `runner.capacity: 1` (default; also caps per-job docker subnet consumption) → fleet concurrency 3. Cache: each runner's built-in cache server must be pinned to a job-reachable `cache.host` + fixed published port (dockerized runners otherwise create per-job networks the cache address is unreachable in — `actions/cache` fails ETIMEDOUT); 32 GB disk guarded by `cache.repo_size_limit`, `health_check.min_free_disk_space_mb`, and a host-side `docker system prune` cron. Workspace-path alignment inside/outside the runner container is NOT needed for our jobs (no `container.bind_workdir`; `docker build` TARS the context over the API) — documented as the known sibling-mode gotcha if a future workflow bind-mounts.
|
||||
|
||||
**Workflow lanes (`.gitea/workflows/`):** push lane on `on: push` (all branches) — node lane (label `node`): corepack pnpm 12.3.4 → `pnpm install --frozen-lockfile` → eslint + tsc via `pnpm --filter` over the 5 TS workspaces (never wholesale `turbo lint`, which pulls the venv-dependent ai-service task) → `pnpm web:test` + `pnpm cli:test`; python lane (label `python`): `scripts/bootstrap.sh` venv → `scripts/lint.sh` (ruff) → `scripts/typecheck.sh` (mypy) → `FAST=1 scripts/test.sh` (fast subset `-m "not real_server and not userns"` per D-063 — real_server/userns NEVER in job containers; docker's default seccomp blocks nested `unshare --user` there anyway); ubuntu-latest lane: workflow_dispatch hello-world only (fleet verification, REQ-8-001). Tag lane on `on: push: tags: ['v*']` is the EXCLUSIVE owner of release assets + registry push (D-064): builds from the tag checkout (jobs never have `dist/`), stamps `build:binary` with `gitea.ref_name`, attaches binaries + debs + checksums via the same REST API scripts/release-assets.sh uses (`GET /releases/tags/{tag}` → `POST /releases/{id}/assets`), never `actions/upload-artifact`. Secrets: `REGISTRY_TOKEN` + `GITEA_TOKEN` as org/repo Actions secrets (self-serve `PUT /api/v1/repos/…/actions/secrets/{name}` first, founder UI fallback); the automatic per-job `GITEA_TOKEN` CANNOT publish packages (upstream-confirmed) — the PAT secret is the only viable registry credential. pnpm/pip caches via `actions/cache@v4` (runner 3.x serves cache v2 + self-patches stock actions ≥4.2/4.4) once cache-host pinning is live; deterministic fallback = volume-mounted stores via `container.options` + `valid_volumes`.
|
||||
|
||||
**Image layers (multi-stage Dockerfile, `git.coreci.dev/coreci/nextcraft`, amd64 only per D-069):** deps/build stages — web export stage (`node:24-bookworm`, `NEXT_PUBLIC_AI_SERVICE_URL=self pnpm build` → `apps/web/out`, ~16 MB; the URL is build-time-only, inlined by engine-base-url.ts) + venv stage (`python:3.11-bookworm`, `pip install` prod deps from pyproject — no dev extras); runtime stage `python:3.11-slim-bookworm` (~400–500 MB total with the venv ~130 MB + web export + the D-066 CLI-binary embed at `/usr/local/bin/nextcraft`, ~117 MB): non-root `USER nextcraft`, `AI_WEB_STATIC_DIR=/opt/nextcraft/web` (single-port StaticFiles mount, D-039), `NC_CONTAINER=1` entrypoint marker, `HEALTHCHECK CMD` urllib `GET /health` (slim has no curl), `VOLUME /home/nextcraft/.nextcraft` (state root `~/.nextcraft` = DB `data/nextcraft.db` + `sandboxes/`, env-overridable via `AI_DB_PATH`/`AI_SANDBOX_DIR` with `~` expansion — config.py:39/77/86-93), `CMD uvicorn ai_service.main:app --host 0.0.0.0 --port 8420`. Zero AI_* env needed at build; all real-provider keys stay optional at runtime (G-11 fallbacks). Unprivileged by default; the sandbox fabric honestly degrades inside docker (below).
|
||||
|
||||
**Deb/binary asset matrix (every release, tag-workflow-built):** `nextcraft-linux-x64` + `.sha256` (existing pipeline, build-binary.mjs SEA), `nextcraft-linux-arm64` + `.sha256` (cross-build: esbuild bundle is arch-agnostic; the ONLY arch-specific step is `copyFileSync(process.execPath, out)` — replaced by a copy from the official `node-v<ver>-linux-arm64.tar.xz` base, probe-verified 200/30 MB; postject adds an ELF note, pure file surgery, never runs the target — QEMU-free per D-69, optional binfmt `--version` smoke if binfmt is registered on CT 113), `nextcraft_<ver>_amd64.deb` / `nextcraft_<ver>_arm64.deb` + `.sha256` (`dpkg-deb --root-owner-group -Zxz`, never executes payload → cross-arch safe; control fields: Package nextcraft, Version = tag minus `v` (policy-clean), Architecture per build, empty Depends, `Recommends: nodejs (>= 18), python3 (>= 3.11), git, util-linux` — soft deps, D-067), binary at `/usr/bin/nextcraft`, postinst = advisory `nextcraft doctor` (never fails dpkg) + next-steps, NO systemd unit (`deploy --service` owns unit generation) + NO proxy fragments. install.sh arch-gate becomes arch-resolve (`x86_64`→x64, `aarch64|arm64`→arm64; sha256 + version integrity gates unchanged). Image tags per D-065: semver `<tag>` + `latest` on newest release, no per-push tags.
|
||||
|
||||
**Channel upgrade semantics (D-071):** docker = `docker pull git.coreci.dev/coreci/nextcraft:<tag>` + recreate the container (state persists in the named `nc-state` volume); `deploy`/`bootstrap`/`dev` refuse in-container (D-066 — container check before the repo-root checks, pointer to the docker paths; `doctor`/`verify`/`guide` remain allowed, `verify` gains a container-mode branch checking the mounted web dir + `/health` instead of a repo clone). deb = `dpkg -i` the new deb + `nextcraft deploy --service` (idempotent v0.4.6 rail). binary = re-run install.sh + `nextcraft deploy --service`. doctor detects the channel (NC_CONTAINER/`/.dockerenv` for docker; `dpkg -s`/`/usr/bin/nextcraft` for deb) and describes its upgrade path; `nextcraft guide` serves offline-first embedded man-page text channel-appropriately (D-072 — TS constants bundled by esbuild into the SEA binary, zero runtime fetches).
|
||||
|
||||
**Sandbox degrade in containers (D-068):** capability probe promoted verbatim from tests/helpers/userns.py into `ai_service/sandbox/capability.py` (`userns_available()` = `shutil.which("unshare")` guard + real `subprocess.run(["unshare","--user","--map-root-user","true"])`) — the truth source at boot + per-create; container markers (`/.dockerenv`, `NC_CONTAINER=1`, cgroup string) only flavor remediation text. Degrade: boot notice (the main.py:404 mount-less / main.py:202 admin-token G-11 warning pattern), learner sandbox create rejects honestly with 503 + remediation pointer (a new `except SandboxUnavailableError` arm beside the existing `PoolFullError→503` in api/sandboxes.py:157-160 — today it would 500), doctor surfaces the degraded capability via a real userns attempt (upgrading the `which unshare` check, doctor.ts:138-150); chat/agents/grading untouched. Supersedes A-101's cwd-jail fallback for deployed schools (never implemented — no code removal needed).
|
||||
|
||||
**Pre-commit rails (D-070):** ONE root `.pre-commit-config.yaml`, local hooks only (ruff on Python paths; eslint/tsc via workspace-scoped invocations), no network at hook run; missing toolchain = loud failure, never silent skip; CI is the authoritative backstop.
|
||||
|
||||
### Confirmed Technology Stack (v0.2)
|
||||
|
||||
| Technology | Version | Purpose |
|
||||
@@ -126,6 +203,7 @@ Deliberately **not** used: openai-python SDK (the `LLMProvider` protocol is the
|
||||
| `ai_service/variants/` | `templates.py` (task template library; v0.5 REQ-5-005/D-044: `environment: Literal[build,design,simulation]` registry + per-kind starter files + harness/test commands, G-15 shlex-roundtrip validation), `generator.py` (seeded LLM instantiation D-029), `store.py` (VariantStore; idempotent `_ensure_v05_columns` backfill for pre-v0.5 DBs) | LLM via structured output | llm, grading |
|
||||
| `ai_service/voice/` | `base.py` (VoiceProvider protocol D-030), `browser.py` (native SR/TTS fallback descriptor), `mock.py` (deterministic), `openai_audio.py` (v0.5 REQ-5-001, D-040: real server STT/TTS against OpenAI-compatible `/audio/transcriptions` + `/audio/speech` on the shared httpx pool — CUT-1/G-7 seam CLOSED), `factory.py` (provider selection by `AI_VOICE_PROVIDER`, G-11 boot-safe fallback to mock), `defense_store.py` (DefenseStore: transcripts + integrity signals, D-027) | Never imports agents/ or api/ | config |
|
||||
| `ai_service/identity/` | **v0.5 NEW (REQ-5-003/004, D-042/43):** `base.py` (IdentityProvider protocol: submit/poll/verify), `mock.py` (deterministic approve-on-policy mock; verdicts carry a `mock` marker, A-304), `store.py` (5th D-027 store: identity_record table — derived `age_band`, document **refs**, PII never stored raw); age-gate dependencies `require_verified_age`/`require_verified_adult` (gate composition D-043: G-5 allowlist → identity verdict → rate caps; mounted on variants/sandbox-create/defense-start + the G-18 marketplace stub), exposed via `api/identity.py` (`/v1/identity/*`) | Never imports agents/; api/ composes it via DI | config |
|
||||
| `ai_service/marketplace/` | **v0.6 NEW (REQ-6-001..006, D-048..D-056):** `base.py` (pydantic contracts: Posting/Employer/PostingTags/IngestPosting), `store.py` (6th D-027 store, SIX tables per G-104: posting/employer/embedding/application/employer_enrichment/learner_profile), `ingest.py` (PostingSource protocol + seeded corpus, idempotent upserts G-102), `tagging.py` (D-020 one-shot tag extraction, overwrite semantics D-052), `embedding/` (EmbeddingProvider protocol + deterministic feature-hash mock + OpenAI-compatible real path + G-11 factory, D-051), `search.py` (hybrid facet+cosine ranking, embed-on-publish, skill_breakdown), `enrichment.py` (append-only provenance rows + merge-on-read manual>llm>raw, D-053), `resume.py` (pypdf text extraction + bounds + D-020 draft extraction, D-054); HTTP surface in `api/marketplace.py` (public + apply + resume), `api/marketplace_admin.py` (fail-closed D-057), `api/marketplace_shells.py` (G-101 catch-all), `api/sitemap.py` (dynamic sitemap/robots, D-056) | Never imports agents/ or api/; api/ composes via DI | config |
|
||||
| `ai_service/agents/examiner.py` | Seventh agent: oral defense examiner; streams over existing SSE, consumes process traces + emits integrity signals | reuses BaseAgent (D-018) | llm, prompts, telemetry |
|
||||
| `ai_service/data/*.db` | SQLite databases (telemetry/grades/variants/defenses) — **v0.3.6: default moved to `~/.nextcraft/data/nextcraft.db` (state out of the repo; AI_DB_PATH overrides, ~ expanded)** | outside repo (home) | — |
|
||||
| `scripts/sandbox-agent.py` | Tiny in-namespace capture process shipped into the sandbox; streams telemetry to ingest | standalone | stdlib only |
|
||||
@@ -290,4 +368,4 @@ v0.4 delivers distribution (CLI + binary releases); later milestones fill in the
|
||||
- **No search → Semantic vector search (pgvector)** — Filter UI replaced with vector similarity search
|
||||
- **No payments → Payment processing** — Pricing page replaced with real subscription/payment flows
|
||||
|
||||
The monorepo structure (apps/web + apps/ai-service + apps/cli + packages/*) accommodates further apps without restructuring.
|
||||
The monorepo structure (apps/web + apps/ai-service + apps/cli + packages/*) accommodates further apps without restructuring.
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
{
|
||||
"phase": 3,
|
||||
"stage": "verify",
|
||||
"milestone": "v0.6",
|
||||
"milestone_name": "marketplace-engine",
|
||||
"phase_role": "execution",
|
||||
"attempts": 0,
|
||||
"updated_at": "2026-09-22T01:45:00Z"
|
||||
}
|
||||
@@ -1,3 +1,48 @@
|
||||
# Nextcraft v0.9 — GRILL.md (Adversarial Review Verdict)
|
||||
|
||||
**Stage:** GRILL, Phase 0 pre-execution · **Verdict:** GO-WITH-BINDINGS (REVISE → record G-301..G-310, then SHIP) · **Confidence:** 0.85 · **Date:** 2026-09-29
|
||||
|
||||
## Summary
|
||||
|
||||
The v0.9 Payment Engine plan (5 requirement phases + final, D-074 locked) is feasible, correctly scoped, and hermetically testable — the operator-mediated checkout model is coherent end-to-end and entitlement needs no employer auth. But red-teaming against the working tree (not the plan's description of it) found 10 binding defects: a mock-complete route mounted on every default-config production box (D-082's "never on a real deployment" rationale is **false** — mock IS the default), webhook handlers that would trust forgeable event payloads (leaked secret = free entitlements), a check-then-increment race in consume_posting, event-id-only dedupe defeated by Stripe's dual invoice events, a phantom `upgraded` state with no transition rows, an un-pinned ingest bypass that would 402 the seeded corpus, a checkout route naming contradiction between REQUIREMENTS/ROADMAP and binding D-076, an admin panel requiring a browser token entry that exists nowhere in apps/web, and a stripe checkout that cannot create sessions (success_url never populated — Happy Path 5's "zero code changes" was false). Two plan citations proved wrong in-tree (the "sitemap env-gated routes" precedent does not exist; admin surface has zero admin-token plumbing). Two Gs bite inside P1's Task 1-1-02 — recording them now prevents store-schema retrofit churn after P1 ships. Nothing re-architects: every G amends an existing task, must-have, or requirement sentence; the phase/wave structure is untouched.
|
||||
|
||||
## Per-Axis Findings
|
||||
|
||||
| # | Axis | Verdict | Reason |
|
||||
|---|------|---------|--------|
|
||||
| 1 | Feasibility | PASS | Operator-mediated checkout coherent end-to-end; entitlement composes after require_admin with employer_id as body field; 6-phase shape matches the proven v0.6 cadence |
|
||||
| 2 | Scope creep | CONCERN | REQ-9-003/ROADMAP name a public POST /v1/billing/checkout contradicting D-076 (G-307); admin panel hides a browser-token requirement (G-308); "stripe switch = zero code changes" false without success/cancel URLs (G-310) |
|
||||
| 3 | Security | CONCERN | Mock-complete route unauthenticated on default deployments (G-301); webhook state resolution unspecified — payload trust = forged entitlements (G-302) |
|
||||
| 4 | Correctness | CONCERN | consume_posting check-then-increment race (G-304); dual invoice events defeat event-id dedupe (G-303); `upgraded` state hole (G-305); out-of-order events against missing targets + grace timing unspecified (G-306) |
|
||||
| 5 | Testability | PASS | Hermetic by construction: MockTransport byte-contracts, now-injection, direct-handler-call mock-complete — provided G-306 keeps grace lazy |
|
||||
| 6 | Backward compat | PASS | Fixture strategy workable (~9 test sites grant unlimited to legacy seeded employers); pricing metadata pin survives conversion; ingest bypass unpinned → G-309 |
|
||||
| 7 | Cost/benefit | PASS | D-074 stands: payments unblocks employer self-serve; no new deps (hand-rolled REST, no Stripe SDK); challenge declined |
|
||||
| 8 | Plan-vs-reality | PASS (with corrections) | All cited patterns verified in-tree; two rationale citations false (G-301/G-308); suite count 674/625-fast drift noted |
|
||||
|
||||
## Binding Decisions (G-301..G-310 — applied to PLAN/REQUIREMENTS/ROADMAP before execute)
|
||||
|
||||
**G-301 — mock-complete route: admin-gate it; D-082's "never on a real deployment" rationale is false.** The default provider is mock (D-075) and the pilot IS a real deployment — `POST /v1/billing/mock/complete` mounted "only when provider=mock" is mounted on every default-config production box. An unauthenticated completion route on a payment surface is a hole no matter how unguessable `cs_mock_…` ids are. Decision: keep the provider=mock conditional mount AND compose `require_admin` on the route — the operator completing a session after out-of-band payment is exactly the honest pilot flow D-076 describes. Amends PLAN Task 3-2-03, MH-3c; D-082's rationale corrected (ship-notes record: the sitemap "env-gated routes" precedent does not exist — this is the first factory-conditional mount in-tree). Tests: no-token → 403 under mock; route 404s under stripe; E2E green with admin-gated complete. Confidence 0.85.
|
||||
|
||||
**G-302 — webhook events are untrusted ID references; state resolves from local rows.** If checkout.completed reads session status/amount from the event payload, a leaked AI_WEBHOOK_SECRET = free entitlements (forge status=complete, payment_status=paid for any session id). Decision: handlers treat event payloads as ID references only — the session resolves from the local checkout_sessions row (creatable only via the admin route); unknown session id → recorded as an `unmatched` billing_event, NO entitlement, 200. Purchase price/name from the stored snapshot (D-078), never the event body; renewal amounts from the local plan row. Amends Task 3-2-02. Tests: signed checkout.completed with no local row → 200, zero purchases, one unmatched event; inflated payload amount → purchase price = snapshot. Confidence 0.85.
|
||||
|
||||
**G-303 — grants are idempotent per session, not per event id.** R-43/D-083 accept invoice.paid AND invoice.payment_succeeded and Stripe's async path fires distinct completed events — different event ids for the same logical completion sail past event-id dedupe and double-grant. Decision: `purchases.checkout_session_id` gets a UniqueConstraint; subscription upsert keys on provider subscription id; entitlement creation is exactly-once per session regardless of event count. Amends Task 1-1-02 (schema), Task 3-2-02; extends MH-3b. Test: two signed checkout.completed events, different event ids, same session → exactly one purchase row (IntegrityError → created=False), one subscription. Confidence 0.85.
|
||||
|
||||
**G-304 — consume_posting is a single conditional UPDATE, not check-then-increment.** insert_application survives concurrency via UniqueConstraint; posts_used has no such backstop — two concurrent create_posting calls both read posts_used=9 and both increment. Decision: consume_posting = one statement `UPDATE purchases SET posts_used = posts_used + 1 WHERE id = <newest non-expired with remaining> AND posts_used < posts_limit` (rowcount-checked; 0 rows → PackageExhausted/NoActivePackage). Amends Task 1-1-02. Test: 1 post remaining, two concurrent consumes on separate connections (WAL) → exactly one succeeds. Confidence 0.80.
|
||||
|
||||
**G-305 — `upgraded` is not a status state.** D-083's "(+ upgraded)" has no transition-matrix rows and REQ-9-005's canonical states don't include it. Decision: upgrade = plan_id transition within `active` (provider update per R-47 with items[0][id] — pinned by MH-3d), recorded as a billing_event with provenance; `upgraded` removed from the status enum — D-083's "(+ upgraded)" reinterpreted as the auditable upgrade ACTION, not a state. Amends Task 5-1-01, MH-5a. Tests: upgrade on active → status stays active, plan_id changes, billing_event exists; stored-status set contains no `upgraded`. Confidence 0.75.
|
||||
|
||||
**G-306 — out-of-order tolerance includes missing targets; grace expiry is lazy, not a timer.** (a) invoice.payment_failed/invoice.paid can arrive before checkout.completed creates the local subscription — handlers never 500 on unknown targets: record as unmatched (G-302 marker), return 200; recovery is the grant or admin manual complement. (b) past_due → expired at 7 days is computed lazily from past_due_at + 7d at read/entitlement time — no background timer, keeping tests hermetic. Amends Task 3-2-02 (tolerance rule), Task 5-1-01 (grace semantics); risks 3-4. Tests: signed invoice.paid for unknown subscription → 200 recorded no crash; entitlement check with injected now at past_due_at+6d → granted, +8d → 402/expired; no sleeps. Confidence 0.80.
|
||||
|
||||
**G-307 — align REQ-9-003/ROADMAP route naming to D-076.** REQUIREMENTS REQ-9-003 and ROADMAP phase-3 say `POST /v1/billing/checkout`; binding D-076, PLAN, and ARCHITECTURE say `/v1/billing/admin/checkout` behind require_admin. Decision: amend the wording at this gate (the requirement text must not name a public un-gated checkout route that will not exist). Test: route-inventory pin — no /v1/billing/checkout route exists; /v1/billing/admin/checkout 403s without token. Confidence 0.90.
|
||||
|
||||
**G-308 — define the browser-side admin-token entry; the admin panel is otherwise unreachable.** The admin surface is mock-data driven; no X-Admin-Token exists in apps/web. REQ-9-004's "admin surface shows per-employer entitlement state" hides a new requirement: an operator token entry in the browser — Task 4-2-01's A-406 citation is wrong (A-406 is for public routes). Decision: a small token input in the entitlement panel persisted to sessionStorage, sent by a new adminFetch wrapper in engine-client (X-Admin-Token header); 403 renders an honest locked state with the token prompt; the token is never logged. Amends Task 4-2-01. Tests: stubbed 403 → locked-state render; fetch stub asserts the header; no admin-token string in non-test web source beyond the wrapper. Confidence 0.75.
|
||||
|
||||
**G-309 — pin the ingest bypass: seed ingestion is never entitlement-gated.** Enforcement composes into the admin create_posting route ONLY, but the seeded-corpus ingest upserts ~20 postings directly through the store and must never hit the 402 path. Decision: explicit rule + test — run_ingest (and any future adapter) bypasses consume_posting by design; enforcement exists only in the admin route. Amends Task 4-1-01 (test list), risk 5 companion. Test: seeded ingest on a store with zero purchases → 20 postings upserted, zero 402s, zero consumption rows. Confidence 0.90.
|
||||
|
||||
**G-310 — default success/cancel URLs for the stripe checkout, or delete the "env-only switch" claim.** R-34: success_url is required for hosted checkout; the admin checkout body is {item_id, employer_id} and no task populates it — the stripe path cannot create sessions as planned. Decision: the checkout route defaults success_url = {public_base_url}/marketplace/pricing?checkout=success and cancel_url = …?checkout=cancelled (public_base_url exists at config.py:170); loud G-11 boot warning when stripe is selected and public_base_url is unset. Amends Task 3-2-01 (defaults) + Task 3-1-01 (byte-contract asserts both fields). Tests: MockTransport byte-contract shows success_url/cancel_url present; factory-selection test shows the loud warning when stripe + empty origin. Confidence 0.80.
|
||||
|
||||
---
|
||||
|
||||
# Nextcraft v0.6 — GRILL.md (Adversarial Review Verdict)
|
||||
|
||||
**Stage:** GRILL, Phase 0 pre-execution · **Verdict:** GO-WITH-BINDINGS · **Confidence:** 0.72 · **Date:** 2026-09-21
|
||||
@@ -162,3 +207,189 @@ a-6 ack on dedup'd appends too (tight margin); a-7 MH-1d 3× runs = one-time shi
|
||||
## Escalations
|
||||
|
||||
None. All four seams remain founder-locked via D-016 / REQ-5-001..007; every finding resolved at confidence ≥ 0.65.
|
||||
|
||||
---
|
||||
|
||||
# v0.8 GRILL (Phase 0, 2026-09-27) — Ship Anywhere
|
||||
|
||||
**Verdict: GO-WITH-BINDINGS · Confidence: 0.74** — G-201..G-210 binding (3×P0, 7×P1); applied to PLAN.md before P1 execution. (Inline orchestrator grill — three delegated griller runs returned empty; logged per Step 4 error recovery at full autonomy.)
|
||||
|
||||
**Evidence:** every load-bearing plan claim re-verified against RESEARCH.md's probe-backed census (R-1..R-32), the existing v0.4 pipeline code (build-binary.mjs, release-assets.sh, install.sh), and Gitea 1.26.1 live state. The research layer held; findings are interaction-surface and lifecycle gaps.
|
||||
|
||||
## Per-Axis Findings
|
||||
|
||||
| Axis | Verdict | Rationale |
|
||||
|------|---------|-----------|
|
||||
| Goal coverage | PASS | All four founder options map to REQ-8-001..005 with falsifiable MHs; docker-per-phase-upload honored by the release workflow design. |
|
||||
| Feasibility | AT-RISK → fixed | QEMU-free arm64 SEA (R-25/26) probe-first is honest, but the plan pinned no failure exit; G-201 forces a decided fallback ladder. Runner fleet on 4GB is bounded by capacity=1 + label routing (R-4). |
|
||||
| Vertical-slice integrity | PASS | P1 ships a green fleet + live pipelines; P2 ships a pullable image; P3 ships installable assets; P4 ships channel-aware CLI; P5 ships the runbook. Each independently real. |
|
||||
| Wave ordering | AT-RISK → fixed | P2→P3 ordering claimed "forced" but both only extend P1's workflow; G-202 makes the true dependency explicit (asset-matrix ownership) and permits P2/P3 work within the same release lane without re-ordering phases. |
|
||||
| Testability | AT-RISK → fixed | MH-1d asserted workflow-built release assets but the release job runs on the tag push — which exists only at ship time; G-203 defines the within-phase proof (temporary tag on the phase branch). MH-2b smoke gate had no in-container test harness; G-204 pins the concrete assertions. |
|
||||
| Security posture | AT-RISK → fixed | Secrets chain mostly sound (R-6/R-13), but the REGISTRY_TOKEN self-serve PUT needs a value the .env token cannot mint — G-205 forces founder-side PAT creation with scoped package-write, closing a plan-time fantasy. CT root password rotation was "ask founder"; G-206 makes it a recorded P0 completion condition. |
|
||||
| Performance/capacity | PASS | Image budget ~400-500MB (R-18) asserted in smoke gate; 32GB disk bounded by prune cron + cache caps + health_check floor (R-5). |
|
||||
| Operational readiness | AT-RISK → fixed | The runbook (P5) would document a fleet whose bring-up lives only on CT 113; G-207 requires the compose/config/cron committed as fleet-as-code in-repo. Degrade remediation text must name the privileged variant precisely (G-208). |
|
||||
| Dependency risk | PASS | No new product deps; docker.io engine on release lane accepted-risk with documented future fix; corepack fallback decided (R-11). |
|
||||
| Adoption/UX | PASS | Three channels each end at doctor/verify green; guide offline-first with parity test; refusals honest. |
|
||||
|
||||
## Binding Decisions (applied to PLAN.md)
|
||||
|
||||
- **G-201 (P0)** — arm64 build has a decided fallback ladder: probe QEMU-free cross-arch SEA on the runner first; if the blob fails to run under emulation, fall back to binfmt+qemu for FULL arm64 builds (not just blob generation); if the runner can't install binfmt, ship v0.8 with x64-only debs/binaries and record the arm64 deferral — never leave the release lane red or blocked.
|
||||
- **G-202 (P1)** — dependency truth: P2 and P3 both consume P1's release workflow as their extension point; P2 precedes P3 for founder-priority (docker is the headline channel), not technical force. PLAN wave-order paragraph corrected; no phase reorder.
|
||||
- **G-203 (P1)** — release-workflow within-phase proof: MH-1d/D-3d prove via a temporary `v0.7.1-rc1`-style tag pushed to the phase branch head at verify time, workflow observed building + attaching to the (pre-release/draft or immediately-deleted) release, tag then deleted. The phase ship tag remains the real artifact.
|
||||
- **G-204 (P1)** — smoke gate pinned: container starts → /health 200 within timeout → `GET /` content-type text/html AND contains a known marker (not just non-JSON-404) → degrade boot notice present in logs → fabric create returns 503 with remediation → clean stop. All five assertions in the workflow step; failure = red release job.
|
||||
- **G-205 (P0)** — REGISTRY_TOKEN is a founder-minted PAT with package-write scope (the .env GITEA_TOKEN may lack it): P1's self-serve attempt becomes "PUT the secret IF the existing token can mint it — else escalate to founder with the exact scope needed (write:package + write:repository)". The plan must not assume the PUT succeeds; escalation path has a founder question, not a silent wait.
|
||||
- **G-206 (P0)** — CT 113 root password rotation is a P0 completion condition of Wave 1-1: after deploy-key install, the founder is asked to rotate; if not confirmed by Wave 1-2, an `escalation: ct_root_password_still_live` commit lands and the ship notes carry it. Never silently carried.
|
||||
- **G-207 (P1)** — fleet-as-code: the compose file, per-runner configs, and prune cron are committed in-repo (e.g. `deploy/ci/`) as the reproducible fleet definition; CT 113 deployment is a copy + `docker compose up -d` — the runbook's fleet recipe references the committed files, not box memory.
|
||||
- **G-208 (P1)** — degrade remediation text must be exact: name the unprivileged default, the seccomp constraint, the documented privileged/seccomp-override variant (docker run flags), and the host-side alternative (run the stack binary-side); the boot notice and 503 payload carry the same text (single remediation constant, tested).
|
||||
- **G-209 (P1)** — pre-commit hooks must not break contributor boxes lacking the toolchain silently in the other direction either: hooks fail-loud (D-070) but the README dev section documents the exact skip path (`pre-commit run --no-skip` semantics never needed; SKIP=env documented) — a contributor with no ruff gets a loud pointer, not a broken commit flow.
|
||||
- **G-210 (P1)** — the guide parity test (MH-5b) needs a defined source of truth: the runbook's channel sections are the canonical text; `nextcraft guide` renders them via an extracted shared snippet (single source file, generated or duplicated-with-test); divergence = test failure. PLAN Task 5-1-02 mechanism named.
|
||||
|
||||
## Plan Edits Applied
|
||||
|
||||
1. G-201 → Task 3-1-01 fallback ladder + MH-3a reworded (probe → binfmt-full → deferral, never red lane)
|
||||
2. G-202 → Overview wave-order paragraph corrected (P2 precedes P3 for founder priority, not technical force)
|
||||
3. G-203 → Task 1-2-02 + Task 3-2-03 verification mechanism (temporary rc tag, deleted after proof)
|
||||
4. G-204 → Task 2-2-02 five-assertion smoke gate pinned
|
||||
5. G-205 → Task 1-2-04 reworded (founder-minted PAT with package-write; escalation question not silent wait)
|
||||
6. G-206 → Task 1-1-01/1-1-03 rotation condition + ship-notes carry
|
||||
7. G-207 → new P1 Wave 1-1 task (fleet-as-code committed in deploy/ci/)
|
||||
8. G-208 → Task 2-1-02 single remediation constant, tested
|
||||
9. G-209 → Task 1-2-05 README dev-section skip path documented
|
||||
10. G-210 → Task 5-1-02 parity mechanism named (single source, divergence = test failure)
|
||||
|
||||
## Advisories (recorded, no action)
|
||||
|
||||
- a-201: docker.io rate limits on the release lane — bookworm main is fine; watch anonymous pull quotas on job-image pulls (runner-images:ubuntu-latest is docker.gitea.com, not docker.io).
|
||||
- a-202: `GITEA_TOKEN` naming collision (automatic job token vs repo secret of the same name) — Gitea precedent lowest-level-wins; keep the repo secret name `GITEA_TOKEN` per R-13 but document the collision in the workflow comments.
|
||||
- a-203: cache.host on CT 113 IP — if the LXC ever changes IP, cache breaks; fleet-as-code (G-207) documents the IP as a bring-up variable.
|
||||
- a-204: image `latest` tag vs immutable release tags — `latest` is convenience-only; runbook always pins the release tag.
|
||||
|
||||
---
|
||||
|
||||
## v0.10 Grill (Phase 0 GRILL, 2026-09-30)
|
||||
|
||||
**Stage:** GRILL, Phase 0 pre-execution · **Verdict:** SHIP-WITH-BINDINGS · **Confidence:** 0.82 · **Date:** 2026-09-30
|
||||
|
||||
**Verdict summary.** The v0.10 B2B Employer Network plan (6 phases, 15 waves, 30 tasks) is feasible and correctly sequenced — every load-bearing tree citation re-verified against the working code and held (require_admin shape, the 402 gate order + hardcoded zeros, billing_admin checkout/mock-complete mechanics, the four main.py wiring sites, the web census, both throttle precedents, the tests/billing layout, scrypt probe). The researcher's six open risks are each carried by a plan task. But red-teaming found 10 binding defects: a REQUIREMENTS-vs-PLAN gate-order contradiction (REQ-10-004 literally says sessions compose AFTER the entitlement check — backwards, the G-307 class); "web render tests" specified against a harness that does not exist in-tree (D-059 declined it — the tests as written are undeliverable without smuggling in jsdom, violating R-66); a suite-breaking throttle trap (the global 30/min deque is module state shared across every tests/employers/ file — the whole fast suite runs inside one 60s window and 429s itself around test ~16); a credential-stuffing hole hiding in an ambiguous throttle-append rule (if failed passwords don't consume global budget, D-088's stated rationale is void); an EmailStr trap (email-validator is NOT installed — the natural pydantic choice is a boot-time ImportError and the first new dependency); a TOCTOU race on one-pending-claim-per-entity with no UNIQUE backing it (insert_application's check-first is safe only because a real constraint backs it); employer postings that would inherit source="admin" provenance if the admin route is copied; a re-tag fork between admin and employer edit paths (D-052 drift); a dual-schema pin pointed at contracts no task creates (the own-postings response has no named pydantic model); and a UX criterion inviting the executor to "fix" the 402 wire zeros (risk 7 stated as acceptance criteria). All ten amend existing tasks — nothing re-architects, no scope cuts required.
|
||||
|
||||
## Per-Axis Findings
|
||||
|
||||
| # | Axis | Verdict | Reason |
|
||||
|---|------|---------|--------|
|
||||
| 1 | Feasibility | CONCERN → fixed | All citations verified in-tree; but 4 tasks assume things the tree doesn't have: a render harness (G-312), EmailStr's dependency (G-315), a backing constraint for the claim 409 (G-316), a named own-postings pydantic contract for the MH-3a pin (G-319) |
|
||||
| 2 | Scope | PASS | Big but REQ-mandated, heavy precedent reuse (the v0.6 46-task cadence); talent pages honestly left mock; no half-built surface found; no CUTs |
|
||||
| 3 | Security | CONCERN → fixed | New trust-boundary code mostly well-specced (hashed tokens, lazy TTL, email-keyed throttles, 422 scrub, own-session mock-complete); defects: throttle-append ambiguity voids the stuffing bound (G-314), throttle-vs-KDF order unspecified (G-320a), claim insert race (G-316) |
|
||||
| 4 | Honesty | CONCERN → fixed | "Render tests" would present source pins as render tests or force a harness dep (G-312); employer postings inheriting source="admin" is provenance dishonesty (G-317); UX criterion 3 contradicts the byte-stable 402 zeros (G-320b) |
|
||||
| 5 | Drift | CONCERN → fixed | D-091 pins strong (payload-parity test + unchanged v0.9 suite); but the own-postings dual-schema pin has no pydantic contract to pin against (G-319), and employer edit would fork the admin re-tag semantics (G-318) |
|
||||
| 6 | Sequencing | PASS | Wave order verified dependency-sound (P1 module → P2 claims → P3 surface → P4 writes → P5 money); pins land against base.py contracts, not pages — no hidden dependency |
|
||||
| 7 | Researcher open risks | PASS | All six (scrypt burst, CORS preflight, 422 echo, sessionStorage, mock-complete own-session, example.com evidence) carried by named tasks with pins |
|
||||
| 8 | Test coverage | CONCERN → fixed | Several must-haves unverifiable AS WORDED (render tests, G-312); the employers suite self-DOSes without a conftest-wide reset (G-313); stuffing untested (G-314) |
|
||||
| 9 | One-entity/one-account races | CONCERN → fixed | One-APPROVED-owner is structurally sound (employer_accounts.employer_id UNIQUE → IntegrityError, pinned); one-PENDING-per-entity is check-first with NO backing constraint — TOCTOU (G-316) |
|
||||
| 10 | Token entropy + storage | PASS | token_urlsafe(32) = 256-bit CSPRNG, sha256-at-rest, lazy 7-day TTL, revoke-on-logout, concurrent sessions — matches D-087 exactly; no finding |
|
||||
|
||||
## Binding Decisions (G-311..G-320 — applied to PLAN/REQUIREMENTS before execute)
|
||||
|
||||
**G-311 — REQ-10-004's gate-order wording is backwards; the session gate composes BEFORE the entitlement check.** REQ-10-004 says "employer sessions compose AFTER the existing entitlement enforcement" — literally: an unauthenticated caller hits the 402 gate before the 401, leaking entitlement state to anonymous callers and breaking the web client's SessionRequiredError-vs-UpgradeRequiredError discrimination (a 402 on an expired session renders an upgrade CTA to a logged-out visitor — a lie). The plan (Task 4-1-02, R-58) has the correct order; the requirement text contradicts it (the G-307 class: requirement prose naming a composition that must not exist). Decision: amend REQ-10-004 to "the entitlement check composes AFTER the employer session gate (401/403 precede any 402 — the R-58 admin-gate-first order preserved)". Applies to: REQUIREMENTS REQ-10-004; PLAN Task 4-1-02 (amendment note). Test: unauthenticated create → 401 (never 402); unclaimed-session create → 403 (never 402). Confidence 0.85.
|
||||
|
||||
**G-312 — no render harness exists in-tree: page/component tests are fetch-stub + source-pin, never "render tests".** Tasks 3-3-01/3-3-02 say "fetch-stub render tests" / "web render tests" — D-059 explicitly declined jsdom/happy-dom (v0.7, founder-scoped), the billing-entitlement.test.ts template's own header says "no render harness in-tree", and adding one is a new dependency violating R-66's zero-dep claim. As written, the executor either smuggles in jsdom or ships tests whose names lie about what they verify (the A-304 class). Decision: every "render test" is reworded to the D-059/E87 discipline — fetch-stub tests over engine-client employer functions (401 → SessionRequiredError, token header attached, logout revoke+clear) + source pins for component honest states (logged-out/claim-pending/loading/error branches present in source, the pins.test.ts discipline); jsdom/happy-dom are BANNED this milestone. Applies to: PLAN Tasks 3-3-01, 3-3-02 (amendment notes; 4-2-01/5-2-01/5-2-02 already say "web fetch-stub" — their loose "render" phrasing is covered by this G); MH-3b/3c/3e and MH-5c/5e read under this discipline. Confidence 0.85.
|
||||
|
||||
**G-313 — both throttle limiters reset via a SUITE-WIDE autouse fixture in tests/employers/conftest.py.** The global cap (default 30/min) is module-level process state (R-63); the entire tests/employers/ suite — register+login flows across test_auth, test_claims, test_claims_admin, test_postings_read, test_postings_write, test_checkout, test_checkout_e2e — runs in ONE process in well under 60 seconds, i.e. inside ONE window: ~90+ auth attempts against a 30-cap → guaranteed mid-suite 429s cascading through every downstream test. The plan places reset fixtures only in test_throttle.py's test list. Decision: tests/employers/conftest.py (a NEW file — the sanctioned deviation from billing's no-conftest layout, R-64) carries an autouse fixture clearing BOTH limiter module states before/after EVERY employers test; the per-file fixtures in test_throttle.py stay for its own window-math. Applies to: PLAN Task 1-2-02 (amendment note), D-096 operationalization. Test: the suite itself (it cannot pass without this — the trap is self-revealing but only after a day of flaky archaeology). Confidence 0.85.
|
||||
|
||||
**G-314 — the global cap counts every well-formed attempt, including failed passwords — or D-088's rationale is void.** The plan's "append only after ALL checks pass (a rejected attempt never consumes budget)" is copied from the sandbox create-cap, where "rejected" means server-rejected-by-validation. Read against auth, "all checks pass" plausibly includes password verification — under that reading, failed logins consume nothing and credential stuffing with rotating emails (the exact attack D-088 names: "bounding cross-email credential-stuffing volume") is UNBOUNDED, and the planned test "rejected attempts don't consume the global budget" would PIN the hole. Decision: the global deque appends for every well-formed login+register request that passes body validation, BEFORE the KDF runs — successes and failed passwords both consume budget; only 422-invalid bodies and the cap's own 429s are exempt; the per-email window keeps failures-only semantics. The test is reworded: "422-invalid attempts consume nothing; FAILED-PASSWORD attempts DO count; N distinct emails inside the window → the (cap+1)-th 429s (stuffing test, knob set low)". Applies to: PLAN Task 1-2-02 (amendment note), MH-1d. Confidence 0.75.
|
||||
|
||||
**G-315 — email fields are plain str with stdlib validation; pydantic EmailStr is BANNED.** email-validator is NOT in the venv (pyproject carries only pydantic/pydantic-settings; no in-tree email-validation precedent exists — identity keys on learner_id). Using pydantic's EmailStr in RegisterEmployerRequest/LoginEmployerRequest — the natural choice for "email + password, honest validation" — raises at model-build/validation time ("email-validator is not installed"), and fixing it means the FIRST new dependency, breaking R-66/D-086's zero-dep claim and the mypy zero-override regime. Decision: email is `str` with stdlib-only validation (non-empty, exactly one "@", non-empty domain, lowercased + stripped on normalize — mirrored in the store's _validate hook); the evidence domain extraction (R-65) already handles the parse. Applies to: PLAN Task 1-1-01 (amendment note). Test: register accepts "User@Example.COM" (normalized), rejects "not-an-email" with an honest 422 that never echoes the password (rides the G-312/1-2-03 pin). Confidence 0.85.
|
||||
|
||||
**G-316 — one-pending-claim-per-entity gets a structural backstop, not just check-first.** insert_application's check-first insert is race-safe ONLY because UniqueConstraint(posting_id, learner_id) backs it; "one PENDING claim per entity" is a CONDITIONAL uniqueness (rejected claims on the same employer_id are legal — "rejection frees the entity"), so no table-level UNIQUE exists and two concurrent claim POSTs both pass the check and both insert. Two threads reach the store (FastAPI sync endpoints run in a threadpool; the store uses check_same_thread=False per-call Sessions) — the 409 promise is TOCTOU. The one-APPROVED-owner arm IS structurally sound (employer_accounts.employer_id UNIQUE → IntegrityError, already pinned) — this G covers only the pending arm. Decision: `employer_claims.__table_args__` gains `Index("uq_pending_claim_per_entity", "employer_id", unique=True, sqlite_where=text("status = 'pending'"))` — SQLite supports partial indexes and SQLAlchemy emits them via create_all (the D-095 one-time path); insert_claim keeps its check-first 409 fast-path and SURFACES the IntegrityError as the same honest 409 under race. Applies to: PLAN Tasks 1-1-02 (schema), 2-1-02 (amendment note), MH-2c. Test: pin the partial index exists in sqlite_master; second concurrent-pending insert → 409 (store test surfaces IntegrityError, never a duplicate pending row). Confidence 0.75.
|
||||
|
||||
**G-317 — employer-created postings stamp their own provenance, never source="admin".** Task 4-1-02 mirrors the admin create route, whose Posting construction hardcodes `source="admin"`, `id=f"adm-…"`, `external_id=f"adm-…"` (marketplace_admin.py:221-243). Copied wholesale, an employer-authored posting presents as operator-authored — corpus provenance lies (A-304: the v0.6 ingest contract means source distinguishes seeded vs admin-authored; a third principal class silently inheriting the admin label makes "who wrote this" unanswerable and muddies the audit story the milestone sells). Decision: employer create stamps a distinct source (e.g., `source="employer"`) with its own id/external_id schemes (`emp-…`), keeping the (source, external_id) upsert identity unambiguous across all three authorship classes; the admin routes are untouched. Applies to: PLAN Task 4-1-02 (amendment note). Test: employer-created posting persists with the employer source stamp (pinned); admin routes still stamp "admin". Confidence 0.80.
|
||||
|
||||
**G-318 — employer edit composes the SAME re-tag path as the admin edit; no tag-semantics fork.** The v0.9 admin edit (PUT /v1/marketplace/admin/postings/{id}) calls update_posting_fields then re-tags via tag_posting — D-052: tags are DERIVED data, overwritten on edit. Task 4-1-02's employer PATCH specifies the own-drafts guard but is silent on re-tagging: an executor shipping edit-without-re-tag leaves employer-edited postings with stale tags — derived data drifting from content, a D-052 violation and a search-facet integrity hole (the exact drift class D-091 exists to prevent, on the tagging axis). Decision: the employer edit route composes the identical update_posting_fields + tag_posting path (tag failure honest — edit stands, tags stay, warning logs — the admin contract), with the own-drafts-only guard evaluated BEFORE the mutation (published/closed → 409 without side effects); PATCH-vs-PUT method naming is free choice. Applies to: PLAN Task 4-1-02 (amendment note). Test: employer edit on a mock provider re-tags (tags updated or TaggingUnavailable-swallowed-pinned); edit published → 409 AND no field/tag mutation occurred. Confidence 0.70.
|
||||
|
||||
**G-319 — the own-postings response is a NAMED pydantic contract; applicant data is COUNTS ONLY.** MH-3a/G-108 pins assert employer.ts against "ai_service/employers/base.py's pydantic contracts — both schemas", but no task's contract list includes the own-postings response: Task 1-1-01 names Account/Claim/Register/Login/Token/Me; Task 3-1-01 describes the route's payload in prose. The pin as specified either pins against nothing (a weak dict-shape grep) or blocks on a contract nobody was told to write. The route also needs a data source the plan doesn't name: applicant_count per posting, while the marketplace store's only read is list_applications(posting_id) — a per-posting N+1 across the employer's postings. Decision: (a) Task 3-1-01 adds named contracts to employers/base.py — `OwnPostingSummary` (PostingSummary reused from marketplace, PLUS applicant_count) and the facets/list response — so the MH-3a pin is schema↔schema; (b) the count rides a new in-pattern marketplace store read (e.g., `count_applications_by_posting(posting_ids) -> dict[str, int]`), never an N+1; (c) explicitly pinned: employer-facing responses expose applicant COUNTS ONLY — learner identifiers NEVER appear in any /v1/employers/* response (PII boundary, security-auditor P3/P5 review scope). Applies to: PLAN Tasks 1-1-01 (contract list), 3-1-01 (amendment note), 3-2-01, MH-3a. Confidence 0.80.
|
||||
|
||||
**G-320 — throttle-before-KDF order (a) and the 402 zeros are wire-only, never displayed truth (b).** (a) R-55's open risk (login bursts stack ~50 ms scrypt) is bounded ONLY if both throttle checks run BEFORE the derivation — a 429'd or globally-capped attempt must never burn KDF CPU. The plan never states the check order inside the login route. (b) UX acceptance criterion 3 says "limits shown are the store's truth" while the 402 payload hardcodes posts_used=0/posts_limit=0 (byte-stable per D-091/MH-4a) — as written the criterion invites the executor to "improve" the zeros (risk 7) or to render "0/0" as real limits (a lie). Decision: (a) route order is body-validation → global cap → per-email window → scrypt verify → failure-append (pinned: a 429'd attempt performs zero derivations); (b) criterion 3 reworded — the 402 payload carries reason + CTA only; real limits render exclusively from GET /v1/employers/billing/entitlement (the entitlement view is the limits truth source, Task 5-1-01). Applies to: PLAN Task 1-2-02 (a, amendment note), Task 4-2-01 + UX criterion 3 (b, amendment note). Tests: (a) a capped email's login attempt completes in ≪ KDF time / no derivation side-effect observable — pinned as "429 before KDF" via the throttle test's knob math; (b) web source pin: the 402 branch renders reason + CTA and fetches nothing from the payload's posts_used/posts_limit. Confidence 0.80.
|
||||
|
||||
## Scope Cuts
|
||||
|
||||
None. Every phase maps to a REQ-10-001..005 row; the one candidate (employer draft-edit, the least-essential P4 arm) is named by REQ-10-004 and is cheap once G-318 forces admin-parity — cutting it would unilaterally narrow a locked requirement. Talent pages staying mock is the honest deferral the plan already makes (D-092).
|
||||
|
||||
## Advisories (recorded, no plan edit)
|
||||
|
||||
- **a-311:** Employer mock-complete "own session" = checkout rows whose employer_id equals the session's claimed entity — including operator-created rows for that entity (same buyer, D-076 fallback path; not a G-301 violation). Pin the test's fixture accordingly so the 403 arm uses a DIFFERENT entity's row, not an admin-created same-entity row.
|
||||
- **a-312:** Per-email throttle inherently permits targeted lockout DoS (5 failures → victim's email 429s for 15 min). Accepted within D-088 (email-keying is locked, never re-litigated); success-clears-window is the mitigation; surface copy need not mention it.
|
||||
- **a-313:** .env.example throttle entries are documentation, not "default-off" — the Settings ints are always active with defaults 5/30 (the R-60d shape). Write the comments that way.
|
||||
- **a-314:** Logout on an already-revoked token → 401 (strict) is fine; do not "fix" it to 204 — idempotent-logout would let a stolen-tab replay confirm revocation state.
|
||||
- **a-315:** Register's 409 duplicate-email necessarily reveals account existence — standard and unavoidable; the login 401 uniformity (already specified) is the enumeration boundary that matters.
|
||||
|
||||
## Plan Edits Applied
|
||||
|
||||
1. G-311 → REQUIREMENTS REQ-10-004 wording + PLAN Task 4-1-02 amendment note
|
||||
2. G-312 → PLAN Tasks 3-3-01, 3-3-02 amendment notes
|
||||
3. G-313/G-314/G-320a → PLAN Task 1-2-02 amendment note
|
||||
4. G-315 → PLAN Task 1-1-01 amendment note
|
||||
5. G-316 → PLAN Task 2-1-02 amendment note
|
||||
6. G-317/G-318/G-311 → PLAN Task 4-1-02 amendment note (single combined note)
|
||||
7. G-319 → PLAN Task 3-1-01 amendment note
|
||||
8. G-320b → PLAN Task 4-2-01 amendment note + UX criterion 3 clause
|
||||
|
||||
---
|
||||
|
||||
## v0.11 Grill (Phase 0 GRILL, 2026-10-01)
|
||||
|
||||
### Run: 2026-10-01 03:00 (mode: mechanical, focus: all — v0.11 placement tracking)
|
||||
|
||||
### Verdict: Proceed (confidence: 0.82)
|
||||
|
||||
**Verdict summary.** The v0.11 plan (6 phases, 15 waves, ~30 tasks) is feasible, correctly sequenced, and — rare for a plan this audit-flavored — unusually honest about its own limits (R-67's three methodology gaps are pinned into the export). Every load-bearing tree citation re-verified held: the billing transition-matrix shape, the `decide_claim` same-transaction precedent, the `submitted`-only application status (zero migration), the G-313 conftest reset pattern, the G-319 counts-only pin, all four main.py wiring sites, the engine-client error-class rails, and the overview mock block D-109 replaces. The two genuinely novel mechanisms (the hash chain, the export) each carry dedicated adversarial tests (tamper/fork/determinism), and the one coherence gap research found (R-80 re-hire) is pinned to a route. But red-teaming found **8 binding defects**: the export's verification story overclaims by omission (the chain detects in-place mutation of an intact sequence — it cannot detect a wholesale DB rewrite, and no instruction tells the auditor how to use prior exports as the anchor); **the learner status panel cannot find the learner's application on revisit** (the read route is keyed by `application_id`, no route exists to discover it for a posting, and the plan never says how the panel obtains it — the happy path only works in the same browser session); the apply route's idempotent arm returns a 200 "applied" confirmation for a withdrawn (terminal) application — a lie D-104's withdraw creates; `role_title` accepts the empty string (the 422 arm pins absence, not emptiness); revoked placements are counted but their evidence bundles are unspecified (an unverifiable `revoked_count`); the re-hired PlacementRow's `decided_at` is unspecified; the operator route's `to` has no 422-vs-409 discrimination; and nothing pins the live UI wording against "CIRR-verified" theater. All eight amend existing tasks — nothing re-architects, no scope cuts required.
|
||||
|
||||
### Per-Axis Findings
|
||||
|
||||
| # | Axis | Verdict | Reason |
|
||||
|---|------|---------|--------|
|
||||
| 1 | Feasibility | PASS | Outcome is unmeasurable without this milestone (no hire state exists in-tree); every prerequisite shipped; 6-phase shape matches the two shipped precedents |
|
||||
| 2 | Scope | PASS | Explicit out-of-scope list; R-67's three pilot gaps pre-disclosed in the methodology (the hidden-requirement class handled better than any prior milestone); the one boundary change (G-319 supersession) is decisioned with a pin split |
|
||||
| 3 | Architecture | CONCERN → fixed | Chain NOT over-engineered (it IS the deliverable; the cheap version) but UNDER-scoped (G-321: the walk cannot detect a wholesale DB rewrite — export-to-export prefix continuity is the anchor); the mine-read gap strands the learner status panel on revisit (G-322); D-100 cross-store transaction verified sound (one Session, one commit — the two-commit alternative voids the tamper-evidence) |
|
||||
| 4 | People | PASS | Roster matches the work; the security-auditor's four review points cover exactly the novel-risk surfaces |
|
||||
| 5 | Timeline | PASS | Consistent with v0.9/v0.10 identical-shape precedents; the flush-then-hash-then-commit append is the one new mechanism, mitigated by R-70's in-tree template + tamper/fork arms |
|
||||
| 6 | Budget | PASS | Zero new deps, zero knobs, zero workflow changes; chain verification is O(n) sha256 over tiny rows |
|
||||
| 7 | Risks | CONCERN → fixed | Pre-mortem done (R-80 found + pinned by research itself; all 10 open risks map 1:1 to tasks); NEW cross-decision defect found: apply → withdraw → re-apply returns a 200 "applied" lie (G-323 — D-043 × D-099 × D-104 interaction nobody mapped) |
|
||||
| 8 | Governance | CONCERN → fixed | Decisions traceable + discipline enforced (the R-80 escalation flow is the pattern working); MISSING: live-surface wording discipline — "CIRR-verified" theater drift unpinned (G-328); the operator route's 422-vs-409 split unspecified (G-327) |
|
||||
| 9 | Adoption | CONCERN → fixed | Export is honestly-minimal (dataset + disclosure, not theater) PROVIDED G-321/G-328 hold; counting gameable only via operator-gated claim approval — honestly disclosed (a-321); empty-string role_title accepted (G-324) |
|
||||
| M | Meta | CONCERN → fixed | Revoked placements' evidence bundles unspecified — an auditor handed revoked_count with no evidence has an unverifiable number, and correction history is what an auditor most wants to inspect (G-325); the re-hired row's decided_at unpinned (G-326); simplest-80% version = this plan (no cut found) |
|
||||
|
||||
### Binding Decisions (G-321..G-328 — applied to PLAN before execute)
|
||||
|
||||
**G-321 — the export methodology states the chain's proof scope, its limit, and the auditor's real anchor.** The walk proves in-place mutation/fork detection of an intact sequence; it does NOT detect a wholesale DB rewrite (delete all events, re-append a fresh plausible chain from GENESIS — it walks green; GENESIS is a constant with no external anchor). PlacementRow itself is not hash-chained — a raw-SQL status flip leaves a chain-consistent ledger with a lying row. Decision: the methodology's `verification` block + the summary's verification instructions state (a) what the chain proves, (b) what it does not (wholesale replacement — the auditor's defense is export-to-export continuity: a prior export's `ledger.events` must appear as an exact prefix of a later export's, and `head_hash` at the prior export must equal the hash at that prefix position), and (c) an event↔row cross-consistency check (every active placement has `placement.created`; every revoked has `placement.revoked`; revoked_count matches the `placement.revoked` events). Amends Tasks 4-1-01, 4-1-02; asserted present by 4-1-03. Confidence 0.80.
|
||||
|
||||
**G-322 — the mine point-read: the learner status panel must never depend on client-persisted application_ids.** The read route is keyed by application_id, but no route discovers a learner's application for a posting (the idempotent apply return yields the id only in-session; there is no by-(posting, learner) read anywhere in-tree) — REQ-11-005's outcome visibility breaks on revisit, the common case for a job board. Decision: store `get_application_by_posting_learner(posting_id, learner_id)` (the insert_application unique key — the get_posting point-read shape) + route `GET /v1/marketplace/applications/mine?posting_id=&learner_id=` on the unchanged D-043 gate stack, returning `{application_id, status}` or 404. The job-detail panel composes: mine-read → found? render the status panel via D-104's read : not found? render the apply CTA. Amends D-104 (additive route), Tasks 5-1-01 + 5-2-01; tests in test_learner_status.py (own/foreign/unverified/unknown arms + 404-when-none). Confidence 0.85.
|
||||
|
||||
**G-323 — apply on an existing terminal application → 409, never a 200 "applied" confirmation.** insert_application's idempotent arm (marketplace/store.py:341-344) returns the EXISTING application with 200 — after D-104's withdraw makes it terminal, re-apply tells the learner they applied to a job they can never re-enter the pipeline for. Decision: the apply route's idempotent arm gains a terminal-state guard: returned application in `withdrawn`/`rejected`/`hired` → 409 `{"reason": "application_terminal", "status": …}` (the posting_not_published 409 shape, marketplace.py:366-373), never a 200; no new application row (the unique key stands); recovery is visibility (G-322's mine-read + status panel), not resurrection. Amends Task 2-2-01's test list (apply → withdraw → re-apply → 409). Confidence 0.75.
|
||||
|
||||
**G-324 — `role_title = Field(min_length=1, max_length=200)`; start_date keeps no semantic range.** Pydantic "required" rejects absence, not emptiness — the house Field shape (marketplace/base.py:68-71) is not specified for the hire body and `role_title: ""` would enter the hashed ledger. Decision: min_length=1 (pinned beside the missing-fields 422 arm), max_length=200 (bounds absurd payloads out of the hashed rows). start_date stays a bare pydantic date — retroactive + future legal per D-103; garbage dates surface as anomalous by_cohort_month buckets in the operator overview and are corrected via the revoke/re-hire lane; the methodology's attestation note covers date integrity. Amends Tasks 1-1-01, 2-1-01. Confidence 0.80.
|
||||
|
||||
**G-325 — evidence_bundles cover EVERY placement (active + revoked), each with the full event history.** An auditor handed `revoked_count: 3` with no evidence for the three revocations has an unverifiable number — and the correction history (hired → revoked → rehired) is precisely what an auditor most wants to inspect. Decision: bundles cover active AND revoked placements with the full event history incl. placement.revoked/placement.rehired; `cohort` stays active-only; revoked_count equals the placement.revoked events (cross-checkable, rides G-321(c)). Amends Tasks 4-1-01, 4-1-03 (completeness test: every placement active-or-revoked has a bundle). Confidence 0.80.
|
||||
|
||||
**G-326 — the re-hired PlacementRow's decided_at = the re-hire event's store-stamped created_at.** D-102 stamps decided_at from "the hired transition's created_at" — a re-hire has no hired transition; an executor will guess. Decision: the same `datetime.now(UTC)` stamp rule extends to the re-hire arm; stated in the module docstring + asserted in the revoke→re-hire test arm. Amends Task 2-2-02. Confidence 0.85.
|
||||
|
||||
**G-327 — the operator transition route's `to` is a pydantic Literal of the seven D-099 statuses.** Unknown value → 422 (body validation), matrix-illegal known value → 409 InvalidTransition — the route never sees a status outside the vocabulary (no 500s, no silent acceptance). Test arm in test_admin_lane.py (garbage `to` → 422, never 500/409). Amends Task 2-2-02. Confidence 0.85.
|
||||
|
||||
**G-328 — live surfaces never present attestation as verification.** Nothing pins the admin placements block / overview copy against the theater drift — "CIRR-verified placements" or "verified: 1,000" on a live surface presents attestation as third-party verification (A-304), the exact self-certification trap the milestone could fall into. Decision: live surfaces label counts as recorded placements ("distinct learners placed", "placements recorded"); "CIRR" NEVER appears as a verification claim on any live surface — "CIRR-style" describes the export format in release notes/methodology only; the summary's title renders the attestation language ("employer-attested, operator-overseen"). Amends Task 4-2-01 (copy) + UX criterion 5's test arm (source pin: no "verified" placement wording on any new surface). Confidence 0.75.
|
||||
|
||||
### Advisories (recorded, no action)
|
||||
|
||||
- a-321: No technical self-hire guard exists (learner handles and employer accounts are disjoint namespaces); the anti-gaming control is operator claim-approval diligence + per-employer overview detection + the revoke lane — already disclosed as R-67 gap (c); do not add a theater cross-check.
|
||||
- a-322: Withdraw shares the apply-rate window (5/60s per learner, D-104) — a learner withdrawing 5 applications quickly locks themselves out of applying for the window's remainder. Honest, bounded, no new knob.
|
||||
- a-323: The matrix arm (read status → validate) is check-then-act, but the terminal guard makes a concurrent loser's write a 409-conflict on re-read; the D-111 concurrent-transition test covers the shape; no pessimistic locking at pilot volumes.
|
||||
- a-324: The employer pipeline list necessarily carries learner_id per row (own postings only) — the G-319 pin split's application-scoped arm working as decisioned; the P2 security review confirms the list route's cross-entity arms return 403 with no data, same as the transitions.
|
||||
|
||||
### Escalations
|
||||
|
||||
None. All eight findings resolve with evidence-backed defaults (each names its amends-task and its test); nothing re-architects, no axis falls below 0.60.
|
||||
|
||||
### Plan Edits Recorded (applied by the orchestrator)
|
||||
|
||||
1. G-321/G-325/G-328 → PLAN Tasks 4-1-01, 4-1-02, 4-1-03, 4-2-01 amendment notes + UX criterion 5 arm
|
||||
2. G-322 → PLAN Tasks 5-1-01, 5-2-01 amendment notes (additive route per D-104)
|
||||
3. G-323 → PLAN Task 2-2-01 amendment note (apply-route terminal guard + test arm)
|
||||
4. G-324 → PLAN Tasks 1-1-01, 2-1-01 amendment notes
|
||||
5. G-326/G-327 → PLAN Task 2-2-02 amendment notes
|
||||
|
||||
+150
-129
@@ -2,21 +2,17 @@
|
||||
|
||||
## Persona Roster
|
||||
|
||||
> **v0.6 update (RESEARCH, lead-developer assessment):** milestone = Marketplace Engine (D-047). **Activated:** data-engineer (6th D-027 store family — five tables, seed port, TS wire types dual-schema sync, its core constraint territory), ai-engineer full activation (tagging/enrichment/resume D-020 prompts + EmbeddingProvider protocol — LLM-facing work returns), frontend-engineer (client shells, engine-client marketplace extension, generateStaticParams removal ×2, SEO metadata + client JSON-LD), backend-engineer (module wiring, config surface: AI_EMBED_*/AI_ADMIN_TOKEN/AI_PUBLIC_BASE_URL, sitemap/robots routes). **security-auditor re-activated (phase-specific)** for admin-token fail-closed (P1), resume upload bounds + PII-logs (P4), sitemap origin (P5), final review (P6). **Deactivated:** identity-engineer (v0.5 custom — module shipped; only the `require_verified_adult` gate import is reused), voice-engineer, sandbox-engineer (no voice/sandbox/telemetry work), cli-engineer, design-system-engineer (existing primitives cover the marketplace shells).
|
||||
|
||||
> **v0.5 update (RESEARCH, lead-developer assessment):** milestone = Real Server Voice, KYC/Identity, Sandbox Environments, Seq-Lease. **Reactivated:** voice-engineer (real server STT/TTS, its v0.3 territory), sandbox-engineer (design/sim environment kinds + the seq-ack protocol on the fabric/agent it owns), frontend-engineer (defense audio upload, identity enrollment flow, kind-aware build surface). **New custom persona: identity-engineer** (KYC/identity domain — 5th store, provider protocol, age-gate dependencies, PII hygiene). **security-auditor re-activated (phase-specific)** for identity PII + age-gate bypass + audio upload attack surface (phases 1-4 review, final phase). ai-engineer light-touch (no LLM-facing work this milestone). backend-engineer retains settings/factory wiring + turbo/root scripts. cli-engineer inactive (v0.3.6 hotfix shipped; no CLI work planned). design-system-engineer/data-engineer inactive (one TS types extension only — data-engineer light-touch for variants/identity types).
|
||||
> **v0.11 update (RESEARCH, lead-developer assessment):** milestone = Placement Tracking and Audit (Feature — ai_service/placements/ module: 9th D-027 store with the hash-chained placement_event ledger, the application state machine via one transactional transition_application, /v1/employers/applications per-target routes, learner withdraw/status routes in marketplace.py, the placements_admin operator lane + export, four web surfaces). **Activated:** lead-developer (coordination + the R-80 re-hire coherence review + the G-319 pin-split review), backend-engineer (owns ai_service/placements/* + api/placements_admin.py + the employer application routes + learner routes in marketplace.py + deps.py get_placement_store + main.py wiring — REQ-11-001..005 core), data-engineer (owns the 2-table placement store schema: PlacementRow partial-unique + PlacementEventRow global hash chain flush-then-hash-then-commit, canonical serialization, the D-102 revoke semantics — REQ-11-001/002), frontend-engineer (owns the four D-109 surfaces: /employer/applications page, overview placements section, job-detail status panel, admin placements block + engine-client placements section + packages/types/placement.ts — REQ-11-003/005), security-auditor (phase-specific: the hash-chain tamper evidence, the G-319 supersession PII review, gate-order pins, export integrity — REQ-11-001/002/004). **Deactivated:** cli-engineer, devops-engineer, sandbox-engineer, ai-engineer, identity-engineer (learner gates compose unchanged — D-104), voice-engineer, design-system-engineer (all unchanged surfaces this milestone).
|
||||
|
||||
### lead-developer
|
||||
```yaml
|
||||
active: true
|
||||
phase_specific: false
|
||||
reason: Coordinates the v0.6 marketplace territory split (store/ingest/embedding/tagging/search/enrichment/resume across data/ai/backend/frontend personas); owns wave-order coupling decisions (D-059: P1 ships backend WITH client shells)
|
||||
reason: Coordinates the v0.11 Placement Tracking milestone (store → state machine → reporting → export → visibility waves); owns wave order + the R-80 re-hire coherence decision's implementation review (the placement.rehired route/event shape) + the G-319 pin-split review (counts-only stays on own-postings lists; learner_id on application-scoped routes only) + the placement.ts ↔ placements/base.py dual-schema pin review + the D-100 cross-store transaction discipline review (one transition_application, no second status writer)
|
||||
domain: coordination
|
||||
frameworks:
|
||||
- next.js
|
||||
- turborepo
|
||||
- pnpm
|
||||
- fastapi
|
||||
constraints:
|
||||
- pragmatic
|
||||
- battle-tested defaults
|
||||
@@ -24,93 +20,143 @@ constraints:
|
||||
territory:
|
||||
- "**/package.json"
|
||||
- "**/turbo.json"
|
||||
- "**/pnpm-workspace.yaml"
|
||||
- "**/tsconfig.json"
|
||||
- "apps/ai-service/pyproject.toml"
|
||||
- "apps/web/tests/pins.test.ts"
|
||||
```
|
||||
|
||||
### data-engineer
|
||||
### devops-engineer
|
||||
```yaml
|
||||
active: true
|
||||
active: false
|
||||
phase_specific: false
|
||||
reason: v0.6 core activation — owns the 6th D-027 store family (D-049: posting/employer/embedding/application/employer_enrichment tables, WAL/pragmas/portable columns/validate hooks), the seed port from packages/mock-data jobs.ts+employers.ts (D-050, one-time, matchScore dropped), and the TS marketplace wire types (dual-schema sync with pydantic contracts)
|
||||
domain: data
|
||||
reason: v0.11 DEACTIVATED — no infra changes; the placements module rides the existing release lane (image + assets build automatically on tag per D-064/D-065). Roster + v0.8 territory retained.
|
||||
domain: devops
|
||||
frameworks:
|
||||
- sqlmodel
|
||||
- pydantic
|
||||
- typescript
|
||||
- docker
|
||||
- docker-compose
|
||||
- gitea-runner
|
||||
- github-actions-syntax (gitea-compatible subset)
|
||||
- bash
|
||||
constraints:
|
||||
- schema-first
|
||||
- type-safe
|
||||
- dual-schema-sync (TS/Python changes made in both places)
|
||||
- idempotent-upserts ((source, external_id) + (posting_id, learner_id) unique constraints)
|
||||
- sibling-mode-socket-trust (org-scoped private repos only; accepted-risk documented)
|
||||
- secrets-via-actions-secrets-or-founder
|
||||
- job-token-cannot-publish-packages
|
||||
- cache-host-pinning
|
||||
- fast-lanes-only-in-ci (real_server/userns never in job containers, D-063)
|
||||
territory:
|
||||
- "apps/ai-service/ai_service/marketplace/base.py"
|
||||
- "apps/ai-service/ai_service/marketplace/store.py"
|
||||
- "apps/ai-service/ai_service/marketplace/ingest.py"
|
||||
- "packages/types/**"
|
||||
- "packages/mock-data/**"
|
||||
- ".gitea/workflows/**"
|
||||
- "Dockerfile"
|
||||
- ".dockerignore"
|
||||
- ".pre-commit-config.yaml"
|
||||
- "deploy/runner/**"
|
||||
```
|
||||
|
||||
### ai-engineer
|
||||
### cli-engineer
|
||||
```yaml
|
||||
active: true
|
||||
active: false
|
||||
phase_specific: false
|
||||
reason: v0.6 full activation — LLM-facing work returns: tagging prompt+schema (D-052), enrichment extraction (D-053), resume parse extraction (D-054) — all through the existing D-020 structured_completion layer; plus the EmbeddingProvider protocol + deterministic feature-hash mock (D-051). Guards the agent/engine boundaries the marketplace surfaces touch
|
||||
domain: ai
|
||||
reason: v0.11 DEACTIVATED — no CLI changes; the placement surface is server+web only. Roster + v0.8 territory retained.
|
||||
domain: cli
|
||||
frameworks:
|
||||
- pydantic
|
||||
- httpx
|
||||
- node
|
||||
- typescript
|
||||
- node-sea
|
||||
- esbuild
|
||||
- postject
|
||||
- dpkg-deb
|
||||
- posix-sh
|
||||
constraints:
|
||||
- stdlib-only-runtime
|
||||
- thin-wrapper
|
||||
- fail-loud-exit-codes
|
||||
- postinst-never-fails-dpkg (advisory doctor, D-067)
|
||||
- deb-no-systemd-unit (deploy --service owns units, D-067)
|
||||
- guide-offline-first (zero runtime fetches, D-072)
|
||||
- deb-version-policy (tag minus leading v)
|
||||
territory:
|
||||
- "apps/cli/**"
|
||||
- "scripts/install.sh"
|
||||
- "scripts/release-assets.sh"
|
||||
- "scripts/build-deb.sh"
|
||||
```
|
||||
|
||||
### sandbox-engineer
|
||||
```yaml
|
||||
active: false
|
||||
phase_specific: false
|
||||
reason: v0.11 DEACTIVATED — no sandbox fabric changes; the D-068 degrade surface ships unchanged. Roster + v0.8 territory retained.
|
||||
domain: infra
|
||||
frameworks:
|
||||
- python
|
||||
- linux-namespaces
|
||||
- docker (degrade semantics only — no docker backend)
|
||||
- pytest
|
||||
constraints:
|
||||
- provider-agnostic-protocol
|
||||
- never-call-cloud-in-tests
|
||||
- mock-first (structured_completion runs against MockLLMProvider)
|
||||
- capability-probe-is-truth-source (markers only flavor remediation, D-068)
|
||||
- reject-not-fallback (unisolated learner code unacceptable in deployed schools; supersedes A-101)
|
||||
- degrade-keeps-core-features (chat/agents/grading untouched)
|
||||
- probe-semantics-verbatim (unshare --user --map-root-user true, 10s timeout)
|
||||
territory:
|
||||
- "apps/ai-service/ai_service/marketplace/tagging.py"
|
||||
- "apps/ai-service/ai_service/marketplace/enrichment.py"
|
||||
- "apps/ai-service/ai_service/marketplace/resume.py"
|
||||
- "apps/ai-service/ai_service/marketplace/embedding/**"
|
||||
- "apps/ai-service/ai_service/marketplace/search.py"
|
||||
- "apps/ai-service/ai_service/llm/**"
|
||||
- "apps/ai-service/ai_service/agents/structured.py"
|
||||
- "apps/ai-service/ai_service/prompts/**"
|
||||
- "apps/ai-service/ai_service/sandbox/**"
|
||||
- "apps/ai-service/ai_service/main.py"
|
||||
- "apps/ai-service/ai_service/api/sandboxes.py"
|
||||
- "apps/ai-service/tests/sandbox/**"
|
||||
- "apps/ai-service/tests/helpers/userns.py"
|
||||
```
|
||||
|
||||
### security-auditor
|
||||
```yaml
|
||||
active: true
|
||||
phase_specific: true
|
||||
reason: v0.11 re-activated (phase-specific) — P1 ledger review: the hash-chain construction (canonical JSON rules, GENESIS pinned, UNIQUE(prev_hash) fork backstop, flush-then-hash-then-commit single append path, no delete path — R-70), partial-unique active-placement guard (G-316 shape); P2 gate review: G-311 gate order on application transitions (401 → 403-claim → 403-cross-entity → 409), the G-319 supersession PII review (learner_id = opaque handle, application-scoped only, anti-enumeration preserved — R-79); P4 export integrity (determinism rules, generated_at exclusion, methodology honesty gaps stated — R-67/R-68/R-73); P6 final review (no PII/credentials in logs or releases)
|
||||
domain: security
|
||||
frameworks:
|
||||
- pytest
|
||||
- httpx
|
||||
constraints:
|
||||
- STRIDE-classified
|
||||
- secrets-via-env-only (D-014)
|
||||
- secrets-never-logged
|
||||
- fail-closed-on-unconfigured
|
||||
- never-display-forgeable-as-verified (A-304 — the export methodology states its own limits)
|
||||
- tamper-evidence-tested (an audit ledger nobody has tried to break is theater, D-111)
|
||||
territory:
|
||||
- "apps/ai-service/ai_service/placements/**"
|
||||
- "apps/ai-service/ai_service/api/placements_admin.py"
|
||||
- "apps/ai-service/tests/placements/**"
|
||||
```
|
||||
|
||||
### backend-engineer
|
||||
```yaml
|
||||
active: true
|
||||
phase_specific: false
|
||||
reason: Owns the v0.6 config surface (AI_EMBED_PROVIDER/BASE_URL/MODEL/API_KEY, AI_ADMIN_TOKEN, AI_PUBLIC_BASE_URL — all env-only), main.py lifespan wiring (marketplace store + embedding provider factory on app.state), the /v1/marketplace/* + admin routers' DI, sitemap/robots routes (D-056), .env.example documentation
|
||||
reason: v0.11 ACTIVATED — owns the placements module core: ai_service/placements/base.py (pydantic contracts + the D-099 transition matrix + event-name vocabulary), store.py wiring via deps.py get_placement_store; the ONE transactional transition_application method (status write + ledger append + placement-on-hired, one commit — D-100) + the R-70 flush-then-hash-then-commit append shape; api routes: employer per-target transitions under /v1/employers/applications (G-311 gate order — D-105), learner withdraw/status in marketplace.py (D-043 stack unchanged — D-104), placements_admin.py operator lane (generic transition + revoke + R-80 re-hire route + overview/export reads — D-106/D-108); main.py wiring (placement_store lifespan + close, placements_admin mount); no new config knobs (no new throttles)
|
||||
domain: backend
|
||||
frameworks:
|
||||
- fastapi
|
||||
- pydantic-settings
|
||||
- httpx
|
||||
- bash
|
||||
- turborepo
|
||||
- pnpm
|
||||
constraints:
|
||||
- secrets-via-env-only (D-014; keys never in code or commits)
|
||||
- secrets-via-env-only (D-014)
|
||||
- idempotent-scripts
|
||||
- fail-closed-admin (unset AI_ADMIN_TOKEN = admin routes 403 + loud boot warning)
|
||||
- fail-closed-admin
|
||||
- never-call-cloud-in-tests (zero network by construction, D-111)
|
||||
- one-status-writer (placements store is the ONLY post-creation writer of application.status — R-78)
|
||||
- no-cross-family-foreign-keys (G-302 ID references at read)
|
||||
territory:
|
||||
- "apps/ai-service/ai_service/config.py"
|
||||
- "apps/ai-service/ai_service/placements/**"
|
||||
- "apps/ai-service/ai_service/main.py"
|
||||
- "apps/ai-service/ai_service/api/marketplace.py"
|
||||
- "apps/ai-service/ai_service/api/marketplace_admin.py"
|
||||
- "apps/ai-service/ai_service/api/deps.py"
|
||||
- "apps/ai-service/scripts/**"
|
||||
- "apps/ai-service/.env.example"
|
||||
- "apps/ai-service/ai_service/api/**"
|
||||
- "apps/ai-service/tests/placements/**"
|
||||
- "apps/ai-service/pyproject.toml"
|
||||
- "package.json"
|
||||
- "turbo.json"
|
||||
```
|
||||
|
||||
### frontend-engineer
|
||||
```yaml
|
||||
active: true
|
||||
phase_specific: false
|
||||
reason: v0.6 marketplace surfaces go live: board/detail/employer-profile client shells (D-055, build/defend pattern), engine-client marketplace functions (listPostings/getPosting/getEmployer/searchPostings/apply), generateStaticParams removal on jobs/[jobId]+employers/[employerId] ONLY, apply-flow wiring on the real route, SEO metadata (export const metadata on static set) + client-side JobPosting/Organization JSON-LD on runtime pages
|
||||
reason: v0.11 ACTIVATED — owns the four D-109 surfaces: new /employer/applications page (own pipeline with status badges + per-target transition CTAs + hire form {role_title, start_date}), employer overview placements section (replaces the mock-labeled placement metrics block — D-092 never-fake-convert), job-detail-client application-status panel (learner history + placement confirmation via D-104 read, EngineError.status discrimination, no new error classes), admin moderation placements block (overview counts + per-employer lists + export links, adminToken transport); engine-client placements section (employer/learner/admin functions, AbortController everywhere, SessionRequiredError reuse — D-110); packages/types/placement.ts dual-schema pinned (D-110); talent badge stays absent (A-304)
|
||||
domain: frontend
|
||||
frameworks:
|
||||
- react
|
||||
@@ -119,40 +165,65 @@ frameworks:
|
||||
constraints:
|
||||
- component-first
|
||||
- server-components-default
|
||||
- honest-state-surfaces (404 on missing posting, verify-CTA on 403, empty boards)
|
||||
- no-build-time-db-reads (D-039 export build stays repo-only)
|
||||
- honest-states (loading/error/empty/logged-out never mocked)
|
||||
- abortcontroller-everywhere (A-406)
|
||||
- session-gated-shell (401 → honest logged-out state, never a retry loop)
|
||||
territory:
|
||||
- "apps/web/**"
|
||||
- "packages/ui/**"
|
||||
- "packages/types/placement.ts"
|
||||
```
|
||||
|
||||
### security-auditor
|
||||
### ai-engineer
|
||||
```yaml
|
||||
active: false
|
||||
phase_specific: false
|
||||
reason: v0.11 DEACTIVATED — no LLM-facing work; placement flows need no tagging/enrichment/embedding changes (hire transitions record decisions; no AI surface is touched).
|
||||
domain: ai
|
||||
frameworks:
|
||||
- pydantic
|
||||
- httpx
|
||||
- pytest
|
||||
constraints:
|
||||
- provider-agnostic-protocol
|
||||
- never-call-cloud-in-tests
|
||||
- mock-first
|
||||
territory:
|
||||
- "apps/ai-service/ai_service/llm/**"
|
||||
- "apps/ai-service/ai_service/agents/**"
|
||||
- "apps/ai-service/ai_service/marketplace/**"
|
||||
- "apps/ai-service/ai_service/prompts/**"
|
||||
```
|
||||
|
||||
### data-engineer
|
||||
```yaml
|
||||
active: true
|
||||
phase_specific: true
|
||||
reason: v0.6 re-activated — admin token fail-closed + route coverage (P1), apply gate composition preserved D-043 (P1), embedding provider key redaction (P3), resume upload bounds + raw-bytes-never-logged (P4), enrichment provenance honesty (P4), sitemap origin config (P5), final review (P6)
|
||||
domain: security
|
||||
phase_specific: false
|
||||
reason: v0.11 ACTIVATED — owns the 2-table 9th store schema (D-112): placements/store.py with PlacementRow (id, learner/employer/posting/application refs, role_title, start_date DATE, status active|revoked, created_at, decided_at; partial UNIQUE application_id WHERE status='active' — the G-316 shape, D-102) + PlacementEventRow (append-only global ledger: nullable indexed application_id + placement_id, event_type, actor_type employer|learner|operator|system, actor_ref, payload, prev_hash UNIQUE + hash, created_at — D-101); the canonical serialization rules (sort_keys + separators, _as_utc(dt).isoformat() pinned, no floats — R-79/R-69); flush-then-hash-then-commit append (R-70); the R-80 placement.rehired event vocabulary; cross-store transaction (one Session writes ApplicationRow + both placement tables — D-100); tz discipline + create_all idempotent compat (D-095 shape); _validate/_normalize + surfaced IntegrityError
|
||||
domain: data
|
||||
frameworks:
|
||||
- pytest
|
||||
- httpx
|
||||
- sqlmodel
|
||||
- pydantic
|
||||
- typescript
|
||||
constraints:
|
||||
- STRIDE-classified
|
||||
- fail-closed (unset admin token never opens routes)
|
||||
- bounded-uploads (resume 2MB/format guard)
|
||||
- secrets-never-logged (_sanitize key redaction)
|
||||
- schema-first
|
||||
- type-safe
|
||||
- dual-schema-sync
|
||||
- idempotency-by-constraint (partial UNIQUE + check-first)
|
||||
- audit-append-only (the ledger has NO delete path — R-70)
|
||||
- canonical-serialization-pinned (one normalization, test-pinned)
|
||||
territory:
|
||||
- "apps/ai-service/ai_service/api/marketplace.py"
|
||||
- "apps/ai-service/ai_service/api/marketplace_admin.py"
|
||||
- "apps/ai-service/ai_service/marketplace/resume.py"
|
||||
- "apps/ai-service/ai_service/marketplace/embedding/openai_compat.py"
|
||||
- "apps/ai-service/ai_service/api/identity.py"
|
||||
- "apps/ai-service/ai_service/placements/store.py"
|
||||
- "apps/ai-service/tests/placements/test_store.py"
|
||||
- "packages/types/**"
|
||||
```
|
||||
|
||||
### identity-engineer
|
||||
```yaml
|
||||
active: false
|
||||
phase_specific: false
|
||||
reason: v0.5 custom persona — module shipped complete (identity/, gates, /v1/identity/*); v0.6 only REUSES the require_verified_adult import on the marketplace apply route (D-058). No identity-domain work.
|
||||
reason: v0.11 stays DEACTIVATED — the milestone composes the EXISTING learner gates unchanged (D-104: the withdraw/status routes ride the D-043 stack — G-5 allowlist → verified 18+ → apply-rate window); no identity-module changes. Reactivation is a founder call if/when a real KYC vendor lands.
|
||||
domain: identity
|
||||
frameworks:
|
||||
- fastapi
|
||||
@@ -161,7 +232,6 @@ frameworks:
|
||||
constraints:
|
||||
- pii-never-stored-raw
|
||||
- pii-never-logged
|
||||
- mock-verdict-honesty
|
||||
- gate-composition-order
|
||||
territory:
|
||||
- "apps/ai-service/ai_service/identity/**"
|
||||
@@ -172,7 +242,7 @@ territory:
|
||||
```yaml
|
||||
active: false
|
||||
phase_specific: false
|
||||
reason: v0.5 territory — voice shipped complete (openai-audio provider, defense routes, browser SR/TTS client); no v0.6 voice work. The EmbeddingProvider protocol MIRRORS the voice pattern (D-051) but the voice module itself is untouched.
|
||||
reason: v0.5 territory — voice shipped complete; no v0.11 voice work.
|
||||
domain: ai-media
|
||||
frameworks:
|
||||
- httpx
|
||||
@@ -183,66 +253,17 @@ constraints:
|
||||
- provider-agnostic-protocol
|
||||
- never-call-cloud-in-tests
|
||||
- key-redaction
|
||||
- bounded-audio-in-memory
|
||||
territory:
|
||||
- "apps/ai-service/ai_service/voice/**"
|
||||
- "apps/ai-service/tests/voice/**"
|
||||
- "apps/web/components/learner/defense-session.tsx"
|
||||
```
|
||||
|
||||
### sandbox-engineer
|
||||
```yaml
|
||||
active: false
|
||||
phase_specific: false
|
||||
reason: v0.3/v0.5 territory — fabric + env kinds + seq-ack shipped complete; no v0.6 sandbox/telemetry work (marketplace data plane never enters the namespace fabric).
|
||||
domain: infra
|
||||
frameworks:
|
||||
- python
|
||||
- linux-namespaces
|
||||
- pytest
|
||||
constraints:
|
||||
- stdlib-only-agent
|
||||
- acks-are-advisory
|
||||
- thread-safe-spool-trim
|
||||
- digest-kind-agnostic
|
||||
territory:
|
||||
- "apps/ai-service/ai_service/sandbox/**"
|
||||
- "apps/ai-service/ai_service/telemetry/**"
|
||||
- "apps/ai-service/scripts/sandbox-agent.py"
|
||||
- "apps/ai-service/ai_service/variants/templates.py"
|
||||
- "apps/ai-service/tests/sandbox/**"
|
||||
- "apps/ai-service/tests/telemetry/**"
|
||||
```
|
||||
|
||||
### cli-engineer
|
||||
```yaml
|
||||
active: false
|
||||
phase_specific: false
|
||||
reason: No CLI work in v0.6 (the binary attaches to every release per the ongoing-binaries requirement; the ship workflow handles it — no apps/cli changes).
|
||||
domain: cli
|
||||
frameworks:
|
||||
- node
|
||||
- typescript
|
||||
- node:test
|
||||
- esbuild
|
||||
- node-sea
|
||||
- posix-sh
|
||||
constraints:
|
||||
- stdlib-only-runtime
|
||||
- thin-wrapper
|
||||
- timeout-every-spawn
|
||||
- fail-loud-exit-codes
|
||||
territory:
|
||||
- "apps/cli/**"
|
||||
- "scripts/install.sh"
|
||||
- "scripts/release-assets.sh"
|
||||
```
|
||||
|
||||
### design-system-engineer
|
||||
```yaml
|
||||
active: false
|
||||
phase_specific: false
|
||||
reason: No design-token or primitive work in v0.6 (existing primitives + JobFilters cover the marketplace shells); roster retained.
|
||||
reason: No design-token or primitive work in v0.11 (the applications page reuses existing Badge/Button/Card primitives); roster retained.
|
||||
domain: frontend
|
||||
frameworks:
|
||||
- tailwindcss
|
||||
@@ -258,7 +279,7 @@ territory:
|
||||
|
||||
| Persona | Phases | Removed After |
|
||||
|---------|--------|---------------|
|
||||
| security-auditor | 1 (admin token + apply gates), 3 (embedding key redaction), 4 (resume bounds + PII), 5 (sitemap origin), 6 (final review) | milestone complete |
|
||||
| security-auditor | 1 (store/ledger review: hash chain, canonical serialization, partial unique, no-delete path), 2 (gate order + G-319 supersession PII review on application routes), 4 (export integrity: determinism rules, methodology honesty), 6 (final review: no PII in logs/releases) | milestone complete |
|
||||
|
||||
All other personas span the milestone. Deactivated personas receive no tasks.
|
||||
|
||||
@@ -266,9 +287,9 @@ All other personas span the milestone. Deactivated personas receive no tasks.
|
||||
|
||||
| Conflict | Resolution |
|
||||
|----------|------------|
|
||||
| data-engineer vs backend-engineer (store.py / api routes) | data-engineer owns base.py/store.py/ingest.py schema + persistence; backend-engineer owns config.py/main.py/api routers/DI wiring — the marketplace store is consumed via deps.py, never imported directly by routes |
|
||||
| data-engineer vs ai-engineer (embedding storage) | data-engineer owns the embedding TABLE + BLOB codec; ai-engineer owns the EmbeddingProvider protocol + mock hash + search cosine math; the store's put/get_vector is the seam |
|
||||
| ai-engineer vs backend-engineer (factory/config) | backend-engineer owns config surface + factory wiring in main.py; ai-engineer owns provider implementations (openai_compat.py + mock.py) |
|
||||
| frontend-engineer vs data-engineer (wire types) | data-engineer owns packages/types marketplace shapes (dual-schema sync); frontend-engineer consumes them in engine-client + shells; wire contract = pydantic contracts in marketplace/base.py |
|
||||
| security-auditor vs backend-engineer (admin routes) | backend-engineer implements require_admin; security-auditor reviews fail-closed behavior + may patch security defects directly in api/marketplace_admin.py + resume.py (its territory) |
|
||||
| backend-engineer vs frontend-engineer (engine-client.ts) | backend-engineer owns the API contract shapes the client consumes; frontend-engineer owns engine-client.ts itself (the placements section) — the existing identity/marketplace/billing/employer sections are frozen contracts neither side may re-shape; the new wire types land in packages/types/placement.ts (data-engineer dual-schema-syncs, lead-developer reviews the pins) |
|
||||
| backend-engineer vs security-auditor (api routes) | backend-engineer implements the routes/deps/gates; security-auditor reviews and may patch security DEFECTS directly in api/placements_admin.py + placements/store.py (its territory) — implementation vs review stays with backend |
|
||||
| backend-engineer vs data-engineer (placements/store.py) | data-engineer owns the schema + store methods (rows, chain, canonical serialization); backend-engineer owns routes/deps/wiring that compose it; the transition_application METHOD contract is data territory (the transaction + hash append), the routes calling it are backend territory |
|
||||
| backend-engineer vs data-engineer (application.status column) | the placements store is the ONLY post-creation status writer (R-78) — marketplace/store.py's insert_application writes it once at creation; no route or future store adds a second writer outside the one-transaction discipline |
|
||||
| frontend-engineer vs security-auditor (PII surfaces) | frontend-engineer implements the application surfaces (learner_id visible on own applicants); security-auditor reviews the G-319 pin split (counts-only stays on own-postings lists) and pins the cross-entity 403 negative arms; neither patches the other's files — findings flow through lead-developer |
|
||||
| lead-developer vs any | lead-developer coordinates only, does not directly modify code files |
|
||||
+161
-204
@@ -1,241 +1,198 @@
|
||||
# Nextcraft — PLAN.md (v0.6 Marketplace Engine)
|
||||
# Nextcraft — PLAN.md (v0.11 CIRR-Style Placement Tracking and Audit)
|
||||
|
||||
## Overview
|
||||
|
||||
**Milestone:** v0.6 — Marketplace Engine (D-047): the real marketplace backend behind the existing surfaces.
|
||||
**Tag line:** v0.5.x patches (P0 → v0.5.0 … P6 → v0.5.6 = milestone release) on the v0.5.x line
|
||||
**Branch:** milestone/v0.6-marketplace-engine
|
||||
**Milestone:** v0.11 — CIRR-Style Placement Tracking and Audit (Feature, D-098): the machinery that makes the guiding outcome measurable and auditable — the placement record model (the 9th D-027 store: `PlacementRow` with the partial-unique one-active-placement-per-application guard + the append-only `PlacementEventRow` ledger, one global sha256 hash chain with a `UNIQUE(prev_hash)` fork backstop), the employer-side application state machine extending the v0.6 `submitted`-only status (the forward-only D-099 matrix, per-target employer routes under `/v1/employers/applications`, learner withdraw, the operator lane incl. revoke + the R-80 re-hire), placement reporting (distinct-learner counts cumulative toward ≥1,000, per employer, per start-date cohort month), and the audit-grade export (self-contained JSON + human summary generated from the same document, methodology stating its own three pilot gaps, re-export determinism). Mock-first doctrine holds: no third-party auditor integration (the export IS the deliverable), tests never call a cloud, zero new dependencies (D-112).
|
||||
**Tag line:** phase tags advance the v0.10.x line (P0 → v0.10.0 … P6 → v0.10.6 = milestone release), continuing from the v0.10 milestone release (v0.9.6)
|
||||
**Branch:** milestone/v0.11-placement-tracking (phase work on phase/NN-* branches; Phase 0 on phase/00-pre-execution)
|
||||
|
||||
**Phase list:** P1 Postings backend + aggregation adapter (REQ-6-001) → P2 AI tagging (REQ-6-002) → P3 Semantic vector search (REQ-6-003) → P4 Enrichment + resume parsing (REQ-6-004/005, two parallel workstreams) → P5 SEO programmatic pages (REQ-6-006) → P6 Final review + ship.
|
||||
**Phase list (requirement mapping):**
|
||||
|
||||
**Wave order (D-059, binding):** P1 ships the backend **WITH the web client shells** in the same phase — a live store behind mock-reading pages proves nothing; REQ-6-001's success criterion is surfaces reading real data. P2 before P3 because tag facets drive the sidebar filters AND the P3 posting embedding text includes the normalized tags. P4's two workstreams (enrichment / resume) are independent — parallelizable within the phase. P5 SEO depends only on P1 (routes exist to enumerate) but stays last-before-final: the sitemap needs `published` postings and the board metadata should reflect final facets. P6 final review + ship.
|
||||
| Phase | Requirement | Focus |
|
||||
|-------|-------------|-------|
|
||||
| P1 | REQ-11-001 | Placement store + evidence ledger: placements/ module (PlacementRow + PlacementEventRow global hash chain, partial UNIQUE active guard), the D-099 matrix + event vocabulary in base.py, the ONE transactional transition_application (flush-then-hash-then-commit), main.py wiring — zero web changes |
|
||||
| P2 | REQ-11-002 | Application state machine: employer per-target routes (G-311 gate order: 401 → 403-claim → 403-cross-entity → 409), learner withdraw (D-043 stack), placements_admin operator lane (generic transition + revoke + the R-80 re-hire), G-319 pin split |
|
||||
| P3 | REQ-11-003 | Placement reporting: admin overview (distinct learners, by_employer, by_cohort_month), per-employer placement view, placement.ts wire types + engine-client placements section, /employer/applications page + overview placements section replacing the mock block |
|
||||
| P4 | REQ-11-004 | Audit export: the self-contained JSON + summary-from-same-JSON, methodology with the three pilot gaps, determinism rules, admin web placements block + export links, the full-chain E2E proof |
|
||||
| P5 | REQ-11-005 | Learner visibility: GET application-status read, job-detail status panel + placement confirmation, badge honesty |
|
||||
| P6 | — | Final review + audit + milestone ship (v0.10.6 = milestone release) |
|
||||
|
||||
**Research decisions D-048..D-059 are binding design contracts.** This plan operationalizes them; it does not re-litigate them. Assumptions A-401..A-412 are resolved fact.
|
||||
**Wave order (binding): ledger before machine before reporting before export before visibility.** P1 builds the store + chain every later phase composes (P2's transitions append to it in one transaction; P3's counts read the rows it writes; P4's export embeds the chain it maintains; P5's panel renders the events it records). P2 precedes P3 because reporting counts placements that only the hired transition creates — a report over an un-exercised machine proves nothing. P3 precedes P4 because the export's summary block is the D-107 computation (one truth source — the summary is generated from the same JSON) and the admin web block consumes both the overview and the export. P4 precedes P5 by requirements priority (REQ-11-004 critical ships before REQ-11-005 medium; no dependency runs the other way — the learner panel composes only P1/P2 machinery). Each phase is a vertical slice: store/schema → routes → web wiring → tests green in the same wave → ship.
|
||||
|
||||
**Environment facts (unchanged):** python 3.11.2 (venv at apps/ai-service/.venv, pip-only — A-009), node v24.15.0, pnpm 12.3.4, SQLite shared `Settings().db_path` (`~/.nextcraft/data/nextcraft.db`), tests NEVER call the cloud (mock providers + httpx MockTransport), secrets env-only (D-014), runtime state under `~/.nextcraft/` (D-039).
|
||||
**Binding contracts:** clarify decisions D-099..D-112 (PROJECT.md) and research conclusions R-67..R-80 (RESEARCH.md) are design contracts; this plan operationalizes them, never re-litigates. Module layout is decided: `ai_service/placements/{__init__,base,store}.py` — NO service.py (D-112/R-74 — routes compose the store via `app.state` DI); routes: the applications section of api/employers.py, learner routes in api/marketplace.py, `api/placements_admin.py`; `tests/placements/`; `packages/types/placement.ts`.
|
||||
|
||||
**Verification hooks (every phase, release-blocking):** `pnpm ai:test` (488 backend tests), web `tsx --test` (22), CLI `node:test` (61), `pnpm typecheck` (8 projects), `pnpm ai:lint` (ruff check), `pnpm build` (static export emits). **Hermeticity rule (v0.5 P04 lesson): every new test pins `Settings(db_path=tmp_path/...)` — never `~/.nextcraft`, never the cloud.**
|
||||
**Environment facts (probe-verified, R-67..R-80):** the hash covers the row's own autoincrement id → the append must be flush-then-hash-then-commit inside one Session, ALL appends funneling through the one transition_application (R-70; decide_claim is the all-or-nothing template employers/store.py:600-652; the ledger must have NO delete path — INTEGER PRIMARY KEY reuses max+1 if the top row is deleted; verification is O(n) sha256 over tiny rows); the matrix precedent is billing's `_VALID_TRANSITIONS` with empty-tuple terminals (billing/store.py:84-90; the 409-matrix test trio tests/billing/test_store.py:400-418; zero migration — existing rows are all `submitted`, marketplace/store.py:211); the shared-DB multi-engine topology is shipped (8 stores, identical pragmas; global SQLModel metadata means create_all on any engine creates every registered table, employers/store.py:400; cross-module import is family-sanctioned employers/base.py:39; NO cross-family foreign keys — G-302 ID references at read); export determinism needs pinned orderings + total generated_at exclusion + float absence (R-73; the list_postings ordering discipline marketplace/store.py:940-948); main.py wiring sites verified (lifespan getattr-guard 182-190/195-200, close() in the finally 335-336, routers beside the employers block 400-411, CORS already carries Authorization 357, G-11 admin boot warning 251-256, deps.py:98); gates verified (require_employer_session employers.py:173-191, _require_claimed :467-484, _own_posting_or_404 :487-503, per-target route idiom :635/:687, provenance `"account:{id}"` :792; learner stack marketplace.py:46-52 → :358 → :359 with window :66-76, `_APPLY_TIMES` :58, cap :63; operator lane employers_admin.py:47 + OPERATOR :54, guard marketplace_admin.py:62-85); web rails verified (engine-client sections — SessionRequiredError :126-131, ClaimRequiredError :136, parseError :146, placements section appends after employer billing :1114; pins.test.ts employer dual-schema block :267-374 + G-319 block :376+; the four surfaces — employer-overview-client.tsx :162/:190-230 real vs mock block :335-372 labelled :351, job-detail-client.tsx apply :95-115 + EngineError 409/404 :103-105 + confirmation :253, moderation page :3/:35 → employer-network-panel.tsx :56 + adminToken/locked-state :28-40); test templates verified (make_client state-injection tests/marketplace/conftest.py:80-120; conftest resets :123-131 + tests/employers/conftest.py:31-33; partial-index sqlite_master pin test_claims_store.py:75-88; gate pins test_postings_write.py:225-234/:315 + test_marketplace_api.py:188; counts-only pin test_postings_read.py:216); two WAL facts (insert_application :873-901 never touches status post-creation; the tamper test's second engine sees the mutation only after commit); three clocks, three serialization rules (start_date date-only ISO YYYY-MM-DD with cohort month `strftime("%Y-%m")`; created_at naive-stored re-labeled via `_as_utc` marketplace/store.py:263-267 — `isoformat()` emits +00:00 for aware, nothing for naive, so the chain pins ONE normalization; generated_at export-only; learner_id is an opaque G-5 handle the 422 scrubber's pii_fields main.py:439 never sees).
|
||||
|
||||
**Verification commands (phase gates — the repo's own scripts):**
|
||||
|
||||
- `pnpm lint` (turbo lint — eslint across all TS workspaces) and `pnpm ai:lint` (ruff on ai-service)
|
||||
- `pnpm typecheck` (turbo typecheck — tsc workspaces) and `pnpm ai:typecheck` (mypy — zero new overrides; stdlib-only, D-112 keeps the D-086 regime intact)
|
||||
- `pnpm ai:test:fast` (FAST=1 — `-m "not real_server and not userns"` per D-063; tests/placements/ joins the fast lane)
|
||||
- `pnpm web:test` (node:test incl. pins.test.ts) + `pnpm cli:test` (unchanged surface, regression guard)
|
||||
- `pnpm --filter web build` (static export, D-039 unchanged) on web-touching phases (P3, P4, P5)
|
||||
|
||||
**NFR note:** this is a Feature milestone — no purity gate; `feat:` commits are expected and scoped to ai_service/placements/, api/placements_admin.py + the employers.py/marketplace.py route sections + deps.py/main.py wiring, tests/placements/, packages/types/placement.ts, the employer/job-detail/admin web surfaces.
|
||||
|
||||
**Secrets policy (binding):** no new secrets this milestone — AI_ADMIN_TOKEN stays env-only (D-014); the placements admin lane inherits require_admin's fail-closed behavior + the G-11 boot warning free (R-74); the export carries no credentials and no identity PII (learner_id is an opaque allowlisted handle, R-79 — name/email/DOB are never stored, identity/base.py:25-33); tests use tmp_path DBs with no credential values; no secret appears in any committed file, log line, or release asset.
|
||||
|
||||
---
|
||||
|
||||
## Phase 1: Postings Backend + Aggregation Adapter (REQ-6-001)
|
||||
## Phase 1: Placement Store + Evidence Ledger (REQ-11-001)
|
||||
|
||||
**Goal:** The 6th D-027 store family, the PostingSource adapter contract with the seeded corpus, the `/v1/marketplace/*` + admin API, the real apply route — and the web surfaces reading all of it at runtime.
|
||||
**Goal:** The placements module exists and is proven: the 2-table 9th D-027 store (immutable-at-creation PlacementRow + the append-only global hash-chain PlacementEventRow), the D-099 matrix + event vocabulary in base.py, the ONE transactional transition_application with flush-then-hash-then-commit, main.py wiring — tamper-tested, fork-tested, zero web changes, zero new dependencies.
|
||||
|
||||
### Wave 1-1: backend core
|
||||
### Wave 1-1: Module core — contracts + matrix + schema (backend-engineer + data-engineer, sequential)
|
||||
|
||||
- **Task 1-1-01** (data-engineer): `ai_service/marketplace/base.py` — pydantic contracts per D-048: `Employer` (id, source, external_id, name + raw ingested fields), `IngestPosting` (A-402 shape: source, external_id, employer + posting fields), `Posting` (full row shape: status `draft|published|closed`, tags JSON column, portable scalar columns, posted_at), `PostingTags` (skills ≤10, seniority, category). Module mirrors D-031 boundary: never imports `agents/` or `api/`.
|
||||
- **Task 1-1-02** (data-engineer): `ai_service/marketplace/store.py` — `MarketplaceStore` protocol + SQLite impl per D-049 **(amended by G-104: six tables)** (`posting`, `employer`, `embedding`, `application`, `employer_enrichment`, `learner_profile`) on the shared `Settings().db_path`; identity/store.py mechanics exactly: WAL/synchronous=NORMAL/busy_timeout/foreign_keys pragmas, `sa_type` portable columns, `_validate()` hooks, surfaced IntegrityError, tz normalization. Unique constraints: `(source, external_id)` on posting + `(posting_id, learner_id)` on application (idempotent upserts A-402/A-408); employer unique per `(source, external_id)`; `embedding` table created now (posting_id PK, `vector` BLOB, `model`, `dim`), its codec/methods land in P3 (the data↔ai seam, per territory table); `learner_profile` (learner_id PK, profile JSON, confirmed_at, model — G-104, consumed in P4).
|
||||
- **Task 1-1-03** (backend-engineer): `config.py` — `admin_token: str = ""` (`AI_ADMIN_TOKEN`), `public_base_url: str = ""` (`AI_PUBLIC_BASE_URL`, placeholder consumed by P5 sitemap); `.env.example` documents both (keys never in code/commits). `api/deps.py` — `get_marketplace_store` (app.state DI; routes NEVER import the store directly — territory rule). `main.py` lifespan — `app.state.marketplace_store`; **loud boot warning when `admin_token` is unset** (G-11; admin routes stay 403-fail-closed regardless).
|
||||
- **Task 1-1-01** (backend-engineer): `ai_service/placements/__init__.py` + `base.py` — pydantic contracts + constants: `TRANSITION_MATRIX` per D-099 (snake_case `submitted → in_review → interview → offer → hired|rejected|withdrawn`, forward-only with skip-forward — any non-terminal may move to any LATER stage or any terminal, terminals have empty-tuple outgoing edges, the billing/store.py:84-90 shape); `APPLICATION_STATUSES`; actor vocabulary `employer|learner|operator|system` (the `_BILLING_EVENT_KINDS` shape billing/store.py:92, D-101); event-name vocabulary per D-101 + **R-80's placement lane**: application-stage events (NO backfill — `application.submitted` is never fabricated for v0.6 rows, D-101/A-304; one event per transition: in_review/interview/offer/rejected/withdrawn/hired) + placement-level events (`placement.created` on hired, `placement.revoked` on the D-102 correction, `placement.rehired` on the R-80 operator re-hire); `PlacementRead`/`PlacementEventRead`/`EmployerApplicationSummary` response contracts (dual-schema-pinned P3 per D-110); `HireTransitionRequest {role_title, start_date}` (D-103: start_date is a pydantic `date` — never a datetime, future + past allowed, timezone-free by construction; **G-324: role_title = Field(min_length=1, max_length=200) — empty-string → 422, the house Field shape marketplace/base.py:68-71**); `GENESIS_HASH = "0" * 64` module constant (D-101, test-pinned). No service.py — routes compose the store via app.state DI (D-112).
|
||||
- **Task 1-1-02** (data-engineer): `placements/store.py` — the 9th D-027 store (D-112/R-72): tables `placement` (id PK, learner_id, employer_id, posting_id, application_id indexed, role_title, start_date stored ISO `YYYY-MM-DD` — a calendar date, no datetime coercion in its path, R-79; status `active|revoked`, created_at, decided_at) + `placement_event` (auto-increment id PK, application_id nullable+indexed, placement_id nullable, event_type, actor_type, actor_ref, payload JSON, prev_hash **UNIQUE**, hash, created_at). Bare `placement` is FREE (D-095's prefix rule was collision-driven — marketplace owns posting/employer/application, no placement table exists). D-102 semantics: role_title/start_date/decided_at/learner_id/employer_id/posting_id/application_id are set once at the hired transition and NEVER rewritten (a silent rewrite is exactly the tamper the chain detects); `status` is the ONLY mutable column with exactly one transition `active → revoked`; decided_at = the hired transition's store-stamped created_at (`datetime.now(UTC)`); the one-active-per-application guard is a **partial UNIQUE index `uq_active_placement_per_application` ON application_id WHERE status='active'** (the G-316 `uq_pending_claim_per_entity` shape, employers/store.py:161-167 — revoked rows stay in history; a re-hire after a mistaken revoke creates a fresh row). Mechanics mirror employers/store.py exactly (D-112): `_sqlite_connect` pragmas WAL / synchronous=NORMAL / busy_timeout=5000 / foreign_keys=ON, `sa_type` portable columns, `_validate()`/`_normalize()` hooks, `_as_utc` re-labeling, Protocol `PlacementStore` + `SQLitePlacementStore` pair, surfaced IntegrityError, `_constraint_error` helper; global-metadata `create_all` idempotent (checkfirst adds both tables to every existing DB at next boot — the shipped D-095 behavior, employers/store.py:398-400); NO cross-family foreign keys (employer/learner/posting/application are ID references resolved at read/export, G-302); **NO delete method and no DELETE SQL anywhere in the module** (R-70: deleting the top row makes INTEGER PRIMARY KEY reuse max+1 — chain-integrity hole; source-pinned). Canonical serialization per D-101/R-69/R-79: `_canonical_event_json` = `json.dumps({...}, sort_keys=True, separators=(",", ":"))` with created_at normalized via **always `_as_utc(dt).isoformat()` — ONE pinned normalization** (the R-79 pitfall: isoformat emits `+00:00` for aware, nothing for naive — drift between the hashing and reading paths breaks the chain on first re-read) and **no floats in payload ever** (str/int/bool/None only, R-69); `hash = hashlib.sha256` hexdigest over the canonical JSON + prev_hash. Tests `tests/placements/test_store.py`: GENESIS_HASH pinned; table existence via sqlite_master (2 tables) + the partial-index SQL pinned (the test_claims_store.py:75-88 template); pragma pins; duplicate prev_hash → IntegrityError surfaced; no-delete-path source pin; tz round-trip (naive stored, aware read, canonical form stable).
|
||||
- **Task 1-1-03** (data-engineer): the chain append + `transition_application` — D-100/R-70: `transition_application(application_id, to_status, actor_type, actor_ref, role_title=None, start_date=None)` — ONE Session on the placements engine covering both tables (R-72: the marketplace `application` row is written through it — the sanctioned D-100 deliberate exception; both tables + the status write land in ONE commit, the decide_claim all-or-nothing precedent employers/store.py:634-652 — the two-commit alternative's crash window voids the tamper-evidence the milestone sells): get_application (marketplace/store.py gains ONLY this point read, the get_posting shape :578-584 — insert_application and every other marketplace seam unchanged) → matrix validation (module InvalidTransition → 409 at routes) → update `application.status` → read chain head (`ORDER BY id DESC LIMIT 1`) → construct the event row with prev_hash=head → **`session.flush()` to obtain the autoincrement id → compute hash → set the column → on hired: create the PlacementRow (decided_at = this transition's created_at; role_title/start_date REQUIRED, D-103) + append `placement.created` with placement_id set → `session.commit()`** — flush-then-hash-then-commit, and ALL ledger appends funnel through this one method (a second append path races prev_hash; the UNIQUE backstop catches it as a lost event). Column ownership stated in the module docstring (R-78): marketplace insert_application (:873-901) writes status once at creation; the placements store is the ONLY post-creation writer of application.status — no route or future store adds a second writer outside the one-transaction discipline. Store methods: `verify_chain` (recompute the walk from GENESIS_HASH → head; O(n) sha256 over tiny rows — milliseconds at pilot scale, R-70), `get_placement`, `get_application_events` (id-ordered), `list_active_placements`, `revoke_placement` (the one status-only mutation + `placement.revoked` event, one transaction, operator-only by route), `rehire_placement` (R-80: fresh PlacementRow + `placement.rehired` event WITHOUT touching the application's terminal status — revoked rows don't match the partial WHERE, the exact G-316 property employers/store.py:159-167). Tests: chain-walk verification green after N appends; hired → PlacementRow + both events chained (application_id event + placement_id event); **tamper test** — direct row mutation via a second engine on the same file (mutation commits before the verification walk reads, R-78 WAL snapshot isolation) → verify_chain fails; **fork test** — a second row claiming the same prev_hash → IntegrityError surfaced; **concurrent-transition arm** (the test_concurrent_consumes_one_post_left shape, tests/billing/test_store.py:335): two sessions transition the same application → one winner commits, the loser surfaces IntegrityError/InvalidTransition — never two events on one prev_hash; revoke → status revoked + event; rehire after revoke → fresh active row + three-event ledger sequence (hired, placement.revoked, placement.rehired).
|
||||
|
||||
### Wave 1-2: ingest + routes
|
||||
### Wave 1-2: main.py wiring + deps + conftest (backend-engineer)
|
||||
|
||||
- **Task 1-2-01** (data-engineer): `ai_service/marketplace/ingest.py` — `PostingSource` protocol `fetch() -> Iterable[IngestPosting]`; `seeded_corpus` adapter over `marketplace/seed_corpus.json` — **a Python fixture file ported ONCE from `packages/mock-data/jobs.ts` (20 jobs) + `employers.ts` (10 employers)**, shared IDs per D-021 convention, mock `matchScore` DROPPED (D-051 computes real ones); `run(source)` upserts idempotently on `(source, external_id)` (employer rows upserted the same way). **Ingest-status contract (G-102): seed-port postings enter as `published` with their original `postedAt`; admin-authored postings start `draft`** — otherwise the board/facets/P1's success criterion are empty after ingest. No scheduler/crawler — the 3M+ corpus lands later as a third adapter with zero store/route changes.
|
||||
- **Task 1-2-02** (backend-engineer): `ai_service/api/marketplace.py` — public router: `GET /v1/marketplace/postings` (list, limit/offset, published only), `GET /v1/marketplace/postings/{id}` (404 honest), `GET /v1/marketplace/employers/{id}` (404 honest; raw fields now, merged+provenance in P4). Mounted in main.py. **The G-18 stub route MOVES here from `api/identity.py` and is deleted there** (identity keeps only its gate exports, D-048).
|
||||
- **Task 1-2-03** (backend-engineer + security-auditor): `ai_service/api/marketplace_admin.py` — `require_admin` FastAPI dependency (X-Admin-Token or Bearer vs `Settings().admin_token` as **`SecretStr`, compared via `secrets.compare_digest` (G-108)**): **unset token → every admin route 403, never open (D-057 fail-closed)**; routes: `POST /admin/postings` (create draft), `POST /admin/postings/{id}/publish` + `/close` (lifecycle `draft→published→closed`, invalid transition → 409), `POST /admin/ingest` (runs the seeded source), `GET /admin/applications` (review list, filterable by posting). Admin routes do NOT pass learner gates (different principal class, D-057).
|
||||
- **Task 1-2-04** (backend-engineer): apply route per D-058 — `POST /v1/marketplace/apply`, body `{posting_id}`: **gate composition binding (D-043, unchanged order): G-5 allowlist → `require_verified_adult` (imported from identity) → rate caps**; then posting must exist and be `published` (404 / 409); insert `application` row (status `submitted`); duplicate `(posting_id, learner_id)` → idempotent 200-with-existing; honest confirmation `{application_id, posting_id, status: "submitted"}`. All `stub`/`mock` markers die.
|
||||
- **Task 1-2-01** (backend-engineer): wiring per D-112/R-74: `deps.py` `get_placement_store` beside get_employer_store (deps.py:98); main.py lifespan getattr-guard `placement_store` directly after the employers block (main.py:195-200 template) + `close()` in the finally block (main.py:336); CORS already carries Authorization (main.py:357 — no change); the G-11 admin boot warning (main.py:251-256) covers the placements admin free. Zero new config knobs, zero .env.example changes (no new throttle — D-104 rides the existing window; the router file + mounts land with its first routes in P2, the main.py:400-411 pattern). `tests/placements/conftest.py` NOW (D-111/G-313/open-risk-4): the make_client state-injection fixture (the tests/marketplace/conftest.py:80-120 shape — tmp_path DB, create_app, `app.state.placement_store` injected, hermetic zero-network by construction — no MockTransport needed, no external calls exist) + the **autouse `_APPLY_TIMES` reset (tests/marketplace/conftest.py:123-131 pattern) before/after EVERY placements test — the withdraw route rides that limiter in P2; without the reset the suite self-429s (the G-313 lesson applied before it ships)**.
|
||||
|
||||
### Wave 1-3: web client shells (D-055)
|
||||
### Wave 1-3: P1 security review + phase gate (security-auditor + lead-developer)
|
||||
|
||||
- **Task 1-3-01** (data-engineer): `packages/types/marketplace.ts` — marketplace wire shapes (`PostingSummary`, `PostingDetail`, `EmployerProfile` with `{value, source}` provenance fields ready for P4, `ApplicationConfirmation`, `PostingFacets`) — **dual-schema sync with `marketplace/base.py`**: field-for-field parity, same change in both places.
|
||||
- **Task 1-3-02** (frontend-engineer): `apps/web/lib/engine-client.ts` marketplace section — `listPostings(filters)` (**paged fetch-all: walks limit/offset pages until exhausted, documented ≤10⁴ bound; response carries `total_published`; "Showing X of Y" computed over the fetched set with an honest truncation notice — G-103**), `getPosting(id)`, `getEmployer(id)`, `applyPosting(posting_id)` typed against the new `packages/types` shapes (`searchPostings` lands P3); 403 discrimination (verify-CTA vs allowlist) already works and is reused.
|
||||
- **Task 1-3-03** (frontend-engineer): board — `(marketplace)/marketplace/page.tsx` keeps its server shell; the grid + `JobFilters` become fetch-backed (client shell over `listPostings`); honest empty state (zero postings → message, never fake cards); filter option lists stay UI constants this phase (P2 derives them from real tags).
|
||||
- **Task 1-3-04** (frontend-engineer + backend-engineer): detail + employer shells **(G-101 — do NOT remove `generateStaticParams`; Next 15 hard-throws E87 under `output:'export'` for any dynamic route without it, even returning `[]`)**: keep `generateStaticParams` on `jobs/[jobId]` + `employers/[employerId]` returning ONE placeholder param (`{jobId: '_'}`) so exactly one client-shell page exports per route; add FastAPI catch-all routes `GET /marketplace/jobs/{id}` + `GET /marketplace/employers/{id}` (trailing-slash variants included — `trailingSlash: true`) serving that exported shell file — the same routes-beat-the-mount mechanism P5 relies on for sitemap; runtime client fetch → render, `notFound()` on 404; apply button wired: 403 verify-CTA renders the enrollment prompt, 409 closed renders honestly, success shows the confirmation payload. `packages/mock-data` jobs.ts/employers.ts go dormant for the marketplace path (still imported by employer/admin mockups — NOT deleted). Rewrite `tests/identity/test_identity.py:444`'s honest-501 pin onto the marketplace router in this phase (G-110).
|
||||
- **Task 1-3-01** (security-auditor): ledger review (P1 scope, D-111's "an audit ledger nobody has tried to break is theater"): canonical serialization pinned to ONE normalization (the hashing/reading drift pitfall caught by tamper tests), GENESIS pinned, UNIQUE(prev_hash) fork backstop real (IntegrityError surfaced never swallowed), flush-then-hash-then-commit with a single append funnel (no second writer), no-delete-path pinned, partial-unique active-placement guard emitted by create_all (G-316 shape), actor vocabulary closed, no floats in payload, no PII in payload fields. Findings recorded; P0s fixed in-phase.
|
||||
- **Task 1-3-02** (lead-developer): P1 phase gate — `pnpm ai:lint` + `pnpm ai:typecheck` (zero new mypy overrides — stdlib only) + `pnpm ai:test:fast` + `pnpm web:test` + `pnpm cli:test` green (additive module — marketplace/billing/employers suites untouched); the D-100 discipline check (one transition_application, no second status writer, no second append path); test counts recorded.
|
||||
|
||||
### Wave 1-4: tests
|
||||
## Phase 2: Application State Machine (REQ-11-002)
|
||||
|
||||
- **Task 1-4-01** (data-engineer): store contract tests (tmp_path db — hermeticity rule): five tables created on the shared file, unique constraints fire on duplicates, pragmas + `_validate` hooks pinned; ingest idempotency (double-run → identical rows, no dupes); **seed-port fidelity check** (20 postings + 10 employers, IDs match the TS fixtures, `matchScore` absent from every API payload).
|
||||
- **Task 1-4-02** (backend-engineer + security-auditor): route tests — admin token fail-closed matrix (unset → 403 + boot warning in caplog; wrong/absent header → 403; correct → 200); lifecycle 409 on invalid transitions; apply gate composition (allowlist 403 fires FIRST for non-pilot ids, verify-CTA 403 for unverified, 429 at cap, 404/409 states, duplicate → 200 idempotent); 404s on missing postings/employers.
|
||||
- **Task 1-4-03** (frontend-engineer): web tests (`tsx --test` pattern) — engine-client marketplace functions; shells render fetched data; `notFound()` on 404; empty-board state; apply-flow states.
|
||||
**Goal:** The hiring pipeline is live: employers drive per-target transitions on their own claimed-entity applications (G-311 gate order, audit-logged, ledger-chained in the same transaction), learners withdraw their own, the operator lane transitions/revoke/re-hire with provenance — every matrix arm tested, the G-319 pin split enforced.
|
||||
|
||||
### Wave 2-1: Employer application routes + G-319 pin split (backend-engineer)
|
||||
|
||||
- **Task 2-1-01** (backend-engineer): api/employers.py gains `GET /v1/employers/applications?status=` (own claimed-entity pipeline — session → claimed → applications resolved through own postings via a new in-pattern marketplace grouped read, the count_applications_by_posting discipline store.py:915-932, never per-row N+1; the `EmployerApplicationSummary` contract with **learner_id visible per the G-319 supersession, D-105: application-scoped reads expose learner_id ONLY for applications on the session's own claimed-entity postings**) + the per-target action routes `POST /v1/employers/applications/{application_id}/in-review | /interview | /offer | /reject | /hire` (the per-target idiom employers.py:635/:687 — the matrix stays OUT of request bodies; hire body `{role_title, start_date}` per D-103, both REQUIRED; **G-324: role_title min_length=1/max_length=200 — the empty-string 422 arm pinned beside the missing-fields arm**). Gate order G-311 (D-105/R-75): **401** (require_employer_session employers.py:173-191) → **403** claim (_require_claimed :467-484) → **403** cross-entity (fetch application → posting → `posting.employer_id != claimed` — the _own_posting_or_404 shape :487-503 applied through the application's posting) → **409** transition (never a 409 before a 403). Every route calls the ONE transition_application with `actor_type="employer"`, `actor_ref=f"account:{account.id}"` (the :792 provenance shape) + appends an `employer_audit_events` row (the D-089 one-queryable lane). Tests `tests/placements/test_employer_transitions.py`: gate-order pins (no token → 401, unclaimed → 403, foreign application → 403 — never a 409 first; the test_postings_write.py:225-234/315 pin shape); matrix 409 arms (every illegal move: backward `offer → in_review`, terminal-source `hired → anything`/`rejected → anything`/`withdrawn → anything`); skip-forward arms legal (`submitted → hired` fast-track, `submitted → interview`, `in_review → reject` — R-71); hire → 201 + PlacementRow + chained events + audit row; hire without role_title/start_date → honest 422 with the D-103 required-fields detail; **G-324 arm: role_title="" → 422**.
|
||||
- **Task 2-1-02** (backend-engineer): the **G-319 pin split** (R-77/D-105, binding): the own-postings LIST stays counts-only — tests/employers/test_postings_read.py:216 green UNCHANGED (the v0.10 boundary holds there); learner_id appears ONLY on application-scoped responses for own-posting applications; cross-entity → 403 with NO application data (anti-enumeration preserved). Pins in test_employer_transitions.py: the list response carries no learner identifiers; the application-scoped GET carries learner_id on own postings; a foreign application's transition/list never returns any application payload.
|
||||
|
||||
### Wave 2-2: Learner withdraw + operator lane incl. the R-80 re-hire (backend-engineer)
|
||||
|
||||
- **Task 2-2-01** (backend-engineer): api/marketplace.py gains `POST /v1/marketplace/applications/{application_id}/withdraw` body `{learner_id}` (D-104): the **D-043 composition unchanged** — `_enforce_allowlist` (marketplace.py:46-52) → `require_verified_age(18)` (:358) → `_check_apply_rate` (:359; window :66-76, `_APPLY_TIMES` :58, cap 5/rolling-60s :63 — the EXISTING window, no new throttle knob); 403 when the application is not the caller's, 409 when terminal (D-099: `withdrawn` is learner- or operator-triggerable, NEVER an employer session — employers reject instead); calls the same transition_application with `actor_type="learner"`; composes the placements store via app.state DI (deps.py). **G-323 (binding): the apply route's idempotent arm gains a terminal-state guard** — a returned application in `withdrawn`/`rejected`/`hired` → 409 `{"reason": "application_terminal", "status": …}` (the posting_not_published 409 shape, marketplace.py:366-373), never a 200 "applied" confirmation; no new application row (the unique key stands); recovery is visibility (G-322's mine-read + status panel), not resurrection. Tests `tests/placements/test_learner_withdraw.py`: unallowlisted → 403, unverified → 403, foreign application → 403, own+submitted → 200 `withdrawn` + ledger event actor learner, terminal → 409; **apply → withdraw → re-apply → 409 application_terminal (never a 200)**; the conftest reset proves no self-429 (5 withdraws inside the window → the 6th 429s honestly, reset between tests).
|
||||
- **Task 2-2-02** (backend-engineer): `api/placements_admin.py` (D-106): prefix `/v1/placements/admin`, `require_admin` IMPORTED from marketplace_admin (the billing_admin.py:27 import precedent, employers_admin.py:47 — token namespaces cannot collide, D-090); router mounts in main.py beside the employers block (main.py:400-411). Routes: `POST /v1/placements/admin/applications/{application_id}/transition` `{to, role_title?, start_date?}` — the generic operator remediation route validated against the SAME D-099 matrix (role_title/start_date required iff `to=hired`); **G-327 (binding): `to` is a pydantic Literal of the seven D-099 statuses — unknown value → 422 (body validation), matrix-illegal known value → 409 InvalidTransition; the route never sees a status outside the vocabulary (no 500s, no silent acceptance; test arm: garbage `to` → 422)**; `actor_type="operator"`, `OPERATOR = "operator"` route-level provenance (employers_admin.py:54 — no per-operator accounts, D-094); the operator can drive ANY matrix-legal transition including `withdrawn` on a learner's behalf (remediation with provenance, the D-083 lane). `POST /v1/placements/admin/placements/{placement_id}/revoke` (D-102: the one `active → revoked` correction). **THE R-80 RE-HIRE ROUTE (pinned explicitly): `POST /v1/placements/admin/placements/by-application/{application_id}/re-hire` `{role_title, start_date}`** — after the first hire the application is terminal (`hired → hired` is a 409 on every matrix-validated surface — the R-80 coherence gap); the re-hire creates the FRESH PlacementRow + appends `placement.rehired` (actor operator) WITHOUT touching the application's terminal status — the ledger reads hired → revoke → rehire as three events, never fabricating a second application transition (the rejected matrix-amendment and revoke+reapplication shapes stay rejected per R-80); structurally safe because revoked rows don't match the partial WHERE status='active' (the exact G-316 property). **G-326 (binding): the re-hired PlacementRow's `decided_at` = the re-hire event's store-stamped created_at (D-102's `datetime.now(UTC)` stamp rule extended) — stated in the module docstring + asserted in the revoke→re-hire test arm.** Reporting/export reads land P3/P4. Tests `tests/placements/test_admin_lane.py`: fail-closed 403 on every route (no/missing/invalid token — the R-56 matrix); generic transition every legal arm + the 409 arms + **garbage `to` → 422 (G-327)**; revoke → placement revoked (→ excluded from counts, asserted P3); **revoke → re-hire → fresh active placement + the three-event ledger sequence pinned + decided_at = the re-hire event's stamp (G-326) + second active placement on the same application without revoke → the IntegrityError surfaced as an honest 409**.
|
||||
|
||||
### Wave 2-3: P2 security review + phase gate (security-auditor + lead-developer)
|
||||
|
||||
- **Task 2-3-01** (security-auditor): gate + PII review (P2 scope): G-311 gate order on every transition route (401 → 403-claim → 403-cross-entity → 409, pinned); the G-319 supersession (R-79): learner_id is an opaque G-5 handle, application-scoped only, anti-enumeration preserved (cross-entity 403 carries no data); employer sessions can never withdraw (D-099); operator provenance on every admin action incl. re-hire; the audit trail answers every decision (employer_audit_events + ledger actor refs). Findings recorded; P0s fixed in-phase.
|
||||
- **Task 2-3-02** (lead-developer): P2 phase gate — `pnpm ai:lint` + `pnpm ai:typecheck` + `pnpm ai:test:fast` + `pnpm web:test` + `pnpm cli:test` green (existing marketplace/employers suites green unmodified); the R-80 coherence review recorded (placements, not applications, are the correction lane — the route shape vs D-099/D-102); test counts recorded.
|
||||
|
||||
## Phase 3: Placement Reporting (REQ-11-003)
|
||||
|
||||
**Goal:** The guiding outcome is measurable: distinct-learner counts computed from rows at query time (per employer, per start-date cohort month, cumulative toward 1,000), the per-employer placement view live, wire types dual-schema-pinned, the employer surfaces converted (the applications page + the overview placements section replacing the mock block).
|
||||
|
||||
### Wave 3-1: Reporting reads (backend-engineer)
|
||||
|
||||
- **Task 3-1-01** (backend-engineer): reporting per D-107 — counts computed from rows at query time, NEVER denormalized counters (G-302/G-306): `GET /v1/placements/admin/overview` → `{total_active_placements, distinct_learners_placed, guiding_goal: 1000, by_employer: [{employer_id, count}], by_cohort_month: [{month, count}]}` — **the guiding-outcome metric is DISTINCT LEARNERS with ≥1 active placement, all-time cumulative toward 1,000 (a learner placed twice counts ONCE — the outcome's noun is learners, PROJECT.md line 7); revoked excluded from every count (D-102); cohort month = `strftime("%Y-%m")` over start_date (D-103/R-79 — employment-start month, not hired month, not application month)**; by_employer ordered count desc then employer_id, by_cohort_month month ascending (R-73); joins through existing stores (employer identity via employer_accounts/EmployerRow, posting via postings, learner via application rows); batched grouped reads (the count_applications_by_posting discipline store.py:915-932 — never per-row N+1). Plus `GET /v1/employers/placements` — the per-employer placement view (session-gated; own claimed-entity hired applications with role_title/start_date, honest empty state; 403 + claim-CTA unclaimed; 401 no token) — D-109 surface 2's data source. Tests `tests/placements/test_reporting.py`: distinct-learner rule (one learner, two employers, two placements → distinct_learners_placed=1, total_active_placements=2); cohort bucketing (two starts in one month → one bucket; a future-dated start lands in its own month); revoke exclusion (revoked → gone from every count; a learner whose only placement was revoked → back to 0); per-employer view own-rows-only + cross-entity 403 + unclaimed 403.
|
||||
|
||||
### Wave 3-2: Wire types + engine-client placements section (frontend-engineer + data-engineer)
|
||||
|
||||
- **Task 3-2-01** (frontend-engineer, data-engineer dual-schema-sync): `packages/types/placement.ts` (D-110 — the fourth types module, the employer.ts precedent): ApplicationStatus union (regex-pinned the D-093 status-union way), Placement, PlacementEvent, EmployerApplicationSummary, transition request/response shapes, HireTransitionRequest, PlacementOverview (+ PlacementExport added with the export shapes in P4) + `export * from './placement'` in index.ts. Dual-schema pins in `apps/web/tests/pins.test.ts` (the employer.ts block :267-374 template): **every field asserted both sides against `ai_service/placements/base.py`** — lead-developer reviews the pins (the G-108 discipline from day one).
|
||||
- **Task 3-2-02** (frontend-engineer): engine-client.ts **placements section** (D-110 — appended after employer billing :1114; ONE client module, no fork): listEmployerApplications, the employer transition functions (inReview/interview/offer/reject/hire with `{role_title, start_date}`), listEmployerPlacements, getPlacementOverview (learner status/withdraw + export functions land P5/P4 with their routes) — every fetch AbortController-equipped (A-406), 401 → SessionRequiredError REUSE (engine-client.ts:126-131), 403 claim → ClaimRequiredError reuse (:136), **NO new error classes** (403 cross-entity renders from EngineError.status). Tests: web fetch-stub tests (the billing-entitlement.test.ts template) — 401 → SessionRequiredError, token attached on every fetch, transition dispatch with the exact body.
|
||||
|
||||
### Wave 3-3: Employer web surfaces (frontend-engineer)
|
||||
|
||||
- **Task 3-3-01** (frontend-engineer): D-109 surface 1 — the NEW `/employer/applications` page (beside postings/login/register/billing/talent): the hiring pipeline — own applications with status badges (the seven D-099 states), per-target transition CTAs, the hire form `{role_title, start_date}` (a date input, future dates allowed — D-103), learner_id shown (own applicants, G-319 supersession); honest pending/empty/403-claim states (the A-406 board-client discipline); session-gated shell (SessionRequiredError → honest logged-out state, never a retry loop). Tests: web fetch-stub + source pins (the G-312 discipline — no render harness): loading/error/empty/claim states present in source, status badge per status, hire form dispatches the transition, withdraw NEVER offered to employers (D-099).
|
||||
- **Task 3-3-02** (frontend-engineer): D-109 surface 2 — the employer overview page's real placements section **REPLACES the mock-labeled placement metrics block** (employer-overview-client.tsx :335-372, the "(mock — no backend computes this)" label :351 — D-092: never leave a convertible surface on mock): hired applications with role_title/start-date via listEmployerPlacements, honest empty state; the talent-match/applicant-pipeline mock metrics STAY mock-labeled (no backend computes them). Tests: pins — the overview grep-clean of the placement mock block + the retained mock labels intact; fetch-stub placements render + empty state; `pnpm --filter web build` (static export) green.
|
||||
|
||||
### Wave 3-4: P3 phase gate (lead-developer)
|
||||
|
||||
- **Task 3-4-01** (lead-developer): P3 phase gate — `pnpm lint` + `pnpm typecheck` + `pnpm ai:lint` + `pnpm ai:typecheck` + `pnpm ai:test:fast` + `pnpm web:test` + `pnpm cli:test` + `pnpm --filter web build` (web-touching phase) green; the D-110 pin review verdict recorded (placement.ts ↔ placements/base.py field-for-field); counts-discipline check (no denormalized counters anywhere); test counts recorded.
|
||||
|
||||
## Phase 4: Audit Export (REQ-11-004)
|
||||
|
||||
**Goal:** The third-party-auditor deliverable exists: the self-contained JSON export + the human summary generated from the same document, methodology stating its own three pilot gaps, byte-deterministic re-exports, the admin web placements block + export links, the full-chain E2E proof.
|
||||
|
||||
### Wave 4-1: Export + summary routes + methodology + E2E (backend-engineer)
|
||||
|
||||
- **Task 4-1-01** (backend-engineer): `GET /v1/placements/admin/export` (D-108) — one self-contained JSON document via a single store-level builder function: `{schema_version, generated_at, summary: {distinct_learners_placed, total_active_placements, revoked_count, by_cohort_month}, cohort: [placement records with employer/posting/application refs + role_title + start_date], evidence_bundles: [per-placement {posting_record, application_record, transition_history[], decision_provenance} — **G-325 (binding): bundles cover EVERY placement (active AND revoked), each with the full event history incl. placement.revoked/placement.rehired — the correction history is precisely what an auditor most wants to inspect; `cohort` stays active-only; `revoked_count` equals the placement.revoked events (cross-checkable, rides G-321(c))** — each resolved from SOURCE ROWS at export time (G-302: the export EMBEDS resolved source content — snapshot-at-export, which is what self-contained means — while live rows stay the only write path; **NO backfill**: pre-v0.11 `submitted` applications carry only their `created_at` in the bundle — honest absence, never fabricated history, D-101/A-304)], methodology: {placement_definition, counting_rules, verification, scope}, ledger: {events: [{id, application_id, placement_id, event_type, actor_type, actor_ref, payload, created_at, prev_hash, hash}], head_hash}}`. Methodology per R-68 (written from in-tree facts) with **the three R-67 pilot gaps stated explicitly — (a) no minimum-employed-duration check (a placement = a recorded hire, not a 90-day sustained role), (b) no salary (D-098), (c) verification is employer-principal attestation + operator oversight, not third-party employment verification — an audit methodology that omits its own verification limits is A-304-class dishonesty**: `placement_definition` = a PlacementRow created by the hired transition, employer-attested role_title + start_date, active at export time, one active placement per application (the G-316 partial unique); `counting_rules` = distinct learners with ≥1 active placement, all-time cumulative toward 1,000, revoked excluded, cohort month = start_date calendar month (D-107); **`verification` per G-321 (binding): states (a) what the chain proves (in-place mutation/fork detection of an intact sequence), (b) what it does NOT (wholesale DB replacement undetectable by the walk alone — the auditor's defense is export-to-export continuity: a prior export's ledger.events must appear as an exact prefix of a later export's, with the prior head_hash equal to the hash at that prefix position), and (c) the event↔row cross-consistency check (every active placement has placement.created; every revoked has placement.revoked; revoked_count matches the placement.revoked events)**; `scope` = pilot-bounded, every placement in the DB unbounded by date, evidence class = employer-principal attestation; the cohort divergence documented deliberately (employment-start month, not graduation cohort — no graduation events exist in a marketplace, R-68); **CIRR kept as naming, not citation — the text stands on its own definitions (R-67)**. Determinism rules (R-73, binding): events ordered by id (chain order); `by_cohort_month` month ascending; cohort/evidence lists ordered placement `created_at` then id (the list_postings discipline, marketplace/store.py:940-948) — pydantic declaration-order serialization is deterministic but set-derived lists would not be, so every list is built with an explicit sort; **`generated_at` is export-only metadata (a function of the request, not the rows — R-79) and is excluded from determinism comparison**; **float absence — every export value is str/int/bool, no ratios or percentages (counts are integers by construction, D-107)**; `head_hash` = the last event's hash = `verify_chain()`'s computed head. pydantic + `JSONResponse` only — zero new deps (D-112). Tests land with Task 4-1-03.
|
||||
- **Task 4-1-02** (backend-engineer): `GET /v1/placements/admin/export/summary` (D-108) — `text/markdown` rendered **FROM the same JSON document (one builder, two renderings — the summary can never drift from the export, D-108's anti-drift rule)**: totals table (distinct learners placed, total active placements, revoked count, the guiding-goal progress line toward 1,000), per-cohort month table, the methodology prose (rendered from the export's methodology block — **G-321: incl. the chain's proof scope, its wholesale-rewrite limit, and the export-to-export prefix-continuity anchor**), **the head hash + chain-walk verification instructions** (recompute `hashlib.sha256` over the canonical JSON + prev_hash from GENESIS_HASH event-by-event — the walk is offline: the export embeds every event, so the auditor needs nothing else, R-70); **G-328 (binding): the summary's title carries the attestation language ("employer-attested, operator-overseen") — never a "CIRR-verified" claim**. Tests: summary totals equal the export's summary block on the same DB state (the same-builder pin); content-type pinned; 403 fail-closed without the admin token.
|
||||
- **Task 4-1-03** (backend-engineer): `tests/placements/test_export.py` — **re-export determinism: two exports on an unchanged DB → identical `ledger.events` chains + identical `head_hash`, with generated_at excluded (parsed field-by-field comparison or key-strip — R-73's TOTAL-exclusion rule)**; **chain-head consistency: `head_hash` = the last event's `hash` = `verify_chain()`'s output** (the walk re-computes every hash from GENESIS_HASH); **methodology completeness: the three R-67 gaps + all four methodology keys asserted present + the G-321 verification-scope statements (proof scope, wholesale-rewrite limit, export-to-export continuity, event↔row cross-check) asserted present**; **evidence-bundle completeness per G-325: every placement (active OR revoked) has a bundle with the resolved posting_record + application_record + transition_history (revoked bundles carry placement.revoked; re-hired carry placement.rehired)**; revoked placements absent from cohort but present in revoked_count (D-108); 403 fail-closed on both routes. Plus **the full-chain E2E proof `tests/placements/test_e2e_audit.py`** (the milestone's machine-checked reason-to-exist, D-111): employer register → claim → admin approve → create draft (direct package grant, the grant_posts precedent test_entitlement_enforcement.py:70-85) → publish → verified learner applies (seed_verified_identity, SUITE_LEARNERS) → employer drives in_review → interview → offer → hire `{role_title, start_date}` → PlacementRow created → ledger events chained (`verify_chain` green) → export → identical chain + head on re-export → overview counts the learner ONCE toward 1,000.
|
||||
|
||||
### Wave 4-2: Admin placements block + export links + security review + phase gate (frontend-engineer + security-auditor + lead-developer)
|
||||
|
||||
- **Task 4-2-01** (frontend-engineer): D-109 surface 4 — the moderation page (app/(admin)/admin/moderation/page.tsx:3/:35, the EmployerNetworkPanel area employer-network-panel.tsx:56) gains a placements block: aggregate counts (distinct learners placed, total active placements, guiding-goal progress) + per-employer placement lists via `GET /v1/placements/admin/overview`, transported over the existing `adminToken()` G-308 sessionStorage wrapper (engine-client.ts:815; the locked-state :28-40 pattern — **403 renders the honest locked state with the token prompt, never a retry loop**); export links — both fetched via the admin transport (token header attached, AbortController-equipped): **the summary opens in-tab** (the markdown rendered in the panel) and **the JSON export downloads** (blob download from the fetched document); honest empty state at zero placements. **G-328 (binding): counts are labeled as recorded placements ("distinct learners placed", "placements recorded") — "CIRR" NEVER appears as a verification claim on any live surface; "CIRR-style" describes the export format in release notes/methodology only (source pin: no "verified" placement wording on any new surface).** Tests: web fetch-stub — locked state on 403, counts + per-employer lists render, export links dispatch with the admin header, empty state; source pins for the locked-state branches + the G-328 wording pin.
|
||||
- **Task 4-2-02** (security-auditor): export-integrity review (P4 scope) — determinism rules honored (orderings pinned, generated_at total exclusion, no floats), **no PII beyond opaque handles** (learner_id is a G-5 roster handle, not name/email/DOB — identity PII is never stored, R-79; the export + 422 scrubber surface carry nothing else), methodology honesty (the three gaps stated; attestation never presented as third-party verification — A-304, the never-display-forgeable-as-verified constraint), head-hash truth (the export's head equals verify_chain's), evidence bundles resolved from source rows (G-302), both export gates fail-closed. Findings recorded; P0s fixed in-phase.
|
||||
- **Task 4-2-03** (lead-developer): P4 phase gate — `pnpm lint` + `pnpm typecheck` + `pnpm ai:lint` + `pnpm ai:typecheck` + `pnpm ai:test:fast` + `pnpm web:test` + `pnpm cli:test` + `pnpm --filter web build` green (web-touching phase); the determinism + methodology-honesty verdicts recorded; test counts recorded.
|
||||
|
||||
## Phase 5: Learner Placement Visibility (REQ-11-005)
|
||||
|
||||
**Goal:** The learner sees their outcome on the surface where they applied: current status + full timestamped history + placement confirmation when hired (one read, one truth source), withdraw within reach; the badge stays honest everywhere.
|
||||
|
||||
### Wave 5-1: Learner application-status read route (backend-engineer)
|
||||
|
||||
- **Task 5-1-01** (backend-engineer): `GET /v1/marketplace/applications/{application_id}?learner_id=` (D-104, in api/marketplace.py — the existing apply surface): gated by the **D-043 composition** (G-5 allowlist marketplace.py:46-52 → verified 18+ :358 — the P2 withdraw additionally rides the existing apply-rate window; no new throttle knob, D-088 untouched); returns `{application, events[], placement|null}` — current status + the full id-ordered timestamped ledger history for THIS application (scoped query, never another learner's events) + the placement record when hired (REQ-11-005's outcome visibility + placement confirmation in one read, D-104); composes the placements store via `app.state` DI (deps.py); the response is a named pydantic contract in placements/base.py (pinned in placement.ts per D-110). **G-322 (binding): the mine point-read — store `get_application_by_posting_learner(posting_id, learner_id)` (the insert_application unique key — the get_posting point-read shape, marketplace/store.py:578-584) + route `GET /v1/marketplace/applications/mine?posting_id=&learner_id=` on the unchanged D-043 gate stack, returning `{application_id, status}` or 404 — the panel NEVER depends on client-persisted application_ids; without this route the status panel cannot find the application on revisit (the common case for a job board).** Tests `tests/placements/test_learner_status.py`: own application → 200 with status + events[] (id-ordered, this application only); hired → placement payload with role_title/start_date/employer refs; foreign learner_id → 403; unverified → 403; unallowlisted → 403; unknown application → 404; **mine-read arms (G-322): own → 200 {application_id, status}; none → 404; foreign learner_id → 403; unverified → 403**; the G-313 conftest reset holds (no self-429).
|
||||
|
||||
### Wave 5-2: Job-detail status panel (frontend-engineer)
|
||||
|
||||
- **Task 5-2-01** (frontend-engineer): D-109 surface 3 — job-detail-client.tsx (the existing apply surface: apply :95-115, EngineError 409/404 discrimination :103-105, confirmation render :253) gains the application-status panel: **G-322 composition: mine-read (`GET /applications/mine?posting_id=&learner_id=`) first → found? render the status panel via D-104's read : not found? render the apply CTA — never client-persisted application_ids**; current status badge (the seven D-099 states), timestamped history rows (events[]), placement confirmation when hired (role title, employer, start date — D-104's read), and the withdraw CTA (the learner's ONLY edit, D-104 — 409 terminal copy honest, and G-323's apply → 409 application_terminal copy renders the honest terminal state); **EngineError.status discrimination through the existing checks — NO new error classes** (403 foreign → the honest "not your application" state; 404 unknown; 401/403 gate arms render their existing states); AbortController everywhere (A-406). Badge honesty (A-304/D-109): **a placement badge renders ONLY in this learner's-own application surface where the data is real; the talent profile pages carry NO badge (v0.1 mock imports — a badge on a mock page is fabricated placement, D-092 binding)**. Tests: web fetch-stub + source pins (the G-312 discipline) — each status state renders, history rows, placement-confirmation payload render, withdraw dispatch + terminal 409 copy, foreign-403 copy, **mine-read composition (mine 404 → apply CTA; mine 200 → status panel)**; pins — talent-profile pages grep-clean of placement-badge additions; pins.test.ts placement blocks green.
|
||||
|
||||
### Wave 5-3: P5 phase gate (lead-developer)
|
||||
|
||||
- **Task 5-3-01** (lead-developer): P5 phase gate — `pnpm lint` + `pnpm typecheck` + `pnpm ai:lint` + `pnpm ai:typecheck` + `pnpm ai:test:fast` + `pnpm web:test` + `pnpm cli:test` + `pnpm --filter web build` green (web-touching phase); the A-304 badge-honesty census recorded (no badge on mock talent pages, no fabricated placement anywhere, mock labels retained where no backend computes them); test counts recorded.
|
||||
|
||||
## Phase 6: Final Review + Ship (milestone release, v0.10.x line)
|
||||
|
||||
**Goal:** Multi-persona review of all v0.11 changes; audit (reconstruction + discipline); milestone ship: merge to main, tag v0.10.6 (final v0.10.x patch = milestone release), full asset matrix + registry image via the existing release lane (no infra changes — the module rides D-064/D-065), milestone completion commits, branch cleanup.
|
||||
|
||||
### Wave 6-1: Multi-persona final review (lead-developer + security-auditor)
|
||||
|
||||
- **Task 6-1-01** (lead-developer → all active personas): full milestone-branch diff review — the **D-100 one-transaction discipline holds end-to-end** (one transition_application, no second status writer, no second append path — R-78), the **R-80 re-hire coherence verdict** (placements, not applications, are the correction lane; the ledger reads hired → revoke → rehire as three events, never a fabricated second application transition), the **G-319 pin-split verdict** (counts-only stays on the own-postings list — test_postings_read.py:216 unchanged; learner_id application-scoped only), the **D-110 wire-pin review** (placement.ts ↔ placements/base.py field-for-field + the status-union regex), the D-092 honest-surface census (the overview mock block replaced, talent mocks retained + labeled, no fake-converted surface, no convertible surface left on mock). P0s fixed in-phase; P1+ findings dispositioned with recorded follow-ups — never loop back to EXECUTE.
|
||||
- **Task 6-1-02** (security-auditor): final review — no credentials or identity PII in logs/releases/assets (learner_id is an opaque handle everywhere, R-79); gate orders pinned on every principal class (employer/learner/operator); the ledger's no-delete path intact; tamper/fork/concurrency arms green; export determinism + methodology honesty re-verified; no secret echoed by any exception path.
|
||||
|
||||
### Wave 6-2: Audit + ship (lead-developer)
|
||||
|
||||
- **Task 6-2-01** (lead-developer → ship): audit (git log ↔ .ciagent/ reconstruction; file discipline — the D-112 addition census: ai_service/placements/, api/placements_admin.py + the employers.py/marketplace.py route sections + deps.py get_placement_store, the marketplace store's get_application point read + grouped reads, main.py wiring, tests/placements/, packages/types/placement.ts + index.ts export, engine-client placements section, /employer/applications page, overview placements section, job-detail panel, admin placements block; branch/commit discipline — feat: scoped to the placement surface) + ship: merge milestone → main; tag v0.10.6; Gitea release with full summary + the complete asset matrix + registry image (the existing tag-triggered lane — zero workflow changes); delete milestone branches (tags preserve history); mark REQ-11-001..005 complete in REQUIREMENTS.md; ROADMAP milestone entry; checkpoint cleared.
|
||||
|
||||
---
|
||||
|
||||
## Phase 2: AI Tagging (REQ-6-002)
|
||||
|
||||
**Goal:** Posting text → skills/seniority/category via D-020 structured output (mock-first, cloud-free); tags persisted; facets drive the sidebar.
|
||||
|
||||
### Wave 2-1: tagging + facets
|
||||
|
||||
- **Task 2-1-01** (ai-engineer): `marketplace/tagging.py` — `PostingTags` schema (skills `list[str]` ≤10, seniority enum, category enum) + versioned prompt constant; `tag_posting(text)` composes the EXISTING `structured_completion(provider, messages, model, schema, schema_hint)` (D-052: no new agent — one-shot extraction like grading's rubric call). Mock-first for free: mock provider default keeps tests cloud-free.
|
||||
- **Task 2-1-02** (data-engineer): persistence hooks — ingest pipeline tags every posting after upsert; re-tag on posting update **overwrites** the tags column (derived data, single source of truth — D-052; unlike enrichment, no append-only).
|
||||
- **Task 2-1-03** (backend-engineer): `PUT /v1/marketplace/admin/postings/{id}` (edit title/description/skills → triggers re-tag) + facets in API responses: `GET /v1/marketplace/postings` carries a `facets` payload (skills/seniority/category value counts) computed from stored tags of published postings.
|
||||
- **Task 2-1-04** (frontend-engineer): `JobFilters` facet lists derive from the API facets payload (static option lists die); counts render honestly.
|
||||
|
||||
### Wave 2-2: tests
|
||||
|
||||
- **Task 2-2-01** (ai-engineer): tests — tagging via `MockLLMProvider` (cloud-free pin); D-020 schema-violation → single bounded retry pinned; skills ≤10 enforced on an 11-skill mock response; facet derivation test (API facets exactly match stored tags of published-only postings); re-tag overwrite pin (old tags gone after update).
|
||||
|
||||
**Verification hooks P2:** all suites green (488+ / web 22+ / CLI 61 / typecheck / ruff / export build). Tagging tests stay mock-provider-only.
|
||||
|
||||
---
|
||||
|
||||
## Phase 3: Semantic Vector Search (REQ-6-003)
|
||||
|
||||
**Goal:** EmbeddingProvider protocol (mock-first, deterministic), SQLite-local vectors, hybrid facet+cosine ranking, computed match scores replacing the mock `matchScore`.
|
||||
|
||||
### Wave 3-1: provider + storage
|
||||
|
||||
- **Task 3-1-01** (ai-engineer): `marketplace/embedding/base.py` — `EmbeddingProvider` protocol `embed(texts: list[str]) -> list[EmbeddingVector]` (frozen pydantic: `values: list[float]`, `model`, `dim` — D-051, D-030 mirror); `embedding/mock.py` — deterministic 256-dim feature-hash of normalized tokens (pure stdlib; similarity deterministic).
|
||||
- **Task 3-1-02** (ai-engineer): `embedding/openai_compat.py` — `POST {AI_EMBED_BASE_URL}/embeddings` (`{"model", "input": [texts]}`) on the shared httpx pool (D-017); `_sanitize` key redaction mirroring `openai_audio.py`. **Probe-corrected (D-051): ollama-cloud does NOT expose /embeddings — `AI_EMBED_BASE_URL` must point at another OpenAI-compatible endpoint (e.g. local ollama `:11434/v1`); default stays mock.**
|
||||
- **Task 3-1-03** (backend-engineer): `config.py` `embed_provider`/`embed_base_url`/`embed_api_key` (SecretStr)/`embed_model` + `embedding/factory.py` wiring in main.py lifespan: `AI_EMBED_PROVIDER=mock|openai-embed`, **G-11 boot-safe — `openai-embed` selected but unconfigured → loud log naming the fix, fallback to mock, boot never crashes**; `app.state.embedding_provider` + `deps.get_embedding_provider`.
|
||||
- **Task 3-1-04** (data-engineer): store `put_vector`/`get_vector` — struct-packed little-endian float32 BLOB codec (`<{dim}f`), `model`+`dim` persisted per row (A-403/A-404: lazy re-embed on provider change works); roundtrip test (the data↔ai seam per territory table).
|
||||
|
||||
### Wave 3-2: pipeline + ranking
|
||||
|
||||
- **Task 3-2-01** (ai-engineer): embed-on-publish — the publish transition embeds posting text + tags and stores the vector; **lazy re-embed**: a row whose `model`/`dim` ≠ the provider's is re-embedded on next access; candidate-side competency-profile text is embedded **on demand, never stored**.
|
||||
- **Task 3-2-02** (ai-engineer): `marketplace/search.py` — pure-Python cosine (sum of products / norm product; ≤10⁴ postings, no numpy — A-403); **hybrid per A-405/D-059: facet hard-filters (SQL on portable columns) first, then cosine ranking over the filtered set; no facets → pure semantic ranking**; `match_score` = cosine(candidate, posting); skill-breakdown = posting-tag overlap with the query + per-skill vector contribution (deterministic feature-hash dot-product shares — testable).
|
||||
- **Task 3-2-03** (backend-engineer): `GET /v1/marketplace/search` (`q` + facet params → ranked results with `match_score` + `skill_breakdown`); DI-composed, no store import in routes.
|
||||
|
||||
### Wave 3-3: web + tests
|
||||
|
||||
- **Task 3-3-01** (frontend-engineer): `engine-client.searchPostings(q, filters)`; board search bar wired to the search API; **match scores appear only in search context (G-106): cards without an active query show no score (honest absence, never a fabricated number); per-learner profile-driven card scores are explicitly post-v0.6 — REQ-6-003's "scores on job cards" satisfied conditionally in search context, recorded**; skill-breakdown panel on detail consumes the computed payload.
|
||||
- **Task 3-3-02** (ai-engineer + security-auditor): tests — deterministic similarity pins (same text → identical vector; related texts > unrelated texts cosine); codec roundtrip; factory fallback + boot-safe; `_sanitize` key-redaction pin (no key in any error); cosine math corner cases (zero vector); hybrid ordering (facet filters before ranking; pure-rank with no facets); embed-on-publish + lazy re-embed on model change.
|
||||
|
||||
**Verification hooks P3:** all suites green; embedding tests never leave the process (mock provider + MockTransport for openai_compat byte-contract tests).
|
||||
|
||||
---
|
||||
|
||||
## Phase 4: Enrichment + Resume Parsing (REQ-6-004, REQ-6-005)
|
||||
|
||||
**Goal:** Two independent workstreams, parallelizable (D-059). (A) employer enrichment with append-only provenance; (B) bounded resume upload → draft extraction → learner confirm gate.
|
||||
|
||||
### Workstream A: enrichment (REQ-6-004)
|
||||
|
||||
- **Task 4-A-01** (ai-engineer): `marketplace/enrichment.py` — `EmployerEnrichment` schema (description, social_links, logo_ref) + prompt; one-shot `enrich_employer()` via structured_completion (D-053, same D-020 layering as tagging; mock-first).
|
||||
- **Task 4-A-02** (data-engineer): store — `employer_enrichment` rows are **append-only** `(employer_id, field, value, source: llm|manual, model, created_at)`; `merge_employer(employer_id)` read precedence **manual > llm > ingested-raw** (A-409); manual override = new `manual` row, NEVER a mutation of `llm` rows.
|
||||
- **Task 4-A-03** (backend-engineer): **enrich-on-first-publish** — a publish whose employer has no prior published posting fires the one-shot extraction (re-publishing the same employer does not re-run); employer GET returns merged fields with per-field `{value, source}` provenance markers (A-304 honesty — LLM copy visibly marked); `POST /v1/marketplace/admin/enrichment` (manual-override upsert, D-057-guarded).
|
||||
- **Task 4-A-04** (frontend-engineer): employer profile shell consumes merged+marked fields; provenance badges visible per field.
|
||||
- **Task 4-A-05** (security-auditor + ai-engineer): tests — precedence pin (manual beats llm beats raw, each combination); append-only pin (no UPDATE/DELETE path exists on enrichment rows); marker honesty (mock-llm copy carries the llm marker end-to-end); trigger-once pin.
|
||||
|
||||
### Workstream B: resume parsing (REQ-6-005)
|
||||
|
||||
- **Task 4-B-01** (backend-engineer): pypdf pin — `pypdf>=6.19,<7` in `apps/ai-service/pyproject.toml` + idempotent install via the existing bootstrap venv channel (probe-verified 6.19.0, A-009; the ONLY new dep).
|
||||
- **Task 4-B-02** (ai-engineer): `marketplace/resume.py` — `ParsedProfile` schema mapped to the competency-profile shape (competencies, skills, experience bands) + prompt; parse via D-020 structured extraction; result carries `status: "draft"`.
|
||||
- **Task 4-B-03** (backend-engineer): `POST /v1/marketplace/resume` (multipart; **PDF/TXT/MD only, ≤2 MB, text-layer required** — empty pypdf extract → honest 422 "text layer required", NO OCR in v0.6; extracted text capped ~100K chars before the LLM call; raw bytes never stored, never logged — A-305, `_scrub_pii_validation` precedent) and `POST /v1/marketplace/resume/confirm` (learner-gated: G-5 → verified → caps; **persists the confirmed profile JSON to a 6th store table `learner_profile` (learner_id PK, profile JSON, confirmed_at, model — G-104; NOT a filesystem sidecar — the D-027 store family is the only persistence mechanism)**; the draft NEVER persists without confirm).
|
||||
- **Task 4-B-04** (frontend-engineer): learner dashboard profile section — upload → draft fields review → confirm; bounds errors render honestly (413 oversize / 422 format+text-layer); nothing saves before the confirm click.
|
||||
- **Task 4-B-05** (security-auditor + ai-engineer): tests — small **generated** PDF + TXT fixtures parse (cloud-free); bounds matrix (format rejection, >2 MB, empty-extract 422, char cap); draft-then-confirm flow; PII sentinel caplog test (resume bytes/sentinel strings in NO log record, NO stored raw form).
|
||||
|
||||
**Verification hooks P4:** all suites green; resume + enrichment tests stay mock-provider; resume fixtures generated in tmp (no binaries committed beyond minimal fixtures).
|
||||
|
||||
---
|
||||
|
||||
## Phase 5: SEO Programmatic Pages (REQ-6-006)
|
||||
|
||||
**Goal:** Metadata + JSON-LD + sitemap/robots on the static-export fabric, D-039 unchanged.
|
||||
|
||||
### Wave 5-1: web metadata
|
||||
|
||||
- **Task 5-1-01** (frontend-engineer): build-time metadata — `export const metadata` (title/description/OG) on the **static set: landing, catalog/stack detail, marketplace board, pricing** (the existing layout.tsx/enroll pattern; static-export-compatible, probe 7).
|
||||
- **Task 5-1-02** (frontend-engineer): server-rendered JSON-LD on the board — `ItemList` + `Organization` — rendered into the export.
|
||||
- **Task 5-1-03** (frontend-engineer): client-side JSON-LD on the **runtime set** — `JobPosting` on job detail, `Organization` on employer profile, injected after fetch (A-411 accepted limitation: JS-less crawlers see the shell — recorded).
|
||||
|
||||
### Wave 5-2: sitemap/robots + tests
|
||||
|
||||
- **Task 5-2-01** (backend-engineer + security-auditor): `GET /sitemap.xml` + `GET /robots.txt` as plain FastAPI routes on the api app — **probe 6 verified: API routes beat the `StaticFiles("/")` mount**, so they win over the export in single-port production; enumerate the static page list (code constant) + all `published` postings; URLs from the `AI_PUBLIC_BASE_URL` origin; robots points at `/sitemap.xml`. **Unset `AI_PUBLIC_BASE_URL` (G-105): loud G-11 boot warning; sitemap serves the empty static-page set (never malformed/relative URLs) and robots omits the Sitemap directive (absolute-URL spec requirement); fail honest at request time; boot never crashes.** **Do NOT use Next `app/sitemap.ts`** (build-time enumeration cannot see runtime postings under `output: 'export'`).
|
||||
- **Task 5-2-02** (frontend-engineer + backend-engineer): tests — sitemap contents reflect published postings (draft/closed excluded); robots points at the sitemap with the configured origin; metadata/OG present in the exported HTML (`out/` probe); mount-order test (routes beat the static mount); client JSON-LD injection web test.
|
||||
|
||||
**Verification hooks P5:** all suites green + export build emits with metadata; sitemap tests pin `db_path=tmp_path` + `public_base_url` explicitly (hermetic, no `~/.nextcraft`).
|
||||
|
||||
---
|
||||
|
||||
## Phase 6: Final Review + Ship (milestone release v0.5.6)
|
||||
|
||||
- **Task 6-1-01** (lead-developer → ci-review personas): multi-persona review of the full milestone branch diff (all phases — correctness, testing, security, performance, maintainability); **known follow-ups checked for scope creep: seed dormancy verified (mock-data untouched except marketplace path), employer dashboard stays mock (A-407), pricing stays mock (A-412) — zero payments/employer-auth/scheduler code**. P0s fixed in-phase.
|
||||
- **Task 6-1-02** (ci-audit): reconstruction test (git log ↔ .ciagent/ files), file/branch/commit discipline, tag hygiene; critical fixes in-phase.
|
||||
- **Task 6-1-03** (lead-developer → ci-ship): merge milestone → main; tag **v0.5.6** (milestone release); Gitea release with full summary + `nextcraft-linux-x64` + `.sha256` assets (D-036); delete milestone branches; mark REQ-6-001..006 complete; clear checkpoint.
|
||||
|
||||
---
|
||||
|
||||
## Must-Haves (per phase — concrete, falsifiable, test-linked)
|
||||
|
||||
### Phase 1
|
||||
|
||||
- **MH-1a**: Store contract tests (tmp_path db): five tables created on the shared `db_path`; `(source, external_id)` and `(posting_id, learner_id)` unique constraints fire on duplicates; WAL/pragmas/`_validate` hooks pinned.
|
||||
- **MH-1b**: Ingest idempotency — running the seeded source twice yields identical row counts (no dupes); upsert overwrites in place.
|
||||
- **MH-1c**: Admin fail-closed matrix — unset `AI_ADMIN_TOKEN` → every admin route 403 + boot warning in caplog; wrong/absent token → 403; correct token → 200. No admin route passes unguarded.
|
||||
- **MH-1d**: Apply gate composition **provable by test** — G-5 403 fires first, verify-CTA 403 second, 429 at cap; published-only (404 missing / 409 draft+closed); duplicate → 200-with-existing; confirmation payload exact; **G-18 stub markers gone** (grep + response-schema pin).
|
||||
- **MH-1e**: Web shells read real data — board/detail/employer consume `/v1/marketplace/*` (web tests pin the engine-client functions); `notFound()` on 404; honest empty board; **E87 regression class pinned (G-101/G-110): placeholder shells emitted for both routes (build does not throw), catch-all serves arbitrary ids, hydration + `notFound()` works at a non-placeholder id via full page load**; the honest-501 stub pin in tests/identity/test_identity.py:444 rewritten onto the marketplace router.
|
||||
- **MH-1f**: Seed fidelity — 20 postings + 10 employers, IDs match the TS fixtures, `matchScore` absent from all marketplace-path payloads; **seed postings enter `published` with original `postedAt` (G-102)**.
|
||||
|
||||
### Phase 2
|
||||
|
||||
- **MH-2a**: Tagging cloud-free via `MockLLMProvider`; `PostingTags` schema enforced (skills ≤10 pin on an 11-skill response); D-020 single bounded retry pinned on schema violation.
|
||||
- **MH-2b**: Tag-on-ingest + re-tag-on-update **overwrites** (old tags absent after update — single source of truth).
|
||||
- **MH-2c**: Facets derive from real stored tags — API facets payload matches published-only tags exactly; `JobFilters` option lists come from the payload (web test).
|
||||
|
||||
### Phase 3
|
||||
|
||||
- **MH-3a**: Codec roundtrip — struct-packed float32 BLOB via `put_vector`/`get_vector` with `model`+`dim` per row.
|
||||
- **MH-3b**: Deterministic similarity — same text → identical vector; related > unrelated cosine (pinned numbers).
|
||||
- **MH-3c**: Factory G-11 boot-safe — `openai-embed` unconfigured → boot survives with loud log + mock fallback; `_sanitize` redaction: no key string in any error (pinned).
|
||||
- **MH-3d**: Hybrid ordering — facets hard-filter before cosine ranking; no facets → pure semantic rank; `match_score` = computed cosine, **mock `matchScore` absent from marketplace-path API payloads and marketplace surfaces (G-107: the pin's grep excludes `packages/mock-data` and the employer/admin route groups, which stay mock)**; absent score = honest absence (no active query → no score, G-106).
|
||||
- **MH-3e**: Embed-on-publish + lazy re-embed on model change (pinned); candidate-side embeddings never stored.
|
||||
- **MH-3f**: Skill-breakdown = tag overlap + vector contribution, deterministic pin.
|
||||
|
||||
### Phase 4
|
||||
|
||||
- **MH-4a**: Enrichment append-only (no update/delete path) + precedence manual > llm > raw, every pairing pinned.
|
||||
- **MH-4b**: Provenance markers — every enriched field carries `{value, source}` in the API; mock-llm copy visibly marked end-to-end.
|
||||
- **MH-4c**: Enrich-on-first-publish fires exactly once per employer (re-publish no-op pin).
|
||||
- **MH-4d**: Resume bounds matrix — PDF/TXT/MD only (other → 422), >2 MB → 413, empty PDF extract → 422 "text layer required", ~100K char cap.
|
||||
- **MH-4e**: Draft-then-confirm — parse returns `status: "draft"`, nothing persisted; confirm persists; **PII sentinel caplog test green** (raw bytes never logged/stored).
|
||||
- **MH-4f**: pypdf pinned `>=6.19,<7` in pyproject + bootstrap installs it; generated PDF fixture parses.
|
||||
|
||||
### Phase 5
|
||||
|
||||
- **MH-5a**: Sitemap reflects published postings (draft/closed excluded) + static page list; origin from `AI_PUBLIC_BASE_URL`; **every sitemap job/employer URL must serve 200 on the single-port app via the G-101 catch-all shells (URL-resolvability pinned — G-109, never advertise URLs the deploy 404s)**; unset origin → empty set + warning, robots omits the Sitemap directive (G-105).
|
||||
- **MH-5b**: robots.txt points at `/sitemap.xml`.
|
||||
- **MH-5c**: Metadata + OG present in the exported HTML (`out/` probe); board ItemList+Organization JSON-LD server-rendered.
|
||||
- **MH-5d**: Runtime JSON-LD injected client-side after fetch (web test); JS-crawler limitation recorded.
|
||||
- **MH-5e**: Mount-order — sitemap/robots routes beat the static export in single-port mode (route test).
|
||||
|
||||
## Milestone Must-Haves
|
||||
|
||||
- **MH-M1**: All six requirements complete with their REQUIREMENTS.md success criteria: REQ-6-001 (store+lifecycle+routes+adapter, surfaces read real data, D-043 gates composed), REQ-6-002 (tags via D-020, facets drive filters), REQ-6-003 (protocol+SQLite vectors, similarity ranking, computed match scores), REQ-6-004 (enrichment with provenance), REQ-6-005 (resume auto-fill with review gate, bounded), REQ-6-006 (metadata+JSON-LD+sitemap/robots, D-039 unchanged).
|
||||
- **MH-M2**: Zero regressions on existing suites at every phase ship: 488 backend pytest, web tsx --test 22, CLI 61, typecheck 8, ruff, export build.
|
||||
- **MH-M3**: G-18 stub markers gone (MH-1d) — the one honest-501 marketplace route is now real.
|
||||
- **MH-M4**: The D-043 gate order provable by test (MH-1d) — allowlist → verified-18+ → caps, unchanged.
|
||||
- **MH-M5**: Hermeticity — every new test pins `db_path` (and any state dir) to `tmp_path`; no test touches `~/.nextcraft` or the cloud (v0.5 P04 lesson).
|
||||
- **MH-M6**: Scope discipline — pricing stays mock (A-412), employer dashboard stays mock (A-407), no payments/employer-auth/scheduler/crawler code; seed corpus is the only ingestion source.
|
||||
- REQ-11-001..005 all complete per their REQUIREMENTS.md rows.
|
||||
- The E2E machine-checked proof (the milestone's reason to exist, tests/placements/test_e2e_audit.py): employer registers → claims → operator approves → posts → learner (verified 18+) applies → employer drives in_review → interview → offer → hire `{role_title, start_date}` → PlacementRow created → the global chain walks green GENESIS_HASH → head → the export reproduces identical chains + head_hash on re-export → the overview counts the learner ONCE toward 1,000 — every step pinned in tests/placements/.
|
||||
- Zero new dependencies (D-112 — the chain is stdlib hashlib/json; export is pydantic + JSONResponse), zero workspace changes, zero mypy overrides, zero .env.example changes (no new knobs — recorded explicitly).
|
||||
- The v0.6/v0.9/v0.10 wire contracts unchanged: marketplace/billing/employers suites green unmodified (the only marketplace seam changes are the get_application point read + grouped reads); the own-postings counts-only pin green unchanged (G-319); UpgradeRequiredError and every existing engine-client contract byte-stable.
|
||||
- Wire pins green: placement.ts dual-schema pinned field-for-field against placements/base.py (D-110), status-union regex pinned.
|
||||
- Suite counts: pytest fast lane + web + cli all green, zero warnings (the v0.7 regime holds).
|
||||
- Docs: REQUIREMENTS/ROADMAP updated; deploy/README.md unaffected (no admin-box changes — recorded explicitly); the mock-first doctrine intact (no external systems, no third-party auditor integration — the export IS the deliverable; tests never call a cloud).
|
||||
|
||||
## Risks
|
||||
|
||||
- **Dual-schema drift (TS wire types ↔ pydantic contracts)** — mitigated by the dual-schema-sync constraint (data-engineer owns both sides of every change) + parity checks in review.
|
||||
- **Match-score removal breaking non-marketplace mockups** — jobs.ts/employers.ts stay intact for employer/admin mockups; only the marketplace path switches (A-406); pinned by build + web tests.
|
||||
- **`AI_EMBED_BASE_URL` misconfiguration** (ollama-cloud has no /embeddings — D-051 probe) — default mock; G-11 boot-safe fallback with loud log; endpoint is config, never code.
|
||||
- **Admin token operational risk** — unset token locks the founder out of admin routes (fail-closed is the intent); loud boot warning names the fix; documented in README quickstart.
|
||||
- **Brute-force cosine at scale** — pilot-only (≤10⁴ postings, A-403); documented; `VectorStore` protocol keeps the pgvector swap API-compatible.
|
||||
- **pypdf text-layer variance across real resumes** — honest 422 on empty extract (no OCR); TXT/MD path always works; generated-fixture tests pin both.
|
||||
- **Client-shipped runtime fetch + JS-crawlers see shells on runtime pages** — accepted limitation (A-411), recorded; static set carries the SEO weight.
|
||||
- **E87 static-export build break (grill-verified, G-101)** — Next 15 `output:'export'` hard-throws for dynamic routes lacking `generateStaticParams` (even `[]`); mitigation: one placeholder param per route + FastAPI catch-all shell serving (routes beat the mount, probe 6); pinned by release-blocking tests (G-110).
|
||||
1. **Re-hire-after-revoke coherence gap (R-80)** — `hired → hired` is a 409 on every matrix-validated surface, so the re-hire is pinned as the placement-level operator route `POST /v1/placements/admin/placements/by-application/{application_id}/re-hire` + the `placement.rehired` ledger event, never an application transition — Task 2-2-02; the three-event sequence + the partial-unique IntegrityError arm tested.
|
||||
2. **Hash-after-flush write shape (R-70)** — flush-then-hash-then-commit inside one transaction, ALL appends through the one transition_application, the no-delete-path pin — Task 1-1-03 (+ the 1-1-02 source pin); tamper/fork/concurrency tests green.
|
||||
3. **created_at canonical serialization (R-79/R-69)** — ONE pinned normalization (`_as_utc(dt).isoformat()`) in `_canonical_event_json`; the tamper tests catch hashing/reading drift before the chain breaks on its first re-read — Task 1-1-02.
|
||||
4. **_APPLY_TIMES limiter reset (R-77)** — tests/placements/conftest.py replicates the autouse reset from day one (the G-313 lesson applied before it ships, not after flaky archaeology) — Task 1-2-01.
|
||||
5. **Methodology honesty block (R-67/R-68)** — the three pilot gaps (no duration check, no salary, attestation-not-third-party-verification) stated explicitly in the export methodology — Task 4-1-01; asserted present by Task 4-1-03.
|
||||
6. **Export determinism rules (R-73)** — pinned list orderings (events by id; cohort month ascending; placements created_at then id), total generated_at exclusion, float absence — Task 4-1-01; the re-export test is the proof.
|
||||
7. **Status-column ownership (R-78)** — the placements store is the ONLY post-creation writer of application.status; stated column-level in the module docstring + enforced by the D-100 discipline check at the P1 gate (Task 1-3-02).
|
||||
8. **G-319 supersession pin split (R-77)** — counts-only stays on the own-postings list (test_postings_read.py:216 unchanged); learner_id appears on application-scoped routes only, cross-entity 403 carries no data — Task 2-1-02 pins both arms.
|
||||
9. **Concurrent-transition arm (R-78)** — one-winner-one-IntegrityError on truly concurrent transition_application calls (the billing concurrent-consumption shape, tests/billing/test_store.py:335) — Task 1-1-03.
|
||||
10. **CIRR specifics from knowledge, not live sources (R-67)** — the methodology text stands on its own definitions; CIRR is naming, not citation; the summary renders the prose an auditor reads without external references — Tasks 4-1-01/4-1-02.
|
||||
|
||||
## User-Facing Surface
|
||||
|
||||
1. **Marketplace job board** (`/marketplace`): reads real published postings from `/v1/marketplace/postings`; facet sidebar derives from real AI tags; match scores are computed, not mocked.
|
||||
2. **Job detail** (`/marketplace/jobs/[jobId]`): real posting fetch; full description, tags, employer info, computed skill-breakdown; honest 404 on missing postings; apply flow live with verify-CTA on 403 and 409 on closed.
|
||||
3. **Employer profile** (`/marketplace/employers/[employerId]`): merged raw+enriched fields with visible per-field provenance markers.
|
||||
4. **Learner profile auto-fill**: resume upload → draft review → confirm (nothing saved silently).
|
||||
5. **Founder/admin surface via curl + engineering docs**: `AI_ADMIN_TOKEN`-guarded posting authoring, lifecycle, ingest trigger, enrichment override, applications review — documented in a README marketplace quickstart addition (curl examples included).
|
||||
6. **SEO**: sitemap/robots served by the API; metadata + JSON-LD on the page set.
|
||||
1. **/employer/applications (NEW)** — the hiring pipeline: own applications with status badges, per-target transition CTAs, the hire form `{role_title, start_date}` (a date input, future dates allowed); honest pending/empty/claim states.
|
||||
2. **Employer dashboard — overview placements section** — real hired placements with role/start-date (the mock block REPLACED); talent-match/applicant-pipeline metrics stay mock-labeled.
|
||||
3. **Job detail — application-status panel** — the learner's current status + timestamped history + placement confirmation when hired + withdraw CTA; honest 403/404/409 states.
|
||||
4. **Admin moderation page — placements block** — aggregate counts toward the 1,000 guiding goal + per-employer lists + export links (summary in-tab, JSON download); 403 → honest locked state with token prompt.
|
||||
5. **Talent search + candidate profile** — remain the v0.1 mock, honestly labeled, with NO placement badge (A-304 — no badge on mock pages).
|
||||
6. **API surfaces** — `/v1/employers/applications/*` (session-gated transitions + own pipeline list), `/v1/marketplace/applications/{id}` + `/withdraw` (learner-gated, D-043 stack), `/v1/placements/admin/*` (operator-gated: transition, revoke, re-hire, overview, export, export/summary).
|
||||
7. **Release notes** — the v0.10.x line ships placement tracking through the existing automated lane (no admin-box changes required).
|
||||
|
||||
## Happy Path (end-to-end, written BEFORE execute)
|
||||
|
||||
1. Founder sets `AI_ADMIN_TOKEN=ops-secret` in `.env`; boots the stack; log shows the marketplace store on the shared DB (no unset-token warning).
|
||||
2. Founder runs `POST /v1/marketplace/admin/ingest` (X-Admin-Token header) → seeded corpus populates: 20 postings + 10 employers, upsert-idempotent.
|
||||
3. Founder authors a posting via `POST /v1/marketplace/admin/postings` (draft) → `POST .../publish` → posting is published (auto-tagged, embedded).
|
||||
4. Learner opens `/marketplace` → board client shell fetches real postings → filters by a facet derived from real tags → opens `/marketplace/jobs/{id}` detail.
|
||||
5. An 18+ verified, allowlisted learner clicks Apply → passes G-5 → verified-18+ → rate caps → posting published → `application` row (status `submitted`) → honest confirmation; a second click returns the same application (idempotent).
|
||||
6. Founder reviews via `GET /v1/marketplace/admin/applications` (token-guarded) and contacts the employer out-of-band (no notification infra, A-408).
|
||||
7. `GET /sitemap.xml` lists the static pages + every published posting.
|
||||
1. **Employer onboards (v0.10 rails unchanged):** register → claim their entity → operator approves → the account owns the entity.
|
||||
2. **Employer posts:** create draft (package granted) → publish → the posting is live on the job board.
|
||||
3. **Learner applies:** a verified 18+ learner applies from the job-detail page → application `submitted` → the status panel shows the timestamped entry.
|
||||
4. **Employer drives the pipeline:** /employer/applications → in_review → interview → offer → the learner's panel reflects each step with its event history.
|
||||
5. **Hire:** the employer submits `{role_title: "AI Orchestration Engineer", start_date: next month}` → hired (terminal) → the PlacementRow is created in the same transaction as the ledger events → the learner's panel shows the placement confirmation (role, employer, start date).
|
||||
6. **Operator oversight:** the admin overview counts the learner ONCE toward 1,000; a mistaken hire → operator revoke → re-hire creates a fresh placement with a three-event ledger trail — the learner is never erased from the count by a correction.
|
||||
7. **Auditor exports:** the admin placements block → the JSON export downloads (self-contained: cohort + evidence bundles + methodology + chain with head hash) + the summary opens in-tab → re-export reproduces the identical chain + head → the chain-walk instructions let a third party recompute every hash offline.
|
||||
|
||||
## UX Acceptance Criteria
|
||||
|
||||
1. Board shows real postings with an honest empty state (no fake cards when the store is empty).
|
||||
2. Missing posting id → honest 404 page (no fabricated job).
|
||||
3. Unverified learner clicking Apply → verify-CTA prompt linking to enrollment (never a dead JSON error or a fake "applied").
|
||||
4. Match scores are computed cosine values only; no mock `matchScore` anywhere; absent score = absent query context (honest).
|
||||
5. Tag facets derive from real stored tags (API payload → sidebar), never hardcoded lists.
|
||||
6. Per-field provenance markers visible on the employer profile (raw/llm/manual).
|
||||
7. Sitemap lists published postings; robots points at the sitemap; metadata present in the exported HTML.
|
||||
8. Resume auto-fill never persists without an explicit confirm; oversize/wrong-format/text-less PDFs get honest, actionable errors.
|
||||
9. All existing accessibility baselines hold (WCAG AA on new states).
|
||||
1. **Honest states everywhere:** every new surface renders real loading/error/empty states — no spinners that lie, no silent failures, no fake data.
|
||||
2. **Gate order never surfaces a 409 before a 403:** unauthenticated → 401, unclaimed → 403 claim prompt, foreign application → 403 with no data, only then matrix 409s — pinned on every transition route (G-311).
|
||||
3. **401 → honest logged-out state:** SessionRequiredError renders the login CTA on employer surfaces — never a retry loop, never a silent redirect; admin surfaces render the token-prompt locked state on 403.
|
||||
4. **Counts honesty:** the overview counts DISTINCT learners toward 1,000 (a learner placed twice counts once); revoked placements excluded from every count; counts render from the store's rows at query time — never a denormalized or cached counter.
|
||||
5. **Export self-verification:** the summary carries the head hash + offline chain-walk instructions; the methodology states its own three pilot gaps AND the chain's proof scope + wholesale-rewrite limit + export-to-export continuity anchor (G-321) — employer attestation is never presented as third-party verification (A-304); **G-328: no "verified" placement wording on any live surface (source-pinned)**.
|
||||
6. **Badge honesty:** a placement badge renders only on the learner's own application surface where the data is real; no badge until a placement exists; none ever on the mock talent pages.
|
||||
7. **Mock labels retained where no backend exists:** talent-match/applicant-pipeline metrics stay mock-labeled; talent pages stay the v0.1 mock — never fake-convert, never leave a convertible surface on mock (D-092).
|
||||
+160
-2
@@ -16,7 +16,163 @@ Nextcraft is an AI-native outcome school where graduates prove what they can bui
|
||||
|
||||
---
|
||||
|
||||
## Milestone v0.6 — Marketplace Engine (ACTIVE)
|
||||
## Milestone v0.11 — CIRR-Style Placement Tracking and Audit (ACTIVE, Feature, started 2026-10-01)
|
||||
|
||||
**Scope (D-098, auto-decided at SPECIFY under full autonomy D-007; founder scope confirmed 2026-10-01):** Activates **REQ-F-020 — CIRR-style placement tracking and audit** as REQ-11-001..005. The guiding outcome ("≥1,000 learners placed in AI-orchestration roles within 36 months, **verified by CIRR-style third-party audit**") is the school's single north star — v0.11 builds the machinery that makes it measurable and auditable. Every prerequisite is shipped: the learner identity spine (v0.5), the credential pipeline (v0.3), the marketplace applications flow (v0.6, `ApplicationRow`), the employer principals (v0.10, claimed entities + audit trail). v0.11 adds: the placement record model (learner + employer + role + start date, evidenced, immutable event log), the employer-side application state machine extending the v0.6 `submitted`-only status (hiring-stages transitions with audit), placement reporting surfaces (per-employer, per-learner, aggregate), and the **audit-grade export** — the evidence-backed dataset a third-party auditor can verify (cohort snapshots, per-placement evidence chains, tamper-evident event ledger, methodology documentation). Rationale: D-085's closing sentence names CIRR tracking as what the employer network "unlocks"; the guiding outcome is unmeasurable without it; no other deferred requirement (REQ-F-019 is medium and adds a surface, not the outcome). Confidence 0.80 ≥ threshold 0.60 (D-007).
|
||||
|
||||
**Out of scope:** human tutor marketplace (REQ-F-019, deferred), external third-party auditor integration (the export is the deliverable — no CIRR org exists to integrate with), learner-side employment verification (self-report stays out; employer-side state changes are the evidence), compensation/salary tracking (role + start date + employer suffice for placement counting; salary is out per CIRR-adjacent minimalism), public placement-stats marketing pages (internal + export only).
|
||||
|
||||
**Success (milestone-level):** every application in the marketplace has an auditable state history (submitted → in_review → interview → offer → hired/rejected/withdrawn, transitions employer-principal-driven and audit-logged); a placement record exists for every hired application with evidence (posting ref, application ref, timestamps, decision provenance); aggregate placement counts are computable from the ledger (per employer, per cohort month, cumulative toward ≥1,000); the audit export produces a self-contained, evidence-linked dataset (JSON + human-readable summary) whose placement claims are each traceable to immutable events; the mock-first doctrine holds (no external systems; tests never call a cloud). a placement record exists for every hired application with evidence (posting ref, application ref, timestamps, decision provenance); aggregate placement counts are computable from the ledger (per employer, per cohort month, cumulative toward ≥1,000); the audit export produces a self-contained, evidence-linked dataset (JSON + human-readable summary) whose placement claims are each traceable to immutable events; the mock-first doctrine holds (no external systems; tests never call a cloud).
|
||||
|
||||
## Clarify decisions (D-099+, CLARIFY stage full autonomy, 2026-10-01)
|
||||
|
||||
| ID | Decision | Rationale | Confidence |
|
||||
|----|----------|-----------|------------|
|
||||
| D-099 | Application status vocabulary = **snake_case set `submitted → in_review → interview → offer → hired / rejected / withdrawn`, forward-only with skip-forward, terminals have no outgoing edges**: the validated matrix (billing's `_VALID_TRANSITIONS` shape, billing/store.py:84-90) allows from any non-terminal status (a) any LATER stage (a fast-track `submitted → hired` is a legal hire — CIRR counts the hire, not the ceremony) and (b) any terminal (`rejected`/`withdrawn`); NO backward moves (no `offer → in_review`; the posting lifecycle draft→published→closed is strictly forward, store.py:289/609-632 — hiring inherits the discipline); `hired`/`rejected`/`withdrawn` are terminal — re-transition → 409 (`InvalidTransition`, the set_posting_status route contract); `withdrawn` is triggerable by the learner (own application, D-104) OR the operator (remediation, actor recorded — never by an employer session, who may `reject` instead); value naming is snake_case `in_review` (REQ-11-002's own text; billing's `past_due` precedent). Existing v0.6 rows are all `submitted` (store.py:211) — a valid matrix start, zero data migration. | The tree's two transition machines (posting store.py:609-632, subscription billing/store.py:84-90) both pin exact matrices with terminal empty-tuples; G-305's lesson (no phantom states, no un-matrixed moves) applies verbatim; skipping stages is honest pipeline reality (REQ-11-002 names the stages but no rule forbids acceleration, and an operator correcting a mis-entered pipeline must be able to jump forward). | 0.85 |
|
||||
| D-100 | The state machine lives in **`ai_service/placements/` — the placements store owns ONE `transition_application(application_id, to_status, actor_type, actor_ref, role_title=None, start_date=None)` method that updates the marketplace `application` row + appends the ledger event + creates the `PlacementRow` on hired, ALL IN ONE TRANSACTION** (the decide_claim all-or-nothing precedent, employers/store.py:636-651: "the audit row rides the SAME transaction"); the transition matrix constant lives in `placements/base.py` (billing/base.py `CANONICAL_EVENT_NAMES` placement); the marketplace store KEEPS application insert/read ownership (insert_application unchanged; gains only a `get_application(application_id)` point read, the get_posting shape at store.py:578-584) — the placements store's cross-family write to the `application` table is the sanctioned deliberate exception: both stores share the one SQLite file, so one Session on the placements engine covers both tables atomically. The rejected alternative — route composes `marketplace.set_application_status` + `placements.append_event` as two commits — leaves a crash window where the status changed but no ledger row exists, which voids REQ-11-002's "every transition appends the placement ledger" (the exact tamper-evidence the milestone sells). | REQ-11-002's ledger-append requirement is only provable under one transaction; decide_claim is the in-tree proof that decision + audit event must land together; cross-module reuse is family-sanctioned (employers/base.py:22 subclasses marketplace.base.Posting — D-093); D-027 table ownership bends here because the feature boundary (application lifecycle) crosses the v0.6 table boundary, and the bend is one column-write executed by one named store method, never a route-side two-step. | 0.80 |
|
||||
| D-101 | Hash-chain construction = **ONE GLOBAL chain over `PlacementEventRow` ordered by autoincrement id: each row stores `prev_hash` (the prior event's hash; `GENESIS_HASH = "0" * 64` module constant, test-pinned) + its own `hash` = `hashlib.sha256` (hex digest) over canonical JSON `{id, application_id, placement_id, event_type, actor_type, actor_ref, payload, created_at}` + `prev_hash`, serialized `json.dumps(..., sort_keys=True, separators=(",", ":"))`, created_at as ISO-8601 UTC** (deterministic; stdlib-only — the D-086 zero-dep doctrine, the D-077 HMAC-SHA256 crypto precedent); **`UNIQUE(prev_hash)`** makes a chain fork structurally impossible (two events claiming the same predecessor surface IntegrityError — the G-316 structural-backstop class); event rows carry BOTH a nullable indexed `application_id` (application-stage transitions log before any placement exists) and nullable `placement_id` (set from hired onward); **NO backfill**: pre-v0.11 applications have no `submitted` event — the export's evidence bundle carries the application record's own `created_at` (honest absence, never fabricated history, A-304; the G-302 doctrine cuts both ways). Actor vocabulary: `employer \| learner \| operator \| system` (the billing `_BILLING_EVENT_KINDS` shape, billing/store.py:92). | REQ-11-004 names "the event-ledger chain with head hash" — singular: one global chain with one head is the simplest verifiable shape (a single linear walk re-computes every hash; per-placement chains would need N heads and per-chain genesis bookkeeping for nothing at pilot scale); canonical sorted-key JSON is the standard deterministic-serialization answer and makes the re-export integrity test exact; SQLite's single-writer serialization plus the UNIQUE backstop closes the two-appenders-same-prev race the G-316 lesson demands. | 0.80 |
|
||||
| D-102 | PlacementRow semantics = **immutable at creation; `status` is the ONLY mutable column with exactly one transition `active → revoked` (operator-only correction, the D-083 manual-remediation lane)**: `role_title`/`start_date`/`decided_at`/`learner_id`/`employer_id`/`posting_id`/`application_id` are set once at the hired transition and NEVER rewritten (a silent field rewrite is exactly the tamper the ledger exists to detect; the D-053 append-only enrichment doctrine); `decided_at` = the hired transition's created_at (store-stamped, `datetime.now(UTC)`, the insert_application precedent); the one-placement-per-application guard is a **partial UNIQUE index on `application_id` WHERE status='active'** (the G-316 `uq_pending_claim_per_entity` shape, employers/store.py:161-167) — a revoked placement stays in history, and a re-hire after a mistaken revoke creates a fresh placement for the same application, so an operator fat-finger never permanently erases a learner from the ≥1,000 count; `employer_id`/`learner_id`/`posting_id` are ID REFERENCES resolved from source rows at read/export (G-302 — never trusted denormalized copies). | REQ-11-001's plain "UniqueConstraint (application_id)" would make a mistaken hire uncorrectable forever (terminal application + unique placement = no re-hire path), which is operationally dishonest for an audit-grade dataset that must survive human error; the partial-index precedent exists in-tree for exactly this conditional-uniqueness shape; revoked placements are excluded from counts (D-107) so the correction is counting-honest too. | 0.75 |
|
||||
| D-103 | `start_date` = **the employment start DATE (first day of work), a pydantic `date` — not the offer date, not a datetime**: the offer moment is already audit-truth as the hired transition's `decided_at` (D-102), so `start_date` answers "when did/will employment begin" (the CIRR question); timezone-free by construction (a calendar date has no tz — the cohort month D-107 keys on it); **future dates allowed** (hired today, starts next month — the normal case) and past dates allowed (retroactive recording of a hire that began last week); REQUIRED in the hire request body alongside `role_title` (employer-supplied at transition time, REQ-11-002's "hired creates the PlacementRow + role_title + start_date payload"); `role_title` is free text (defaults to nothing — never silently the posting title; the employer names the actual role). | A datetime would fabricate precision no employer supplies (nobody's start is "2026-11-03T14:22:51Z"); date-only matches every CIRR-adjacent reporting convention (monthly cohort tables); making both fields explicit-request-body requirements keeps the placement record employer-attested (the A-304 doctrine: the record carries what the principal actually asserted, never an inferred copy). | 0.85 |
|
||||
| D-104 | Learner routes live in **`api/marketplace.py` (the existing apply surface) with the D-043 composition unchanged — G-5 allowlist → verified 18+ → `_check_apply_rate`**: `POST /v1/marketplace/applications/{application_id}/withdraw` (body `{learner_id}` — 403 when the application is not the caller's, 409 when terminal, 422-free) and `GET /v1/marketplace/applications/{application_id}?learner_id=` returning `{application, events[], placement|null}` (current status + full timestamped ledger history + the placement record when hired — REQ-11-005's outcome visibility + placement confirmation in one read); the withdraw rides the EXISTING apply-rate window (marketplace.py:66-76 — 5/rolling-60s per learner, no new throttle knob, D-088's auth-only throttle scope untouched); the routes compose the placements store via `app.state` DI (the territory rule, deps.py) for the history/placement sections and call the SAME `transition_application` store method (D-100) with `actor_type="learner"`. Learner-initiated edits go NO further: only `withdrawn` (REQ-11-005's "no learner-initiated edits… the withdrawn transition is the exception"). | D-097's binding left the learner gates untouched and pinned them to learner surfaces — the marketplace module IS the learner application surface (apply at marketplace.py:345-382 with this exact gate stack); the G-5 allowlist stays the pilot guard on every learner-gated route (A-306); riding the existing limiter avoids a new knob and its G-313 conftest-reset trap is already solved in tests/marketplace (conftest.py:123-131, mirrored into tests/placements per D-111). | 0.85 |
|
||||
| D-105 | Employer transition routes = **per-target action routes under `/v1/employers/applications`** — `GET /v1/employers/applications?status=` (own pipeline), `POST .../{application_id}/in-review`, `.../interview`, `.../offer`, `.../reject`, `.../hire` (hire body `{role_title, start_date}`) — mirroring the posting lifecycle idiom (`/postings/{id}/publish`, `/postings/{id}/close`, employers.py:632-715); gate order (G-311): session 401 (`require_employer_session`, employers.py:173-191) → claim 403 (`_require_claimed`, employers.py:467-484) → cross-entity 403 (fetch application → posting → `posting.employer_id != claimed` → 403, the `_own_posting_or_404` shape at employers.py:487-503 applied through the application's posting) → transition 409 (never a 409 before a 403); every route rides the same `transition_application` method with `actor_type="employer", actor_ref="account:{id}"` (the D-091 checkout-metadata provenance shape) and appends an `employer_audit_events` row (the audit trail stays one queryable lane, D-089). **G-319 scoping (binding):** the v0.10 counts-only PII boundary was scoped to the own-postings LIST surface; v0.11 supersedes it for application-scoped reads/transitions — `learner_id` becomes visible ONLY for applications on the session's own claimed-entity postings (cross-entity → 403, no enumeration); the own-postings list's `applicant_count` stays counts-only. | A hiring pipeline without applicant identity is unworkable (REQ-11-002/003 inherently require it; A-408's "founder contacts employers out-of-band" was the no-employer-principal era's workaround, ended by v0.10); per-target routes keep the matrix OUT of request bodies (each route's store call names its target — one less validation surface, the publish/close precedent); G-319's intent was anti-enumeration/anti-cross-entity, and the 403-on-foreign-application arm preserves exactly that. | 0.80 |
|
||||
| D-106 | Admin oversight = **`api/placements_admin.py`, prefix `/v1/placements/admin`, `require_admin` IMPORTED from marketplace_admin (the billing_admin.py:27 import precedent, employers_admin.py:47) — one generic remediation route `POST /v1/placements/admin/applications/{application_id}/transition` `{to, role_title?, start_date?}`** (validated against the same D-099 matrix; role_title/start_date required iff `to=hired`; `actor_type="operator"` with `OPERATOR = "operator"` route-level provenance, employers_admin.py:54 — no per-operator accounts exist, D-094), **plus `POST .../placements/{placement_id}/revoke`** (D-102's operator-only correction, one transition) and the reporting/export reads (D-107/D-108): `GET .../overview`, `GET .../export`, `GET .../export/summary`; no employer-session gate, no learner gate (a third principal class — D-097); token namespaces cannot collide (D-090); the operator can drive ANY matrix-legal transition including `withdrawn` on a learner's behalf (remediation with provenance — the D-083 manual-grant lane). | REQ-11-002 names "admin routes retain operator oversight (admin transition + audit, the D-094 lane)" — one generic route (vs the employer surface's per-target idiom) is the operator-tooling shape: fewer routes to audit, and the matrix validation lives once in the store (D-100); the export prefix matches REQ-11-004's own `/v1/placements/admin/export`; fail-closed on unset token is inherited free from require_admin (G-11 boot warning already covers it, main.py:251-256). | 0.85 |
|
||||
| D-107 | Reporting semantics = **counts computed from rows at query time (never denormalized counters — G-302), with the guiding-outcome metric = DISTINCT LEARNERS with ≥1 `active` placement, all-time cumulative toward 1,000**: a learner placed twice counts ONCE ("≥1,000 learners placed" — the PROJECT.md guiding outcome is learners, not placements); `revoked` placements are excluded from every count (D-102's correction semantics); **cohort month = the calendar month of `start_date` (`YYYY-MM`)** — not application month, not hired month (CIRR cohorts on employment start); `GET /v1/placements/admin/overview` returns `{total_active_placements, distinct_learners_placed, guiding_goal: 1000, by_employer: [{employer_id, count}], by_cohort_month: [{month, count}]}`; per-employer view = the claimed entity's `hired` applications with role/start-date (REQ-11-003's employer-dashboard placements section); joins run through the existing stores (employer identity via `employer_accounts.employer_id`/EmployerRow, posting via postings, learner via application rows — REQ-11-003's own "counts join through existing stores"); batched reads use the `count_applications_by_posting` grouped-read discipline (store.py:915-932) — never per-row N+1. | The guiding outcome's noun is "learners" (PROJECT.md line 7) — counting placements would inflate the north star; date-only cohort keys make month buckets deterministic (D-103); counting from rows keeps revoke honest without counter-maintenance writes (the G-306 lazy-evaluation lesson: derived state computed at read, never a timer or a stored tally). | 0.85 |
|
||||
| D-108 | Export format = **`GET /v1/placements/admin/export` returns one self-contained JSON document**: `{schema_version, generated_at, summary: {distinct_learners_placed, total_active_placements, revoked_count, by_cohort_month}, cohort: [placement records with employer/posting/application refs + role_title + start_date], evidence_bundles: [per-placement {posting_record, application_record, transition_history[], decision_provenance} — each resolved from SOURCE ROWS at export time (G-302)], methodology: {placement_definition, counting_rules, verification, scope}, ledger: {events: [{id, application_id, placement_id, event_type, actor_type, actor_ref, payload, created_at, prev_hash, hash}], head_hash}}`; **`GET /v1/placements/admin/export/summary`** returns the human-readable rendering (text/markdown: totals table, per-cohort table, methodology prose, head hash, chain-walk verification instructions); scope is honest pilot-bounded (every placement in the DB, unbounded by date — REQ-11-004's own scoping); **re-export determinism: the integrity test asserts identical `ledger.events` chains + identical `head_hash` across two exports, with `generated_at` excluded from comparison** (the chain is a function of stored rows; generated_at is the export's own timestamp, not ledger content); the summary is generated from the same JSON (one truth source — the summary can never drift from the export). | REQ-11-004 names all four dataset components ((a) cohort snapshot, (b) evidence bundles, (c) methodology, (d) chain+head) — this is exactly that shape with names an auditor can consume; "resolved from source rows, never denormalized copies" means snapshot-at-export (the export EMBEDS resolved source content — that's what self-contained means) while the live rows stay the only write path; methodology-as-structured-JSON keeps it versioned and machine-checkable while the summary route renders the prose an auditor reads. | 0.80 |
|
||||
| D-109 | Web conversion scope = **four surfaces, no new client module**: (1) new `/employer/applications` page (the hiring pipeline: own applications with status badges + per-target transition CTAs — honest pending/empty/403-claim states, the A-406 board-client discipline); (2) the employer overview page gains a real placements section (hired applications with role/start-date, honest empty state) — its existing applicant-pipeline/talent-match mock metrics stay mock-labeled (D-092: never fake-convert, never leave a convertible surface on mock); (3) the job-detail client (the existing apply surface, job-detail-client.tsx) gains an application-status panel: current status + timestamped history + placement confirmation when hired, via D-104's learner read (401/403/409 discrimination through existing `EngineError.status` checks — job-detail-client.tsx:103-105 precedent, NO new error classes); (4) the admin moderation page's EmployerNetworkPanel area gains a placements block (aggregate counts + per-employer lists via D-107 overview, adminToken() transport per G-308) + an export link (summary opens in-tab; JSON export downloads). **The talent profile's placement badge stays absent** — talent profile pages remain v0.1 mock (D-092 binding), and a badge on a mock page is A-304 dishonesty; a REAL badge renders only on the learner's own application surface (D-104's placement section) where the data is real. | REQ-11-003 names the employer dashboard + moderation-page surfaces; REQ-11-005 names the learner application surface (the job detail page IS that surface today — apply + confirmation live there, job-detail-client.tsx:50/253); D-092's conversion doctrine (real where a real backend exists, mock where none does) maps cleanly: placements have a backend, talent profiles do not. | 0.80 |
|
||||
| D-110 | Wire discipline = **`packages/types/placement.ts` (ApplicationStatus union, Placement, PlacementEvent, EmployerApplicationSummary, transition request/response shapes, PlacementOverview, PlacementExport) dual-schema pinned field-for-field against `ai_service/placements/base.py` pydantic contracts in `apps/web/tests/pins.test.ts`** (the D-093 template — the employer.ts pin block); engine-client.ts gains a **placements section** (no new client module — D-092's binding: one client module keeps parseError discrimination in one place): employer list/transition/hire functions, learner application-status/withdraw, admin overview/export — every fetch AbortController-equipped (A-406), 401 → SessionRequiredError reuse (engine-client.ts:126-131), no new error classes. | Every prior cross-boundary wire (PostingSummary D-084, employer.ts D-093) rides exactly this rail from day one; the placement surface is a new cross-boundary contract and the pins make drift structurally detectable (G-108 discipline); the 403 cross-entity arm needs no client-side class — components render the honest "not your application" state from EngineError.status. | 0.85 |
|
||||
| D-111 | Testing doctrine = **`tests/placements/` mirroring D-096: real flows against create_app + TestClient, tmp_path DBs, zero network by construction, no MockTransport (no external calls exist), mypy green with no new overrides (stdlib only — D-086)**: state-machine 409 matrix arms (every illegal move incl. backward + terminal-source), gate order pins (employer transition: no-token → 401, unclaimed → 403, foreign application → 403 — never a 409 first; learner withdraw: unallowlisted → 403, unverified → 403, foreign application → 403, terminal → 409), hired E2E (transition → PlacementRow created → ledger events chained → employer dashboard placement visible), revoke + re-hire (partial-unique arm: second active placement on the same application → IntegrityError surfaced), **hash-chain tamper tests** (direct row mutation via a second engine → verification walk fails; fork attempt → UNIQUE(prev_hash) surfaces), **export determinism** (two exports → identical chains + head, generated_at excluded), learner visibility (history + placement confirmation), reporting counts (distinct-learner rule: one learner, two placements → counts once). `tests/placements/conftest.py` carries the G-313-shape autouse reset for the marketplace apply-rate limiter module state (the withdraw route rides it — tests/marketplace/conftest.py:123-131 pattern) — the suite cannot self-429. | The billing/employers suites are the proven template (behavior over the real app, real scrypt, honest assertions); the tamper and determinism tests are THIS milestone's reason to exist — an audit ledger nobody has tried to break is theater; the limiter reset is the G-13 lesson applied before it ships (v0.10 caught it only after flaky archaeology). | 0.85 |
|
||||
| D-112 | Migration/compat = **9th D-027 store, tables `placement` + `placement_event` on the shared DB file, `SQLModel.metadata.create_all` idempotent — zero migration** (the D-095 shape verbatim): `SQLitePlacementStore` mirrors employers/store.py mechanics exactly (WAL/synchronous=NORMAL/busy_timeout/foreign_keys pragmas at connect, `sa_type` portable columns, `_validate`/`_normalize` hooks, Protocol + SQLite impl pair, surfaced IntegrityError, tz-aware↔naive normalization, `_constraint_error` helper); bare `placement` is FREE (D-095's prefix rule was collision-driven — marketplace owns `posting`/`employer`/`application`, no `placement` table exists); the marketplace `application` table gains NO new columns (status is already a plain str column, store.py:211 — the D-099 vocabulary extends the validated set, existing `submitted` rows stay valid); lifespan wiring = the getattr-guard template (main.py:195-200) + `close()` in the finally block (main.py:336); routers mount in main.py beside the employers block (main.py:400-411). No new dependencies (hash chain is stdlib `hashlib`/`json`; export is pydantic + `JSONResponse`). | Seven prior stores never broke an existing DB via this exact pattern (D-095's 0.90 confidence carries forward); create_all checkfirst adds the two tables to every existing deployment at next boot; the zero-dep claim stays intact (D-086/R-66) — sha256 + canonical JSON need nothing the venv lacks. | 0.90 |
|
||||
|
||||
## Milestone v0.10 — B2B Employer Network (COMPLETE, Feature, 2026-09-30, shipped as v0.9.6)
|
||||
|
||||
**Scope (D-085, auto-decided at SPECIFY under full autonomy D-007; founder scope confirmed 2026-09-30):** Real employer auth/accounts and employer self-serve — the milestone every prior decision sequences next: A-407 ("Real employer auth lands post-payments with the B2B employer network" — payments shipped v0.9), A-401 (employer self-serve posting management deferred pending employer auth), D-076/D-079 (operator-mediated checkout + contact-path CTAs were honest *because* no employer principals exist). Employers become principals: registered accounts with sessions, claiming their existing employer entity (the v0.6 `EmployerRow` ingested data), self-serve posting management (draft → published → closed on their own entities), self-serve checkout (the v0.9 billing catalog with employer-principal buyers instead of operator mediation), and the employer dashboard surface converting from the v0.1 mockup to real data. Rationale: the guiding outcome (≥1,000 placements) needs a self-serve employer side; the supply side (v0.6), monetization rails (v0.9), and install-anywhere distribution (v0.8) are all in place — the employer network is the missing B2B surface that unlocks CIRR tracking (REQ-F-020 needs employer-side placement data) and closes the last mock-only surface. Confidence 0.80 ≥ threshold 0.60 (D-007).
|
||||
|
||||
**Out of scope:** CIRR placement tracking (REQ-F-020, deferred), human tutor marketplace (REQ-F-019, deferred), multi-tenant SSO/OIDC enterprise login (email+password at pilot), employer team/multi-seat management, posting analytics beyond the existing enriched views.
|
||||
|
||||
**Success (milestone-level):** an employer can register an account, claim/verify their employer entity, log in, manage their own postings through the full lifecycle, purchase posting packages/talent-access plans through self-serve checkout with entitlement enforcement applying to their own posts, and see real data in the employer dashboard; admin routes retain operator oversight (impersonation-free, audit-logged); all auth is session-based with hashed credentials, rate-limited, and fail-closed on unconfigured secrets; the mock-first doctrine holds (no external auth provider, tests never call a cloud).
|
||||
|
||||
## Clarify decisions (D-086+, CLARIFY stage full autonomy, 2026-09-30)
|
||||
|
||||
| ID | Decision | Rationale | Confidence |
|
||||
|----|----------|-----------|------------|
|
||||
| D-086 | Password KDF = **stdlib `hashlib.scrypt`, zero new dependencies**: per-password 16-byte random salt (`secrets.token_bytes`), OWASP-floor params N=2^14/r=8/p=1, dklen=32, stored self-describing as `scrypt$16384$8$1$<salt_b64>$<hash_b64>` so params can evolve without invalidating stored rows; verification compares derived bytes via `hmac.compare_digest`; params are module constants pinned by test (the D-083 PAST_DUE_GRACE_DAYS shape). | passlib is unmaintained and ships no type stubs — adding it would force the FIRST `ignore_missing_imports` mypy override, breaking the v0.7 pyproject regime ("currently NONE" — pyproject.toml:143-151); bcrypt adds a compiled dep to the deb/docker/arm64 matrix (D-069) for nothing; scrypt IS a library-grade memory-hard KDF (OpenSSL-backed, probe-verified in the shipped venv) and the tree's crypto precedent is stdlib-only end-to-end (HMAC-SHA256 webhooks D-077, ingest tokens v0.4.7, `secrets` minting). pypdf was "the ONLY new v0.6 dependency" — the zero-dep discipline holds. | 0.80 |
|
||||
| D-087 | Employer sessions = **server-side rows in the new `employer_sessions` table (8th D-027 family), opaque token minted per login, stored hashed**: token = `secrets.token_urlsafe(32)` (CSPRNG — per-boot entropy inherent, the factory.py mint precedent); the row stores only `sha256(token)` and lookups re-hash the presented token, so a DB-file leak never yields usable credentials (the G-108 secrets doctrine extended to storage). TTL = fixed 7 days from login (module constant, test-pinned) evaluated LAZILY at read (G-306 — no timer); logout DELETEs the row + audit event (revoke = lookup miss → 401); multiple concurrent sessions per account (per-device rows) are allowed. The agents/ `InMemorySessionStore` is NOT reused — it is LRU-evicted chat context (D-019), a different concern; principal state is a durable D-027 row like everything else persisted. | REQ-10-001 already fixes "server-side store" (signed tokens/JWTs are off-spec); opaque random tokens need no signing key (server-side lookup is the truth source) and no per-boot secret to manage; hashed-at-rest is the standard session-store discipline at zero cost. | 0.85 |
|
||||
| D-088 | Auth throttling = **in-memory sliding windows in api/ (process-local, the G-5 precedent)**: (a) per-EMAIL failed-login window — default 5 failures / rolling 15 min → 429 (settings knob, the `identity_submits_per_min` shape); (b) a global per-min cap on login+register attempts (the `_check_global_create_rate` deque, api/sandboxes.py:123) → 429, bounding cross-email credential-stuffing volume; successful login clears the email's failure window; 429s carry the honest "wait" detail. Keyed by the SUBMITTED EMAIL, not client IP — behind HAProxy every request's `request.client.host` is the proxy (the tree has zero IP-trust machinery; D-039 single-port). | The identity `_SubmitRateLimiter` (api/identity.py:97-116) and sandbox create-cap are the proven in-tree throttle patterns — same module-state acceptability (D-019: one process, one box); IP-based keys would be fake security on this topology; brute-force economics at pilot are bounded by the two windows without any new infra. | 0.80 |
|
||||
| D-089 | Claim/verify = **claim → pending → admin decision; evidence recorded, never auto-activating at pilot**: `POST /v1/employers/claims {employer_id}` (authenticated) creates an `employer_claims` row status=pending with computed evidence `{account_email_domain, entity_website_domain, match}` (normalized registrable-domain comparison — stored as provenance); `employer_accounts.employer_id` is UNIQUE and set on approval (the REQ's "one account : one entity" UniqueConstraint); one PENDING claim per entity + one APPROVED owner per entity enforced check-first in the store (the `insert_application` precedent); rejection frees the entity for a new claim. Admin approve/reject routes (require_admin) set decided_by/decided_at + append `employer_audit_events` (the billing_events provenance shape). Auto-approval on domain match is DEFERRED: without email verification the match is forgeable, so the admin queue DISPLAYS the signal but the operator decision activates. | The seeded corpus websites are example.com placeholders — no real verification surface exists at pilot; REQ-10-002 explicitly retains "admin routes for claim review/approve/reject (operator oversight)"; an auto-approve on forgeable evidence would be a dishonest gate (the A-304 doctrine — never present unverified as verified). | 0.80 |
|
||||
| D-090 | Session transport = **`Authorization: Bearer <session-token>`** with a `require_employer_session` dependency (api/employers.py — the require_admin extract→verify→return shape): 401 on missing/expired/unknown token (the webhook-HMAC credential precedent), 403 stays the authorization failure (cross-entity access); the dep returns the session + account context (claimed employer_id included). NOT a cookie: D-039 static export has no Next middleware — the client attaches the header explicitly on every fetch (A-002); an explicit header is CSRF-immune by construction (no ambient credential, no SameSite machinery). CORS `allow_headers` gains `"Authorization"` (main.py:341 — the E87-class lesson: the v0.3 PUT preflight omission broke every cross-origin Save; tests/api/test_cors.py extended to pin it) for the two-port dev + D-038 network-mode topologies. Token namespaces cannot collide: admin routes compare against the env token, employer routes hash-lookup sessions — a token of one class fails the other's gate. Operator routes live in a separate `api/employers_admin.py` mounting `require_admin` imported from marketplace_admin (the billing_admin.py:27 import precedent). | Parallel to require_admin's dual-header acceptance but single-header for one principal class; same-origin production fetches skip CORS entirely; the dev topology needs the allow-list entry or every employer preflight dies — caught before it ships this time. | 0.85 |
|
||||
| D-091 | Entitlement reuse = **one shared api-layer helper, two principal gates composing it**: extract the 402 gate from marketplace_admin.create_posting (lines 181-220) into a shared api/ function `consume_posting_entitlement(store, employer_id, upgrade_cta)` raising the canonical 402 dict payload `{reason, posts_used, posts_limit, upgrade_cta}`; the admin route passes the admin-checkout CTA, the employer route the employer-checkout CTA — reason/posts_* identical, `UpgradeRequiredError` contract unchanged (D-080/D-084 wire stability). `consume_posting` itself (G-304 single conditional UPDATE) is untouched — no store change, no billing/→api/ boundary violation (the helper lives in api/ beside both callers, D-027/D-048 territory preserved). Employer checkout `POST /v1/employers/billing/checkout {item_id}` mirrors billing_admin.create_checkout with the buyer = the session's claimed entity (403 + claim-CTA when unclaimed; metadata operator_ref → account provenance) and an employer-scoped mock-complete arm mounted only under provider=mock, completing one's OWN session (D-082 transposed to the employer principal; success/cancel URLs from public_base_url per G-310). | REQ-10-004 demands the exact v0.9 check parameterized, not reimplemented — extraction is the only no-drift shape; the billing webhook/provider/store path is reused verbatim (REQ-10-005 "the v0.9 billing module reused"), only the principal derivation changes. | 0.85 |
|
||||
| D-092 | Web conversion = **employer section in engine-client.ts (no new client module) + sessionStorage `nc-employer-session`**: engine-client.ts is THE fetch module (identity/billing/marketplace sections already live there; pins.test.ts pins its content) — the employer section adds register/login/logout/me, claim, own-postings CRUD/publish/close, own-checkout, own-entitlement + a `SessionRequiredError` (401 → the G-308 honest logged-out state, never a retry loop; logout clears storage + calls the revoke route; every fetch aborts via AbortController — the A-406 board-client discipline). Storage = sessionStorage (the G-308 admin-token wrapper is the only in-tree credential-storage pattern; tab-scoped bounds XSS token exposure vs localStorage's persistent copy; no pilot requirement demands cross-tab persistence). Conversion scope: postings page (real own-postings lifecycle), overview page (real active-postings count + per-posting applicant counts from the applications table; talent-match/placement metrics stay mock-labeled — no backend computes them), employer profile (claimed entity via the existing public GET /v1/marketplace/employers/{id}), new /employer/login + /employer/register pages; **talent search + candidate profile pages stay the v0.1 mock** (no candidate backend exists in any milestone — v0.6 built postings/search over POSTINGS; a talent-access search backend is honestly out of scope, their mock imports remain). | One client module keeps parseError/error-class discipline in one place (a second module would fork the 402/401 discrimination); mock stays only where no real data source exists — the honest-surface rule cuts both ways (never fake-convert, never leave a convertible surface on mock). | 0.78 |
|
||||
| D-093 | Wire types = **`packages/types/employer.ts`** (EmployerAccount, EmployerClaim, EmployerPublicProfile reuse where shapes coincide — PostingSummary is reused from marketplace.ts, never duplicated, and the entitlement view reuses the v0.9 shapes) dual-schema pinned field-for-field against `ai_service/employers/base.py`'s pydantic contracts in `apps/web/tests/pins.test.ts` (the G-108 discipline; the billing.ts pin block, pins.test.ts:202-230, is the template — every field asserted both sides). | Every prior cross-boundary wire (PostingSummary, SearchResult, Package/Plan) is pinned this way (D-084); the employer surface is a new cross-boundary contract and gets the same rail from day one. | 0.85 |
|
||||
| D-094 | Admin network overview = **the admin marketplace moderation page gains the network sections** (app/(admin)/admin/moderation/page.tsx — where the v0.9 EmployerEntitlementPanel already landed, REQ-9-004's operator lane): employer accounts list (email, claimed entity, entitlement state columns), claim queue (evidence + domain-match signal, approve/reject actions), fed by new operator routes in api/employers_admin.py (require_admin + audit events): GET /v1/employers/admin/accounts, GET /v1/employers/admin/claims, POST .../claims/{id}/approve, POST .../claims/{id}/reject, GET .../audit — web transport via the existing `adminToken()` G-308 sessionStorage wrapper + honest 403 locked states. | REQ-10-005 names "the operator oversight lane"; the moderation page is the established admin marketplace surface (employer claims are the marketplace-moderation concern — REQ-025's verification queue was its v0.1 mock ancestor); one admin surface keeps the operator's one-glance workflow instead of fragmenting across pages. | 0.80 |
|
||||
| D-095 | Migration/compat = **8th D-027 store on the shared DB file, `SQLModel.metadata.create_all` idempotent — zero migration**: `SQLiteEmployerStore` mirrors billing/store.py mechanics exactly (WAL / synchronous=NORMAL / busy_timeout / foreign_keys pragmas at connect, sa_type portable columns, `_validate`/`_normalize` hooks, Protocol + SQLite impl pair, surfaced IntegrityError, tz-aware↔naive normalization); `create_all` checkfirst semantics add the 4 tables (`employer_accounts`, `employer_sessions`, `employer_claims`, `employer_audit_events`) to existing DBs at next boot — the billing store shipped the same way against the marketplace-era file (proven compat). Lifespan wiring: the state-injection override (main.py `if getattr(app.state, "employer_store", None) is None: construct from settings.db_path`) + `close()` in the finally block (the billing_store wiring, main.py:182-190/325). The `employer_` prefix is mandatory — the bare `employer` table name is taken by marketplace's EmployerRow (store.py:145). | The 7 prior stores never broke an existing DB via this exact pattern (D-027 family replication is the most-repeated store contract in the tree); REQ-10-001's table names already carry the prefix. | 0.90 |
|
||||
| D-096 | Testing doctrine = **real flows against create_app + TestClient, tmp_path DBs, real KDF, zero network by construction**: `tests/employers/` (the billing suite layout): register/login/logout/me, throttle 429 windows (both knobs), claim → admin approve → own-posting lifecycle → cross-entity 403s, entitlement 402 arms via direct store grants (the test_entitlement_enforcement.py:60 precedent), employer checkout + employer mock-complete E2E through the REAL webhook path (the D-082 proof shape). Password hashing runs the REAL scrypt in tests (N=2^14 ≈ tens of ms per hash — honest, never a fake-hash path; tests never assert hash bytes, only accept/reject behavior; salts random per hash — determinism is at the behavior level, the mock-provider verdict lesson). No MockTransport needed — auth has no external calls; the conftest zero-network guard stays satisfied; mypy green with no new overrides (stdlib only). | The suite's contract is behavior over the real app (billing/billing_admin/entitlement tests are the template); a reduced-KDF test profile would fork the code under test — the exact drift the honest-surface rule forbids. | 0.85 |
|
||||
| D-097 | Gates = **no learner gates on employer routes; email verification + self-serve password reset deferred (honest out-of-scope)**: employer routes compose ONLY the employer session gate — no `require_verified_age`, no G-5 learner allowlist (employers are a third principal class, not learners; D-043's composition on the learner routes — apply/resume/sandbox — is untouched and keeps allowlist → verified 18+ → rate caps). Registration stores email UNVERIFIED (displayed as such; that is why claim evidence is advisory per D-089); no email/notification infra exists (the A-408 out-of-band precedent) so email verification and self-serve password reset are deferred and documented honestly in the surface copy; admin retains remediation authority via the operator routes + `employer_audit_events` trail. | Employer accounts are B2B adults buying posts, not gated minors — the 18+/16+ gates exist to protect learners on learner surfaces (D-043); inventing an email-verification path without any mail transport would be security theater (A-304: never present unverified as verified). | 0.85 |
|
||||
|
||||
---
|
||||
|
||||
## Milestone v0.9 — Payment Engine (COMPLETE, Feature, 2026-09-29 → 2026-09-30, shipped as v0.8.6)
|
||||
|
||||
**Scope (D-074, auto-decided at SPECIFY under full autonomy D-007; founder scope question left open post-v0.8):** Activates **REQ-F-018 — payment processing and subscription management** as REQ-9-001..005. The pricing page (REQ-017, critical since v0.1) gains its real backend: posting packages (single, bundle, enterprise), talent-access plans for employers, and subscription tiers — with checkout, provider webhooks, entitlement enforcement on posting creation, and a subscription lifecycle (renew/cancel/upgrade/downgrade) under a provider-agnostic protocol (D-014 mock-first pattern). Rationale: the guiding outcome (≥1,000 placements via the Nextcraft marketplace) requires a monetized, self-serve employer side; the marketplace engine (v0.6) built the supply side, ship-anywhere (v0.8) made the stack installable anywhere — payments is the only high-priority requirement deferred since v0.3 that directly unblocks employer self-serve (A-407: "real employer auth lands post-payments with the B2B employer network") and CIRR-style placement tracking needs paid postings to track. Confidence 0.80 ≥ threshold 0.60 (D-007).
|
||||
|
||||
**Out of scope (landed in v0.10):** real employer auth/accounts (B2B employer network), multi-currency, tax/VAT handling beyond passthrough, invoice PDF generation, Stripe-specific UI components, CIRR tracking (REQ-F-020, deferred).
|
||||
|
||||
**Success (milestone-level):** an employer (via admin-mediated flow at pilot) can purchase a posting package or talent-access subscription through a real Stripe-compatible checkout; webhooks update entitlements automatically; posting creation enforces package limits honestly; subscription lifecycle transitions (renew/cancel/upgrade) work end-to-end; the pricing page reflects real catalog data; all provider integrations are mock-first (tests never call Stripe). — ACHIEVED, all 5 REQ complete, shipped as v0.8.6 (release with full asset matrix + registry image per D-064).
|
||||
|
||||
## Clarify decisions (D-075+, CLARIFY stage full autonomy, 2026-09-29)
|
||||
|
||||
| ID | Decision | Rationale | Confidence |
|
||||
|----|----------|-----------|------------|
|
||||
| D-075 | Both providers ship in-milestone: `mock` (deterministic, default) and `stripe` (real Stripe-compatible REST via the shared httpx pool — checkout session create/retrieve, subscription cancel/upgrade, event signature verify). Tests exercise the stripe provider ONLY through `httpx.MockTransport` (the openai-audio/embedding precedent — byte-contract pinned, cloud never called); `AI_PAYMENT_PROVIDER=stripe` is env-gated and needs `AI_PAYMENT_API_KEY` — unset key falls back to mock with a loud G-11 boot log (voice/embedding factory pattern, `billing/factory.py` + main.py lifespan catch). | The D-030 openai-audio precedent: a real provider shipped alongside mock with MockTransport byte-contract tests. A protocol without a real implementation is unproven; a real implementation without mock is untestable. Pilot runs mock; the real path is config-away. | 0.80 |
|
||||
| D-076 | Buyer model at pilot = **operator-mediated** (extends A-401): checkout sessions are created via admin-token-gated routes (`/v1/billing/admin/checkout`) on behalf of an employer ref in the request body; no employer principals exist (A-407). Every purchase records `operator_ref` (admin token identity = "operator") + `employer_id`. Webhook route is public (server-to-server) but HMAC-verified (D-077). | Employers are data, not principals (A-407); the admin token dep (`require_admin` returning Settings) is the only operator identity mechanism in the codebase. Self-serve checkout requires employer auth — explicitly post-payments scope. | 0.85 |
|
||||
| D-077 | Webhook signature = **HMAC-SHA256 over `"{timestamp}.{raw_body}"`** (Stripe's own scheme shape), verified with `hmac.compare_digest`; secret from `AI_WEBHOOK_SECRET` env, **unset → per-boot random** (the `telemetry_ingest_secret` pattern) — meaning webhooks fail closed when unconfigured, which is correct for a payment surface. Missing/bad signature → 401, event_id dedupe via UniqueConstraint + check-first (the `insert_application` at-least-once pattern). Raw body read via `await request.body()` (the resume route is the nearest raw-request precedent). | The v0.4.7 ingest-token pattern (per-boot secret, compare_digest, length-prefixed binding) is the proven in-tree HMAC precedent; Stripe's timestamp.body scheme is the industry shape and tolerates clock skew via a replay window (±5 min, pinned by test). | 0.80 |
|
||||
| D-078 | Catalog = **seeded DB tables, not a code constant**: `packages` (one-time: single $49/1 post/30d, bundle $399/10 posts/90d each, enterprise) + `plans` (recurring: starter $99/mo, pro $299/mo, enterprise-talent custom) seeded idempotently at store init from a versioned code constant (the SeededCorpusSource `seed_corpus.json` pattern). Prices = integer cents, currency `usd` fixed. Purchases **snapshot** price/name at buy time (catalog edits never rewrite history). | The pricing page and admin checkout must read ONE source (data-driven tier copy, REQ-9-002); DB tables allow future admin price edits without code changes while snapshots keep financial history immutable. Code-constant-only would make REQ-9-002's "no hardcoded tier copy drifting from backend" harder to prove. | 0.80 |
|
||||
| D-079 | Pricing page = **server shell retained** (static-export metadata stays — A-411) + new client component fetching `/v1/billing/catalog` (the A-406 board-client pattern: AbortController, honest loading/error/empty states). CTA buttons at pilot = **contact path** (mailto + "operator-mediated checkout" copy) — NOT self-serve purchase (no employer auth, D-076). The real checkout trigger lives in the admin surface (operator buys on behalf of an employer). | Self-serve CTAs without employer auth would be a dishonest button; the admin-mediated purchase is the honest pilot flow. The pricing page's job in v0.9 is truth: real catalog data, real states. | 0.80 |
|
||||
| D-080 | Entitlement model: `purchases` table (one-time packages: `posts_limit`/`posts_used`/`expires_at` snapshot) + `subscriptions` (recurring plans). Posting creation consumes 1 post from the **newest non-expired purchase with remaining posts**, else 402 with upgrade-CTA dict payload (the `require_verified_age` dict-detail precedent); enterprise = manual unlimited grant (admin route, provenance-recorded). Store tables (7th D-027 family): `packages`, `plans`, `purchases`, `subscriptions`, `subscription_events`, `checkout_sessions`, `billing_events` — `purchases` + `billing_events` added to the REQ-9-001 list (one-time packages + full audit trail need their own tables; a one-time purchase is NOT a degenerate subscription). | Mixing one-time packs into subscriptions overloads the state machine (REQ-9-005's states don't apply to a 10-post bundle); the identity/store.py + marketplace/store.py replication pattern makes an 7-table store cheap. | 0.75 |
|
||||
| D-081 | Money = **integer cents** end-to-end (pydantic `int` with ge=0, TS `number` documented as cents); no floats anywhere in billing; currency `usd` only (multi-currency out of scope). | Float money is the classic billing bug; Stripe itself is cents-native. The dual-schema pins (pins.test.ts) enforce the int wire type both sides. | 0.90 |
|
||||
| D-082 | Mock checkout completion = **a mock-provider-only confirm route** (`POST /v1/billing/mock/complete`, mounted ONLY when provider=mock): it mints a properly-signed webhook event and POSTs it through the REAL webhook processing path (fetch to self or direct handler call — same code path, proven by test). This is the E2E payment proof without cloud. The route 404s when provider=stripe. | The pipeline must be provable end-to-end in tests (webhook → dedupe → entitlement); a confirm route mounted only in mock mode is the same shape as the sitemap's env-gated routes and can never be hit on a real deployment (factory mounts it conditionally). | 0.70 |
|
||||
| D-083 | Subscription lifecycle: states `trialing → active → past_due → cancelled|expired` (+ `upgraded`), transitions driven ONLY by webhook events or admin manual actions. **Event names are OUR canonical names, normalized at the provider boundary** (R-43: Stripe has no `subscription.renewed`/`checkout.completed`): `checkout.completed` ← `checkout.session.completed`; `invoice.paid` ← `invoice.paid` (also accept `invoice.payment_succeeded`); `subscription.cancelled` ← `customer.subscription.deleted`; `subscription.renewed` ← `invoice.paid` on a renewal invoice (corroborated by `customer.subscription.updated`); provider event ids stored + deduped verbatim (never normalized). Completion predicate `status=complete AND payment_status=paid` (R-37). `past_due` grace = 7 days (module constant, test-pinned) before expiry downgrade; renewals extend `expires_at` idempotently (event_id dedupe makes double-fire safe); manual grant/revoke records `source: "manual"` + operator provenance in `billing_events`. Invalid transitions → `InvalidTransition` → 409 (store precedent). | At-least-once webhooks + idempotent state transitions is the A-309 seq-lease lesson applied to billing; manual remediation must be audit-visible (REQ-9-005's "recorded as manual events with provenance"). Research R-41..R-45 verified the state/event mapping against Stripe's actual enums. | 0.80 |
|
||||
| D-084 | Wire discipline: billing types in `packages/types/billing.ts` + pydantic contracts in `ai_service/billing/base.py`, dual-schema pinned field-for-field in `apps/web/tests/pins.test.ts` (G-108 discipline); `engine-client.ts` gains `listBillingCatalog()` + a `PaymentRequiredError` (402, dict-detail discrimination — the existing `parseError` VerifyRequiredError precedent). | Every prior cross-boundary wire (PostingSummary, SearchResult, facets) is pinned this way; the 402 CTA payload must be machine-readable for the admin surface. | 0.85 |
|
||||
|
||||
## Milestone v0.8 — Ship Anywhere (COMPLETE, Feature, 2026-09-27 → 2026-09-29)
|
||||
|
||||
**Scope (founder directive 2026-09-26, options 1–4 confirmed + scope decisions answered 2026-09-26/27):** Release and deployment guides for admins. nextcraft must be installable on any Debian-based Linux server, via every mainstream channel, with release consistency enforced by automation:
|
||||
|
||||
1. **Docker container** (Option 1): packaged image with all dependencies pre-loaded, built and uploaded to the Gitea container registry on every phase release
|
||||
2. **Release binaries** (Option 2, extends the existing v0.4 line): the CLI published as binaries in every release's downloads — x64 (existing) plus arm64, plus .deb packages
|
||||
3. **CLI full suite** (Option 3): the CLI contains the full application suite for easy onboarding — one binary takes an admin zero → running
|
||||
4. **Release consistency** (Option 4): pre-commit hooks + Gitea Actions pipelines so every release is made the same way
|
||||
|
||||
**Founder scope decisions (2026-09-26/27):** deb + arm64 both added (packaging breadth); docker container unprivileged-by-default with honest sandbox degrade (userns conflict documented, privileged variant documented); Gitea act_runner stood up by this milestone on founder-provided LXC CT 113; one milestone, 6 phases (P0 + P1–P5 + P6 final). Three org-level runners on CT 113 as docker containers (gitea/act_runner, sibling-container mode, host docker.sock, hybrid labels ubuntu-latest + node/python/release).
|
||||
|
||||
**D-073 (founder directive, 2026-09-29, post-milestone):** CT 113 root password + the org runner registration token are **RETAINED for future use — rotation declined**. This supersedes the G-206 rotation request carried in the v0.7.6 ship notes. Both are stored in the sanctioned secrets file (`.ciagent/.env.secrets`: gitignored, 0600, the only copies — verified by tree-wide scan). The live-host deploy key (`nc_ci_deploy` → root@10.0.0.105) is likewise persistent per founder approval. Security posture: the credentials never appear in git history, workflows, container layers, or release assets; access remains SSH-key-gated on both hosts.
|
||||
|
||||
**Out of scope:** Windows/macOS targets, apt repository hosting (debs ship as release assets), Helm/K8s deployment, Postgres migration, browser E2E tooling.
|
||||
|
||||
**Success (milestone-level):** `docker run` / `.deb install` / one-liner binary each take a fresh Debian server to a running verified stack; every release carries binary + checksum + deb + image tag automatically; a push to any branch runs lint/typecheck/tests on the runner fleet; admins have a single deploy guide covering all channels with upgrade + troubleshooting paths.
|
||||
|
||||
## Clarify decisions (D-063+, CLARIFY stage full autonomy, 2026-09-27)
|
||||
|
||||
| ID | Decision | Rationale | Confidence |
|
||||
|----|-----------|-----------|------------|
|
||||
| D-063 | CI push lane = lint + typecheck + **fast lanes only**: `ai:test:fast` (`-m "not real_server and not userns"`), default `web:test` + `cli:test` (E2E stays env-gated out). `real_server`/`userns` NEVER run in job containers. | `userns` is blocked by docker's default seccomp in the sibling-container runners (nested `unshare --user` fails — infeasible, not merely slow); `real_server` is feasible (plain uvicorn processes) but the locked spec wording is "pytest fast lane" and push feedback stays minutes-scale; both lanes remain local/verify-lane surfaces. The CLI E2E (900s real bootstrap) is already env-gated out of `cli:test` (D-055) and stays out | 0.85 |
|
||||
| D-064 | Tag-triggered Actions workflow is the **exclusive owner** of release assets + registry push (builds x64/arm64 binaries, checksums, debs from the tag checkout; consumes Actions secrets `GITEA_TOKEN`/`REGISTRY_TOKEN` set via the self-serve PUT mechanism). The local ship path stops calling `scripts/release-assets.sh` once the workflow is green; the script remains as the manual fallback (its .env-only token resolution unchanged). | Exclusive ownership kills the double-attach race (ship workflow + tag trigger would both upload the same asset names); the job must build from a clean tag checkout anyway (dist/ artifacts don't exist in the job), so the script's attach-what-exists logic can't serve the workflow; "release consistency enforced by automation" (founder Option 4) means the pipeline, not the founder's box, is the release maker | 0.75 |
|
||||
| D-065 | Image = `git.coreci.dev/coreci/nextcraft`, tags = the release semver (`v0.7.x`) on every phase ship + `latest` moved to the newest release. No per-push/branch tags. Admin guides pin semver; `latest` is a convenience alias only. | The Gitea registry is owner/repo-scoped (`{instance}/{owner}/{repo}`) — no other image name is addressable, so the naming question has exactly one answer; per-push tags would churn the 32 GB runner disk for zero admin value while the release-consistency scope is phase releases | 0.85 |
|
||||
| D-066 | The runtime image embeds the CLI binary (`/usr/local/bin/nextcraft`): `docker exec` gives admins in-container `doctor`/`verify`/`guide`; `bootstrap`/`deploy`/`dev` detect the container env and refuse honestly, pointing at the docker-channel paths. | REQ-8-004's "detects container env + suggests volume/privileged facts" is only truthful from inside the container (uid_map/seccomp/userns reality lives there — a host-side CLI cannot probe it without knowing the container name); ~117 MB on an image already carrying a venv + static export is acceptable; refusing beats repo-surgery-in-container (git clone + rebuild inside an immutable image is the anti-pattern the docker channel exists to remove) | 0.80 |
|
||||
| D-067 | deb = CLI binary at `/usr/bin/nextcraft` + package docs, nothing else. NO systemd unit in the deb — `deploy --service` owns service-unit generation (it bakes the real clone + binary paths; a deb unit would be stale/wrong). No proxy config fragments (HAProxy recipes are per-box, live in the deploy guide). postinst runs `nextcraft doctor` best-effort as an **advisory** summary (output printed, exit never fails the dpkg transaction) + prints next-steps (`doctor` → `deploy --service`). | The deb packages the CLI, not the stack — the unit's paths only exist after deploy chooses a clone dir; postinst failing on missing node/pnpm would brick unattended installs while advisory doctor output still tells the admin what to fix (honest-loud, never blocking — the install.sh degradation pattern) | 0.75 |
|
||||
| D-068 | Degrade detection = **capability probe**, not markers: at boot + per environment-create the backend attempts a real `unshare --user --map-root-user` (the proven `tests/helpers/userns.py` pattern promoted into the sandbox module); `/.dockerenv` + an `NC_CONTAINER=1` entrypoint var only flavor the remediation text. Degrade semantics: learner environment creation **rejects honestly** (503 + pointer to the documented privileged/seccomp variant) + loud boot notice + doctor surfaces the degraded capability; chat/agents/grading keep working. This supersedes A-101's cwd-jail fallback for deployed schools. | The probe is the truth source — `/.dockerenv` says "docker" but not "userns blocked" (a privileged container passes userns and must NOT degrade; a non-docker host with userns disabled must); unisolated learner code would run as the service user next to provider keys + network — the namespace fabric exists precisely to prevent that, so the A-101 fallback (founder-box convenience) is unacceptable for untrusted multi-learner deployments; reject-with-remediation is the honest degrade | 0.70 |
|
||||
| D-069 | arm64 = **cross-build on the x64 runner, no QEMU for the build**: the SEA pipeline is arch-agnostic file surgery (esbuild bundle + postject into an arm64 node base binary fetched as a build input); x64 + arm64 binaries and debs build in one release job in minutes. QEMU binfmt (if registered on CT 113) adds an optional `--version` smoke of the arm64 binary; `dpkg-deb` never executes its payload, so the deb needs no emulation. No multi-arch docker image in v0.8 (spec scope is binaries + debs; image stays amd64). RESEARCH verifies the arm64 node base + binfmt availability. | Emulated builds are the slow path and unnecessary: SEA injection never runs the target binary; the only execution need is a smoke, which binfmt provides opportunistically; multi-arch manifests would pull image-arm64 into a scope the spec never asked for | 0.70 |
|
||||
| D-070 | pre-commit = ONE root `.pre-commit-config.yaml` for the whole monorepo, directory-scoped (ruff on Python paths, eslint/tsc via workspace-scoped invocations), local-only, no network at hook run. On boxes without the toolchain, hooks **fail loudly** — never silently skip; `--no-verify` is the visible deliberate bypass and CI is the authoritative backstop. | A silently-skipped hook lies about release consistency (Option 4's whole point); pre-commit is inherently a repo-root single config — per-workspace configs buy nothing; CI remains the enforcement gate so a bypassed local hook cannot ship unlinted code | 0.80 |
|
||||
| D-071 | Docker-channel upgrade = `docker pull <tag>` + **recreate** the container (state persists via the `~/.nextcraft` volume) — `deploy`/`bootstrap` never run in-container (D-066 refuse). Binary channel = re-run install.sh + `deploy --service`; deb channel = `dpkg -i` the new deb + `deploy --service` (both idempotent). doctor/guide describe the detected channel's upgrade path. | The image is immutable — deploy-from-repo inside a container is meaningless by construction; the other two channels keep the v0.4.6 idempotent deploy as their upgrade rail (proven on the live box) | 0.85 |
|
||||
| D-072 | `nextcraft guide` = **offline-first embedded text** (man-page style): channel-aware sections checked into the CLI source (mirrored from deploy/README.md at build time), zero runtime fetches; forge URLs print as pointers to the living runbook. | Fresh-box and degraded installs (no network, no clone) are exactly when guidance is needed; the binary is self-contained by design (SEA) — embedding honors that; runtime fetching would make the guide fail precisely on broken boxes | 0.80 |
|
||||
|
||||
## v0.8 research conclusions (Phase 0 RESEARCH, 2026-09-27)
|
||||
|
||||
Full evidence + concrete commands live in `.ciagent/RESEARCH.md` (R-1..R-32); architecture in ARCHITECTURE.md's "v0.8 Distribution & Release Architecture" section. Brief conclusions:
|
||||
|
||||
1. **Runner image = `gitea/runner:3`** — Docker Hub's `gitea/act_runner` is deprecated/renamed; runner 3.x needs Gitea ≥1.21 (instance probe-verified at 1.26.1). Basic flavour + host docker.sock = exactly sibling mode.
|
||||
2. **3 containers, one per lane, each with its OWN `/data` volume** (`.runner` registration file — shared = lock refusal + identity loss). Registration token via env at bring-up only (founder chat-provided, reset after fleet green, never in any repo file). Org-level scope comes from the token itself.
|
||||
3. **Labels via `GITEA_RUNNER_LABELS` env** (passed to both register + daemon): `node:docker://node:24-bookworm`, `python:docker://python:3.11-bookworm`, `release:docker://node:24-bookworm`, `ubuntu-latest:docker://docker.gitea.com/runner-images:ubuntu-latest`. Unmatched `runs-on` silently runs on a default image — always pin our labels.
|
||||
4. **Capacity 1 per runner** (config default; also bounds docker subnet consumption). Fleet concurrency = 3.
|
||||
5. **Cache requires `cache.host` + published port** on dockerized runners (per-job networks make the auto-detected cache address unreachable — actions/cache ETIMEDOUTs otherwise); 32 GB guarded by cache caps + health_check disk floor + host prune cron. `actions/cache@v4` works on runner 3.x (cache v2 API, stock action self-patched).
|
||||
6. **Sibling-mode path alignment NOT needed for our jobs** (no bind_workdir; `docker build` TARS context over the API); documented as the gotcha if a future workflow bind-mounts.
|
||||
7. **Push lane = repo's own scripts, no turbo lint wholesale** (it pulls venv-dependent ai-service tasks): node lane (corepack pnpm 12.3.4, eslint+tsc per TS workspace, web/cli node:test) + python lane (bootstrap.sh venv, ruff, mypy, FAST=1 test.sh). D-063's fast-only rule is both policy and physical (docker default seccomp blocks nested unshare). ubuntu-latest lane = dispatch verification only.
|
||||
8. **Release lane = tag-triggered exclusive owner**: builds from the tag checkout, stamps with `gitea.ref_name`, attaches assets via the same REST API scripts/release-assets.sh uses (NOT actions/upload-artifact); reuses the API in-workflow, script untouched as manual fallback (.env-only token resolution preserved).
|
||||
9. **Automatic job GITEA_TOKEN cannot publish packages (upstream-confirmed)** — registry push needs the `REGISTRY_TOKEN` PAT secret (self-serve PUT first, founder UI fallback). `docker/build-push-action` unnecessary: plain login+build+push for a single-arch amd64 image.
|
||||
10. **Dockerfile**: web-export stage (NEXT_PUBLIC_AI_SERVICE_URL=self, build-time-only) + venv stage (prod deps) + `python:3.11-slim-bookworm` runtime (~400-500 MB incl. the ~117 MB CLI embed, D-066): non-root, urllib `/health` healthcheck (no curl in slim), `VOLUME /home/nextcraft/.nextcraft` (state root is `~/.nextcraft` by config default, env-overridable with ~-expansion), zero AI_* env at build, all keys optional at runtime (G-11).
|
||||
11. **deb**: `dpkg-deb --root-owner-group -Zxz` staging build (never executes payload — cross-arch free), Version = tag minus `v`, empty Depends + `Recommends: nodejs, python3, git, util-linux` (soft deps), postinst advisory doctor (exit 0 always), no unit, no proxy fragments (D-067).
|
||||
12. **arm64 cross-build QEMU-free**: the only arch-specific step in build-binary.mjs is `copyFileSync(process.execPath, out)` — replaced by a copy from the official arm64 node tarball (probe: nodejs.org dist 200, 30 MB); esbuild bundle + postject ELF-note injection are arch-agnostic file surgery. SEA blob cross-arch needs a P3 probe (config has no useCodeCache/useSnapshot — good sign); binfmt `--version` smoke optional per D-069.
|
||||
13. **D-068 degrade**: probe promoted verbatim from tests/helpers/userns.py into `ai_service/sandbox/capability.py`; boot notice copies the main.py G-11 warning pattern; per-create rejects 503 via a new SandboxUnavailableError arm beside the existing PoolFullError→503 (today it 500s); doctor upgrades `which unshare` to a real userns attempt. Markers only flavor text.
|
||||
14. **install.sh arch-resolve**: `x86_64`→x64, `aarch64|arm64`→arm64; sha256+version integrity gates stay byte-identical per arch.
|
||||
15. **Admin-guide structure** (REQ-8-005): per-channel chapters (docker/deb/binary) each ending in the SAME verification checklist, an upgrade matrix table (D-071 semantics), symptom/cause/fix troubleshooting tables, where-state-lives table per channel, sibling-mode accepted-risk row, SEA/corepack/cache-egress probe outcomes recorded. Ecosystem scan: Ollama installer UX, Tailscale per-channel doc skeleton, Gitea/act_runner's own dual distribution, Miniflux binary+image+deb shape.
|
||||
|
||||
## Milestone v0.7 — Test Harness Review (COMPLETE, shipped as v0.6.6, 2026-09-26)
|
||||
|
||||
**Scope (founder directive post-v0.6, scope decisions answered 2026-09-26):** Once v0.6 shipped, review the entire test harness — make sure the right tests are being run, make them effective, cut tests that provide no real value, review all warnings, and address all of it within this single milestone. NFR refinement-only: zero `feat:` commits (D-001 purity gate at final phase).
|
||||
|
||||
**Baseline research (completed at phase 0, 2026-09-26):** 785 tests (671 pytest / 53 web node:test / 61 CLI node:test), all green. Coverage unmeasured anywhere. No framework-level timeouts (20-30s polling loops, 600s CLI bootstrap step). Zero pytest markers despite a real split (fast-unit vs real-uvicorn vs real-userns). Web tests outside the turbo pipeline. 1,716 warnings per pytest run (~99% from 14 `session.query()` SQLModel deprecation sites; 14 ResourceWarning sites from unclosed UploadFile/sockets/file). All 81 Python `# noqa` inert (rules not in the ruff select-set); 5 orphaned eslint-disable comments; **no ESLint exists at all** (turbo lint is a no-op for 5 of 6 packages). `recharts@2.15.4` deprecated direct dep. No Python type checker (27 inert `# type: ignore`). Stale PLAN.md counts (488/22/61 vs actual 671/53/61).
|
||||
|
||||
**Founder scope decisions:** D-048 ESLint included; D-049 recharts 2→3 included; D-050 source-pin triage (cut trivial, keep real regression pins); D-051 mypy included.
|
||||
|
||||
**Out of scope:** Gitea Actions CI YAML (the CIAgent verify hooks are the CI), Playwright/browser E2E tooling, new features of any kind.
|
||||
|
||||
**Success (milestone-level):** pytest runs green with zero first-party warnings; the fast-subset (`-m fast`) completes in seconds; coverage measured and reported in all three workspaces; `turbo lint` exercises all 6 packages; all suppressions (noqa/eslint-disable/ts-ignore/type:ignore) are enforced-and-meaningful or gone; the suite is smaller (trivial tests cut) with no loss of regression value.
|
||||
|
||||
**Clarify decisions (D-052+, CLARIFY stage full autonomy, 2026-09-26):**
|
||||
|
||||
| ID | Decision | Rationale | Confidence |
|
||||
|----|----------|-----------|------------|
|
||||
| D-052 | Coverage tooling: **pytest-cov for ai-service; c8 for web/cli** wrapping the existing `tsx --test` runner — no vitest/nyc/istanbul, no runner swap | c8 handles tsx source maps and adds one devDep per workspace; node's `--experimental-test-coverage` mis-reports through the tsx loader; vitest adoption is a framework swap, not NFR refinement | 0.85 |
|
||||
| D-053 | Marker taxonomy: registered `fast`/`real_server`/`userns` under `--strict-markers`; **unmarked tests default to fast**; canonical fast run = `-m "not real_server and not userns"` (aliased `ai:test:fast`); `real_server`/`userns` always exclude from the fast subset | Zero-churn — no need to stamp ~600 unit tests with `fast`; the exclusion markers carry the selection; strict mode catches typo'd markers that would silently deselect | 0.85 |
|
||||
| D-054 | pytest-timeout: **`signal` method**, global 60s (comfortably above the 20-30s polling loops), conftest collection hook bumps to 180s for `real_server`/`userns`-marked tests; `@pytest.mark.timeout` for known outliers | Linux-only target makes SIGALRM safe and accurate; the thread method can't cancel blocked calls; 60s bounds a hang without false-positiving real polling | 0.80 |
|
||||
| D-055 | CLI fresh-clone E2E: **keep the 600s real bootstrap as-is** (the real path is the value), give it an explicit per-test 900s budget (600 + slack), env-gate it out of the default `cli:test` run with a dedicated `cli:test:e2e` script for the verify/ship path | A 10-minute E2E on every run is wrong for feedback loops but too valuable to cut; opt-in keeps both properties | 0.85 |
|
||||
| D-056 | filterwarnings: **`error` as the base action** (new first-party warnings fail) + a narrow enumerated allowlist of upstream ignores each scoped by exact message + emitting module (fastapi/starlette TestClient httpx warning, anyio BlockingPortal); no blanket category ignores, no ignores on `ai_service.*`; first-party ResourceWarnings fixed at source, never ignored | Error-by-default makes warning hygiene self-enforcing; module-scoped ignores cannot mask first-party regressions; after REQ-7-003 cleanups the non-ignored set is empty so no dedup machinery needed | 0.85 |
|
||||
| D-057 | Source-pin triage rule (operationalizes D-050): **KEEP a pin iff** it encodes a documented regression lesson (E87-style) or verifies cross-boundary wiring invisible to typecheck/build/behavioral tests (runtime fetch wiring, env keys, gate composition, JSON-LD presence); **CUT a pin** whose assertion duplicates another test or merely asserts code says what it says; kept pins move to a single `pins.test.ts` naming their regression | Falsifiable per-assertion; expected outcome ~5-8 kept of the 21 pin sites; cuts tautologies with zero regression loss | 0.75 |
|
||||
| D-058 | mypy strictness: **relaxed-first baseline** — `check_untyped_defs`, `warn_unused_ignores` (each of the 27 ignores either types or is removed), `no_implicit_optional`, `warn_redundant_casts`, `warn_unreachable`; NOT `strict=true`; per-module tightening via `[[tool.mypy.overrides]]` available later | Full strict on a never-myped codebase turns P5 into an annotation retrofit; `warn_unused_ignores` delivers the milestone goal (suppressions meaningful or gone) at realistic cost | 0.85 |
|
||||
| D-059 | recharts 2→3 chart-surface verification = **`tsc --noEmit` green + `next build` static export green (SSR-renders the chart pages) + existing web tests green**; no jsdom/happy-dom render harness (new deps = framework addition); live mount probe on the deployed site as the operational smoke | Build+typecheck exercise the real React 19/recharts 3 integration through SSR; browser/render tooling is explicitly out of scope for v0.7 | 0.80 |
|
||||
| D-060 | Shared Python test helpers: **`tests/helpers/` package** (`KillableProxy`, `free_port`, userns probe, real-uvicorn `serve`, `wirePosting`) imported as `from tests.helpers...`; fixtures stay in conftest.py; changes are test-internal import paths only — no public/test-facing API beyond that | Helpers are direct utilities, conftest is for fixtures — explicit imports keep call-site dependency honest; `tests/` is already a package (`__init__.py` present) | 0.90 |
|
||||
| D-061 | Version drift: **pyproject.toml is the single version source** — bumped to `0.5.6` (the shipped line); `FastAPI(version=)` derives from `importlib.metadata.version("nextcraft-ai-service")` (safe fallback for un-installed runs); stale version comments removed in the same sweep | One hardcoded "0.3.0", one pyproject "0.2.0", and a shipped 0.5.x all drifted — metadata lookup makes drift structurally impossible | 0.90 |
|
||||
|
||||
## Milestone v0.6 — Marketplace Engine (COMPLETE, shipped as v0.5.6, 2026-09-26)
|
||||
|
||||
**Scope (auto-decided at SPECIFY per full autonomy — founder scope question left unanswered 2026-09-21):**
|
||||
|
||||
@@ -203,6 +359,7 @@ The following remain deferred beyond v0.3 and will be activated in subsequent mi
|
||||
|
||||
| ID | Decision | Rationale | Outcome |
|
||||
|----|----------|-----------|---------|
|
||||
| D-085 | v0.10 = B2B Employer Network (auto-decided at SPECIFY, full autonomy D-007; founder scope confirmed 2026-09-30) | Real employer auth/accounts + self-serve: registered employer accounts with sessions, employer-entity claim/verify, self-serve posting management (draft→published→closed on own entities), self-serve checkout (v0.9 catalog with employer-principal buyers, superseding D-076 operator mediation), employer dashboard real-data conversion. Rationale: A-407 sequences employer auth post-payments (payments shipped v0.9); A-401/D-076/D-079 deferred self-serve precisely pending this; the employer dashboard is the last mock-only surface; CIRR tracking (REQ-F-020) needs employer-side data. Confidence 0.80 ≥ threshold 0.60 (D-007). | Milestone scope locked at SPECIFY; tags on v0.9.x line; feature milestone; branch milestone/v0.10-b2b-employer-network |
|
||||
| D-001 | Milestone v0.1 = UI/UX prototype only, no business logic | Founder directive: validate UX before building backend. Prototype must be agreed upon before proceeding to business logic. | Scope locked to frontend surfaces with mock data |
|
||||
| D-002 | MAJOR 0 until MVP released | Founder directive: remain on v0.x until MVP is validated. Signals pre-release status. | All tags are v0.x.y until MVP agreement |
|
||||
| D-003 | TypeScript monorepo (pnpm/turborepo) + Next.js | Unified codebase for all 4 surfaces. Shared component library, types, mock data. Next.js App Router for route-based surface separation. Python AI services deferred to later milestones. | Monorepo structure with apps/web + packages/* |
|
||||
@@ -219,6 +376,7 @@ The following remain deferred beyond v0.3 and will be activated in subsequent mi
|
||||
| D-014 | Provider-agnostic LLM layer; ollama-cloud as initial provider | OpenAI-compatible client abstraction with pluggable providers: ollama-cloud (https://ollama.com/v1, default), local OpenAI-compatible endpoint, deterministic mock (tests/CI). Keys in gitignored .ciagent/.env.secrets, never in code or commits. | apps/ai-service llm package with 3 providers; default=ollama-cloud |
|
||||
| D-015 | All six agents implemented as real LLM services; engines mocked | Coach/Tutor/Mentor fully real. Lab/Assessor/Proctor are real LLM logic over mock inputs (simulated telemetry, pre-baked artifacts) since sandbox fabric, assessment engine, and identity verification are v0.3+. Consistent with v0.1's mock-data approach. | REQ-F-001..006 complete in v0.2; real engines deferred to v0.3+ |
|
||||
| D-016 | v0.4 = Distribution & Bootstrap CLI (founder directive supersedes previously-named v0.4 seams) | Founder directive 2026-09-12: focus this milestone on streamlining install, a bootstrap CLI with a one-liner install script, ongoing release binaries. Real server STT/TTS, KYC, design/simulation envs, seq-lease move to v0.5. | Milestone scope locked at SPECIFY; binary = CLI-only, linux x64 |
|
||||
| D-074 | v0.9 = Payment Engine (auto-decided at SPECIFY, full autonomy; founder scope question unanswered post-v0.8) | Activates REQ-F-018 as REQ-9-001..005: posting packages (single/bundle/enterprise), talent-access plans, subscription tiers — checkout, provider webhooks, entitlement enforcement on posting creation, subscription lifecycle. Provider-agnostic protocol, mock-first (D-014 pattern). Rationale: ≥1,000 placements requires a monetized self-serve employer side; payments is the only high-priority REQ deferred since v0.3 that unblocks employer self-serve (A-407) and paid postings precede CIRR tracking. Confidence 0.80 ≥ threshold 0.60 (D-007). | Milestone scope locked at SPECIFY; tags on v0.8.x line; feature milestone; branch milestone/v0.9-payment-engine |
|
||||
| D-047 | v0.6 = Marketplace Engine (auto-decided at SPECIFY, full autonomy; founder scope question left unanswered 2026-09-21) | Activates REQ-F-011..016 as REQ-6-001..006: real marketplace backend (aggregation, tagging, vector search, enrichment, resume parsing, SEO pages). Rationale: the guiding outcome (≥1,000 placements via the marketplace) runs through the only surface with zero backend; every prior milestone fed the credential side, placement side is the bottleneck. Confidence 0.80 ≥ threshold 0.60 (D-007). External 3M+ job corpus scaled to pilot (adapter contract preserves the full-scale path). | Milestone scope locked at SPECIFY; tags on v0.5.x line; feature milestone |
|
||||
| D-039 | Single-port deploy + unattended dev (v0.3.6 hotfix, founder directive) | Only :8420 reachable behind HAProxy; site was down (domain root hit the API 404). Web app = static export served same-origin by the ai-service (`AI_WEB_STATIC_DIR`); `dev -d`/`stop`/`log` daemonize ops; durable state (DB, sandboxes, pid/log) moves to `~/.nextcraft/` out of the repo. | One port serves UI+API; unattended deploy recipe in deploy/README.md |
|
||||
|
||||
@@ -228,4 +386,4 @@ The following remain deferred beyond v0.3 and will be activated in subsequent mi
|
||||
|
||||
Nextcraft is being built by a solo founder using the CIAgent v0.7.0 autonomous pipeline. The vision document defines a 36-month, 3-phase roadmap to ≥1,000 placements. The first CIAgent milestone (v0.1) is intentionally scoped to UI/UX only — validating the product vision through interactive prototypes before any backend or business logic investment.
|
||||
|
||||
The four surfaces (Learner, Marketplace, Employer Dashboard, Admin) map directly to the four audiences in the vision: learners, employers, marketplace operators, and platform administrators. The prototype will demonstrate the complete user journey across all surfaces with realistic mock data reflecting the AI-era competency stacks, AI-orchestration job listings, and artifact+process trace+oral defense credential model.
|
||||
The four surfaces (Learner, Marketplace, Employer Dashboard, Admin) map directly to the four audiences in the vision: learners, employers, marketplace operators, and platform administrators. The prototype will demonstrate the complete user journey across all surfaces with realistic mock data reflecting the AI-era competency stacks, AI-orchestration job listings, and artifact+process trace+oral defense credential model.
|
||||
|
||||
+201
-17
@@ -1,32 +1,206 @@
|
||||
# Nextcraft — REQUIREMENTS.md
|
||||
|
||||
## v0.6 Requirements (ACTIVE — Marketplace Engine, milestone v0.6)
|
||||
## v0.11 Requirements (Complete — Placement Tracking and Audit, Feature; shipped as v0.10.6)
|
||||
|
||||
**Milestone type: Feature** — CIRR-style placement tracking and audit (REQ-F-020 activated per D-098). Tags on the v0.10.x line (P0 → v0.10.0 … P6 → v0.10.6 = milestone release); branch `milestone/v0.11-placement-tracking`. REQ-F-020 activated as REQ-11-001..005: the placement store + evidence model (REQ-11-001), the employer-side application state machine with audit-logged transitions (REQ-11-002), the placement reporting surfaces (REQ-11-003), the audit-grade export (REQ-11-004), learner-side placement visibility (REQ-11-005). Mock-first doctrine holds (no external systems, no third-party auditor integration — the export is the deliverable); tests never call a cloud.
|
||||
|
||||
### Placement Store + Evidence Model
|
||||
|
||||
| ID | Description | Priority | Phase | Status |
|
||||
|----|-------------|----------|-------|--------|
|
||||
| REQ-11-001 | Placement store + evidence model: `ai_service/placements/` module (D-031 extend pattern — 9th D-027 store family, shared DB file, `create_all` idempotent): `PlacementRow` (id, learner_id, employer_id, posting_id, application_id, role_title, start_date, status, created_at, decided_at) with partial UNIQUE on `application_id` WHERE status='active' — one ACTIVE placement per application, revoked rows stay in history (D-102, the G-316 conditional-uniqueness shape); `PlacementEventRow` (append-only ledger: application_id nullable+indexed, placement_id nullable, event_type, actor_type, actor_ref, payload, prev_hash, hash, created_at) — one global hash chain, sha256 over canonical JSON + prev_hash, `UNIQUE(prev_hash)` fork backstop (D-101), tamper-evident by append-only discipline + hash chain (the chain makes silent rewrites detectable, G-301-class integrity); evidence links resolved from existing rows only (posting ref from postings store, application ref from applications store, employer ref from the claimed entity — G-302 doctrine: never trust denormalized copies); SQLModel typed access, Protocol + SQLite impl pair (the employer-store pattern), tz-normalization, fail-closed on unknown inputs | critical | 1 | complete (v0.10.1) |
|
||||
|
||||
### Application State Machine
|
||||
|
||||
| ID | Description | Priority | Phase | Status |
|
||||
|----|-------------|----------|-------|--------|
|
||||
| REQ-11-002 | Employer-side application state machine: the v0.6 `ApplicationRow.status` extends from `submitted`-only to the hiring lifecycle (submitted → in_review → interview → offer → hired / rejected / withdrawn — forward-only with skip-forward, terminals have no outgoing edges, D-099; withdrawn learner- or operator-initiated, all others employer-principal-driven); transitions via per-target employer routes under `/v1/employers/applications` (`/{id}/in-review`, `/{id}/interview`, `/{id}/offer`, `/{id}/reject`, `/{id}/hire` with `{role_title, start_date}` — D-105) gated by the employer session + claimed-entity authorization (the posting's employer must be the session's claimed entity — 403 otherwise, G-311 gate order); every transition appends the placement ledger in the SAME transaction as the status write (application events + placement events on hired — D-100); rejected/withdrawn/hired are terminal with different semantics (hired creates the PlacementRow + role_title + start_date payload); admin routes retain operator oversight (admin transition + audit, the D-094 lane); learner read access stays the existing surface (their own application status history); G-319 scoping: learner identifiers become visible on employer surfaces only for applications on the session's claimed-entity postings (the own-postings list stays counts-only) | critical | 2 | complete (v0.10.2) |
|
||||
|
||||
### Placement Reporting
|
||||
|
||||
| ID | Description | Priority | Phase | Status |
|
||||
|----|-------------|----------|-------|--------|
|
||||
| REQ-11-003 | Placement reporting: aggregate placement counts computed from the ledger (per employer, per cohort month, cumulative toward the ≥1,000 guiding outcome); per-employer placement view (the employer dashboard gains a placements section — their hired applications with role/start date, honest empty states); per-learner view (the learner's application list gains outcome states); admin placement overview (the moderation page's network section gains aggregate counts + per-employer placement lists — the operator lane); counts join through existing stores (employer identity via claimed entities, learner via applications, posting via postings) | high | 3 | complete (v0.10.3) |
|
||||
|
||||
### Audit Export
|
||||
|
||||
| ID | Description | Priority | Phase | Status |
|
||||
|----|-------------|----------|-------|--------|
|
||||
| REQ-11-004 | CIRR-style audit export: admin-gated export routes (`GET /v1/placements/admin/export` + `GET /v1/placements/admin/export/summary`, text/markdown — D-108) producing the third-party-auditor dataset: (a) a cohort snapshot (all placements with employer refs, role titles, start dates, evidence chains); (b) per-placement evidence bundles (posting record, application record, state-transition history, decision provenance — each link resolved from source rows, never denormalized copies); (c) a methodology document (how a placement is defined, counted, and verified — the counting rules an auditor needs); (d) the event-ledger chain with head hash (tamper-evidence for the export itself); output as JSON + a human-readable summary; honest scoping (pilot scale: the export covers every placement in the DB, unbounded by date); export integrity test (re-export reproduces identical event chains + head hash, generated_at excluded — D-108) | critical | 4 | complete (v0.10.4) |
|
||||
|
||||
### Learner Placement Visibility
|
||||
|
||||
| ID | Description | Priority | Phase | Status |
|
||||
|----|-------------|----------|-------|--------|
|
||||
| REQ-11-005 | Learner-side placement visibility: the learner application surface gains outcome visibility via `GET /v1/marketplace/applications/{application_id}?learner_id=` (current status + full timestamped state history + placement record when hired — D-104) and `POST /v1/marketplace/applications/{application_id}/withdraw` (learner-gated per the D-043 composition: G-5 allowlist → verified 18+ → apply-rate window); placement confirmation (when hired, the learner sees the placement record — role title, employer, start date — sourced from the same ledger); no learner-initiated edits beyond withdrawn (status changes are employer/admin-driven only); the talent profile's placement badge stays absent until a placement exists (honest, the A-304 doctrine — no badge on the v0.1 mock pages) | medium | 5 | complete (v0.10.5) |
|
||||
|
||||
---
|
||||
|
||||
## v0.10 Requirements (Complete — B2B Employer Network, Feature; shipped as v0.9.6)
|
||||
|
||||
**Milestone type: Feature** — real employer auth/accounts + employer self-serve (the B2B employer network; activated per D-085). Shipped on the v0.9.x line (P0 → v0.9.0 … P6 → v0.9.6 = milestone release); branch `milestone/v0.10-b2b-employer-network`. All 5 requirements complete: the employer auth foundation with scrypt credentials + hashed sessions + throttles (REQ-10-001), the entity claim/verify flow with advisory evidence + admin approval (REQ-10-002), the dashboard real-data conversion with honest states (REQ-10-003), self-serve postings through the shared D-091 entitlement gate byte-identical with the admin path (REQ-10-004), self-serve checkout over the v0.9 catalog through the real webhook path + the admin network overview (REQ-10-005). Auth is session-based with hashed credentials (mock-first doctrine: no external auth provider, tests never call a cloud); admin operator routes are retained unchanged (D-043 composition untouched).
|
||||
|
||||
### Employer Auth Foundation
|
||||
|
||||
| ID | Description | Priority | Phase | Status |
|
||||
|----|-------------|----------|-------|--------|
|
||||
| REQ-10-001 | Employer auth foundation: `ai_service/employers/` module (D-031 extend pattern): employer account store (8th D-027 family — `employer_accounts`, `employer_sessions`, `employer_claims`, `employer_audit_events` tables, D-095) with SQLModel typed access; password hashing via stdlib `hashlib.scrypt` (D-086 — zero new deps, per-password random salt, self-describing params); session tokens as server-side store rows with the token stored hashed, fixed 7-day TTL evaluated lazily, revoke-on-logout (D-087); register/login/logout/me routes (`/v1/employers/auth/*`, Bearer session transport per D-090); rate limiting on auth routes (D-088 — per-email failed-login window + global attempt cap, the G-5 in-memory pattern); credentials + secrets env-only (D-014); fail-closed when unconfigured | critical | 1 | complete |
|
||||
|
||||
### Employer Entity Claim
|
||||
|
||||
| ID | Description | Priority | Phase | Status |
|
||||
|----|-------------|----------|-------|--------|
|
||||
| REQ-10-002 | Employer-entity claim/verify: an authenticated employer account claims an existing `EmployerRow` entity (the v0.6 ingested data) via a claim route; claims enter a pending state with recorded evidence (email-domain vs entity-website comparison — advisory signal, D-089) and activate via admin approval at pilot; claims recorded with provenance (`employer_claims`); one account : one entity (UniqueConstraint); admin routes for claim review/approve/reject (operator oversight retained, audit-logged per D-089); claimed-entity authorization: employers can only manage postings/purchases for their own entity | critical | 2 | complete |
|
||||
|
||||
### Employer Account Surface
|
||||
|
||||
| ID | Description | Priority | Phase | Status |
|
||||
|----|-------------|----------|-------|--------|
|
||||
| REQ-10-003 | Employer dashboard real-data conversion: the employer surface switches from v0.1 mock imports to runtime client fetches (A-406 pattern — AbortController, honest loading/error/empty states) via the engine-client employer section + sessionStorage session state (D-092); employer auth UI (login/register pages, session-gated dashboard shell, honest logged-out states); posting management reads the employer's own postings via the authenticated surface (draft → published → closed lifecycle visible); employer profile read from the claimed entity (enrichment retained); talent search + candidate profile pages stay the v0.1 mock (no candidate backend exists — honest out-of-scope, D-092); wire types in `packages/types/employer.ts` dual-schema pinned (G-108 discipline, D-093) | critical | 3 | complete (v0.9.3, release 951) |
|
||||
|
||||
### Self-Serve Posting Management
|
||||
|
||||
| ID | Description | Priority | Phase | Status |
|
||||
|----|-------------|----------|-------|--------|
|
||||
| REQ-10-004 | Self-serve posting management: employer-principal posting routes (`/v1/employers/postings/*`) — create draft, edit own drafts, publish own drafts, close own postings, list own postings with status facets; authorization: the entitlement check composes AFTER the employer session gate (401/403 precede any 402 — the admin-gate-first order preserved, G-311) with the 402 CTA unchanged, D-080 consumption model intact, via the shared api-layer helper extracting the v0.9 gate (D-091 — no duplication); posting creation consumes from the employer's own packages (the v0.9 entitlement check parameterized by the session's employer_id instead of request body); the admin posting routes remain (operator path unchanged, provenance-recorded); 18+ gate N/A (employer surface is not learner-facing; the D-043 learner gates untouched, D-097) | high | 4 | complete (v0.9.4, release 952) |
|
||||
|
||||
### Self-Serve Checkout
|
||||
|
||||
| ID | Description | Priority | Phase | Status |
|
||||
|----|-------------|----------|-------|--------|
|
||||
| REQ-10-005 | Self-serve checkout + admin network overview: employer-principal checkout (`/v1/employers/billing/checkout`) creating provider sessions for the catalog (the v0.9 billing module reused — provider protocol, webhooks, entitlement grants unchanged; buyer = session employer instead of operator mediation, superseding D-076 while admin routes stay as the operator fallback; D-091 composes the existing checkout route logic with the session principal); entitlement view for the employer's own purchases/subscriptions (current package, posts used/limit, expiry — honest states); pricing page CTAs convert from contact-path to employer-login-path (superseding D-079); admin surface gains the network overview on the marketplace moderation page (employer accounts list, claim queue with evidence signals, per-account entity + entitlement state — the operator oversight lane, D-094) | critical | 5 | complete (v0.9.5, release 953) |
|
||||
|
||||
---
|
||||
|
||||
## v0.9 Requirements (Complete — Payment Engine, Feature; shipped as v0.8.6)
|
||||
|
||||
**Milestone type: Feature** — payment processing and subscription management (REQ-F-018 activated per D-074). Shipped on the v0.8.x line (P0 → v0.8.0 … P6 → v0.8.6 = milestone release); branch `milestone/v0.9-payment-engine`. All 5 requirements complete: the billing module + 7th D-027 store + HMAC webhook core (REQ-9-001), the catalog + pricing surface (REQ-9-002), the checkout/webhook flow with per-session exactly-once grants (REQ-9-003), posting entitlement enforcement with honest 402s (REQ-9-004), the full subscription lifecycle + queryable audit log (REQ-9-005). — payment processing and subscription management (REQ-F-018 activated per D-074). Tags on the v0.8.x line (P0 → v0.8.0 … P6 → v0.8.6 = milestone release); branch `milestone/v0.9-payment-engine`. Provider-agnostic protocol, mock-first (D-014 pattern): tests never call Stripe; the real provider drops in by env config without API changes.
|
||||
|
||||
### Billing Foundation
|
||||
|
||||
| ID | Description | Priority | Phase | Status |
|
||||
|----|-------------|----------|-------|--------|
|
||||
| REQ-9-001 | Billing foundation: `ai_service/billing/` module (D-031 pattern — extend ai-service, no new apps): `PaymentProvider` protocol (create checkout session, retrieve session, cancel subscription, upgrade/downgrade subscription, list subscription events) + deterministic mock provider (approves-on-policy, synchronous state machine); SQLite billing store (7th D-027 family — `packages`, `plans`, `subscriptions`, `subscription_events`, `checkout_sessions` tables) with SQLModel typed access; webhook signature verification (HMAC, per-boot secret default — the v0.4.7 ingest-token pattern); provider selection via `AI_PAYMENT_PROVIDER=mock\|stripe` env (keys env-only, never committed); test-only mode is the default (mock) so the stack runs with zero keys | critical | 1 | complete |
|
||||
|
||||
### Catalog + Pricing Surface
|
||||
|
||||
| ID | Description | Priority | Phase | Status |
|
||||
|----|-------------|----------|-------|--------|
|
||||
| REQ-9-002 | Package catalog + real pricing surface: seeded package catalog (single posting, bundle ×5, enterprise-unlimited tiers + talent-access plans: basic/pro/enterprise per REQ-017's existing pricing-page tiers) exposed via `/v1/billing/catalog`; the pricing page switches from mock imports to runtime client fetch (A-406 pattern) with honest loading/error states; package features/limits data-driven from the catalog (no hardcoded tier copy drifting from backend); build-time static metadata retained (A-411) | critical | 2 | complete |
|
||||
|
||||
### Checkout Flow
|
||||
|
||||
| ID | Description | Priority | Phase | Status |
|
||||
|----|-------------|----------|-------|--------|
|
||||
| REQ-9-003 | Checkout + webhook flow: `POST /v1/billing/admin/checkout` (admin token-gated per D-076 — operator buys on an employer's behalf; buyer recorded as operator ref + employer ref) creates a provider checkout session for a catalog item; mock provider renders an in-app confirmation path; stripe provider redirects to Stripe Checkout (env-gated, never in tests); `POST /v1/billing/webhook` receives provider events with HMAC signature verification (reject 401 on bad signature — never process unsigned), idempotent event processing (event_id dedupe + per-session grant idempotency per G-303), entitlement granted on `checkout.completed` with state resolved from local rows only (G-302 — event payloads are untrusted ID references); webhook replay tolerance (at-least-once semantics — the A-309 seq pattern applied to billing) | critical | 3 | complete |
|
||||
|
||||
### Entitlement Enforcement
|
||||
|
||||
| ID | Description | Priority | Phase | Status |
|
||||
|----|-------------|----------|-------|--------|
|
||||
| REQ-9-004 | Posting entitlement enforcement: posting creation (admin API route per A-401) checks the employer's active package — posting limit reached → honest 402 with upgrade-CTA payload (pointing at catalog/checkout); unlimited/enterprise bypass; expired/cancelled package degrades to the same 402 path; entitlement check composed after the admin token gate (operator route — D-043 learner gate composition untouched); admin surface shows per-employer entitlement state (active package, posts used/limit, expiry) in the existing admin marketplace moderation view | high | 4 | complete |
|
||||
|
||||
### Subscription Lifecycle
|
||||
|
||||
| ID | Description | Priority | Phase | Status |
|
||||
|----|-------------|----------|-------|--------|
|
||||
| REQ-9-005 | Subscription lifecycle + billing admin: subscription states (trialing → active → past_due → cancelled/expired) with provider-driven transitions (webhook events `invoice.paid`, `invoice.payment_failed`, `subscription.cancelled`, `subscription.renewed`); renewals extend expiry idempotently; admin routes for manual grant/revoke/complement (operator remediation for failed webhooks — recorded as manual events with provenance); billing event log with full audit trail (every provider event + manual action stored, queryable); honest 402 + grace handling on payment failure (past_due grace window before downgrade) | high | 5 | complete |
|
||||
|
||||
## v0.8 Requirements (Complete — Ship Anywhere, Feature; shipped as v0.7.6)
|
||||
|
||||
**Milestone type: Feature** — new distribution channels (docker image, deb packages, arm64 binaries) and release automation (Gitea Actions, pre-commit). Tags on the v0.7.x line (P0 → v0.7.0 … P6 → v0.7.6 = milestone release); branch `milestone/v0.8-ship-anywhere`.
|
||||
|
||||
### Release Consistency Rails
|
||||
|
||||
| ID | Description | Priority | Phase | Status |
|
||||
|----|-------------|----------|-------|--------|
|
||||
| REQ-8-001 | Release-consistency rails: three org-level Gitea act_runners stood up on founder LXC CT 113 (10.0.0.113, docker containers in sibling-container mode via host /var/run/docker.sock, hybrid labels ubuntu-latest/node/python/release, org-level coreci scope, registration token founder-provided and reset after fleet green), `.gitea/workflows/` lint+typecheck+test pipeline on push (v0.7 toolchain: eslint, ruff, mypy, pytest fast lane, web/cli node:test; CI test lanes = fast only per D-063: `ai:test:fast` `-m "not real_server and not userns"`, default web/cli node:test, CLI E2E env-gated out — real_server/userns never run in job containers), tag-triggered release workflow as the exclusive owner of release assets + registry push (D-064; local release-assets.sh remains manual fallback), single root `.pre-commit-config.yaml` (ruff + eslint + tsc local-only fast hooks, directory-scoped whole-monorepo, no network, secrets never in hooks or workflow env; hooks fail loudly on missing toolchain, never silently skip — D-070; CI is the authoritative backstop), runner cache-hygiene (docker prune cron + cache caps, 32 GB disk), hello-world dispatch verification across all three labels | critical | 1 | complete |
|
||||
|
||||
### Container Channel
|
||||
|
||||
| ID | Description | Priority | Phase | Status |
|
||||
|----|-------------|----------|-------|--------|
|
||||
| REQ-8-002 | Docker image channel: multi-stage Dockerfile (deps layer: pnpm store + pip wheels pre-loaded; build layer: web static export with NEXT_PUBLIC_AI_SERVICE_URL=self; runtime: uvicorn :8420 serving API + export — single-port topology preserved; runtime image embeds the CLI binary at /usr/local/bin/nextcraft for in-container doctor/verify/guide — D-066), unprivileged default + honest degrade (capability probe at boot + per create — a real `unshare --user --map-root-user` attempt as the truth source, `/.dockerenv`/NC_CONTAINER only flavor remediation text; degraded = learner environment creation rejects 503 with privileged/seccomp remediation pointer + loud boot notice + doctor surfacing — D-068), healthcheck on /health, `~/.nextcraft` state volume, image pushed to the Gitea container registry as `git.coreci.dev/coreci/nextcraft` tagged semver release `v0.7.x` + `latest` on newest release (D-065), REGISTRY_TOKEN as Gitea Actions secret (self-serve PUT attempt first, founder UI fallback) | critical | 2 | complete |
|
||||
|
||||
### Debian-Native Channel
|
||||
|
||||
| ID | Description | Priority | Phase | Status |
|
||||
|----|-------------|----------|-------|--------|
|
||||
| REQ-8-003 | Debian packaging: arm64 SEA binary + sha256 sidecar cross-built on the x64 runner without QEMU for the build (arch-agnostic esbuild+postject file surgery into an arm64 node base; optional binfmt `--version` smoke — D-069), .deb packages (dpkg-deb) for x64+arm64 = CLI binary at /usr/bin/nextcraft + package docs only, NO systemd unit (deploy --service owns unit generation) and no proxy fragments; postinst runs `nextcraft doctor` best-effort advisory (never fails dpkg) + prints next-steps (D-067); all attached to every release's downloads by the tag-triggered workflow (D-064); install.sh arch-gate becomes arch-resolve (x64 + arm64 binary paths); deb install + binary install both end at `nextcraft doctor` verify | high | 3 | complete |
|
||||
|
||||
### CLI Onboarding
|
||||
|
||||
| ID | Description | Priority | Phase | Status |
|
||||
|----|-------------|----------|-------|--------|
|
||||
| REQ-8-004 | CLI full-suite onboarding: `nextcraft` alone takes an admin zero → running — doctor gains deb/docker-channel awareness (detects container env + suggests volume/privileged facts; detects deb install + knows its binary location; embedded in-container binary per D-066), `nextcraft guide` surfaces the admin runbook channel-appropriately as offline-first embedded text with forge pointers (D-072), docker-channel upgrade = docker pull + recreate (deploy/bootstrap refuse in-container — D-066/D-071), onboarding glue verified by an E2E test per channel (binary one-liner path exists from v0.4; docker + deb paths new) | high | 4 | complete |
|
||||
|
||||
### Admin Guides
|
||||
|
||||
| ID | Description | Priority | Phase | Status |
|
||||
|----|-------------|----------|-------|--------|
|
||||
| REQ-8-005 | Admin release & deployment guides: deploy/README.md expanded into the full admin runbook — three install channels (docker / deb / binary+install.sh) first-install recipes, per-channel upgrade paths (docker pull + recreate / deb reinstall via dpkg -i + deploy --service / install.sh re-run + deploy --service, all idempotent — D-071), HAProxy + systemd recipes preserved, troubleshooting tables extended (runner, registry, docker degrade, deb), every recipe backed by a test or verified live-box evidence (house rule) | critical | 5 | complete |
|
||||
|
||||
## v0.7 Requirements (Complete — Test Harness Review, NFR; shipped as v0.6.6)
|
||||
|
||||
**Milestone type: NFR — refinement-only (D-001 purity gate: zero `feat:` commits).** Review the entire test harness: make sure the right tests are being run, make them effective, cut tests that provide no real value, eliminate all warnings, and address the findings within this single milestone. Founder scope decisions locked 2026-09-26: ESLint included (D-048), recharts 2→3 included (D-049), source-pin triage cut-trivial-keep-real (D-050), mypy included (D-051).
|
||||
|
||||
### Harness Wiring
|
||||
|
||||
| ID | Description | Priority | Phase | Status |
|
||||
|----|-------------|----------|-------|--------|
|
||||
| REQ-7-001 | Test harness infrastructure: coverage measurement wired (pytest-cov for ai-service, c8 around the existing `tsx --test` for web/cli — D-052), pytest-timeout safety net (`signal` method, 60s global / 180s for `real_server`+`userns` via conftest collection hook — D-054; CLI fresh-clone E2E keeps its real 600s bootstrap, env-gated out of the default `cli:test` into a `cli:test:e2e` script with a 900s budget — D-055), markers `fast`/`real_server`/`userns` registered under `--strict-markers` with fast subset = `-m "not real_server and not userns"` (`ai:test:fast` script; unmarked tests default to fast — D-053), web tests inside the turbo pipeline (`web#test` task — package name is `web` + root `test`/`web:test` scripts), silent-skip fixes (path-invocation reports skip; env/global leaks fixed — `AI_PROVIDER` env mutation restored, conftest exception swallow narrowed), stale PLAN.md test counts corrected | critical | 1 | complete |
|
||||
|
||||
### Suite Composition
|
||||
|
||||
| ID | Description | Priority | Phase | Status |
|
||||
|----|-------------|----------|-------|--------|
|
||||
| REQ-7-002 | Evidence-based suite composition: trivial/no-value tests cut per the D-057 rule (keep a source pin only if it encodes a documented regression lesson or cross-boundary wiring invisible to typecheck/build/behavioral tests — e.g. E87, runtime fetch wiring, gate composition; cut pins that merely assert the code says what it says; kept pins named after their regression), duplicated harness infrastructure consolidated (KillableProxy ×2, `_free_port` ×4, userns probe ×4, real-uvicorn serve boilerplate ×5, wirePosting ×2 → `tests/helpers/` package — D-060; fixtures stay in conftest), flake strategy replaces timeout-widening with deterministic waits where possible, leaked sandbox-droppings cleanup + `tests/sandboxes/` anchoring fixed | critical | 2 | complete |
|
||||
|
||||
### Warning Elimination
|
||||
|
||||
| ID | Description | Priority | Phase | Status |
|
||||
|----|-------------|----------|-------|--------|
|
||||
| REQ-7-003 | Zero-warning pytest runs: `session.query()` → `session.exec()` at all 14 sites (marketplace/store.py ×12, identity/store.py ×2), resource cleanup for the 14 ResourceWarning sites (UploadFile close ×10 in api/defense.py + api/marketplace.py, socket close ×3 in scripts/sandbox-agent.py, file handle in tests/grading/test_engine.py), pytest `filterwarnings` policy (base action `error`; narrow module+message-scoped upstream ignores for the fastapi/starlette TestClient httpx warning and anyio BlockingPortal — no blanket category ignores, nothing ignored for `ai_service.*` — D-056), `fixture_loop_scope` pinned, dead `if False` branch removed | critical | 3 | complete |
|
||||
|
||||
### Lint & Suppression Hygiene
|
||||
|
||||
| ID | Description | Priority | Phase | Status |
|
||||
|----|-------------|----------|-------|--------|
|
||||
| REQ-7-004 | Lint toolchain completion: ESLint flat config (typescript-eslint + react-hooks) for all JS/TS workspaces wired into `turbo lint` (currently a no-op for 5 of 6 packages, D-048), all 81 inert Python `# noqa` reconciled via RUF100 (dead ones removed), the 5 orphaned eslint-disable comments resolved under the real config, dead exports removed (ai-scenarios.ts, NavItem/ThemeConfig, Spawn, MicControl), stale version comments + `FastAPI(version="0.3.0")` drift fixed (pyproject.toml as single version source bumped to the shipped line; FastAPI version read from package metadata — D-061), `engines` fields added to package.jsons | high | 4 | complete |
|
||||
|
||||
### Type & Dependency Hardening
|
||||
|
||||
| ID | Description | Priority | Phase | Status |
|
||||
|----|-------------|----------|-------|--------|
|
||||
| REQ-7-005 | Static typing for ai-service (D-051): mypy wired with `ai:typecheck` script + turbo task at a relaxed-first baseline (D-058: `check_untyped_defs`, `warn_unused_ignores`, `no_implicit_optional`, `warn_redundant_casts`, `warn_unreachable` — not full strict; per-module overrides available later), all 27 `# type: ignore` comments made meaningful or removed; recharts 2→3 upgrade (D-049) with chart-surface verification = `tsc --noEmit` + static-export `next build` + existing web tests green, live mount probe as the operational smoke (D-059 — no browser/render harness, out of scope); deprecated transitive deps resolved where toolchain allows | high | 5 | complete |
|
||||
|
||||
## v0.6 Requirements (Complete — Marketplace Engine; shipped as v0.5.6)
|
||||
|
||||
### Job Aggregation & Postings
|
||||
|
||||
| ID | Description | Priority | Phase | Status |
|
||||
|----|-------------|----------|-------|--------|
|
||||
| REQ-6-001 | Job posting backend (from REQ-F-011, pilot-scaled): postings store (6th D-027 store family — SQLite, insert-safe, protocol-wrapped), employer posting lifecycle (draft → published → closed), ingestion adapter contract (employer-authored postings + seeded corpus at pilot scale; 3M+ external aggregation preserved by the adapter interface), marketplace API routes replacing the mock-data reads on job board/detail/employer surfaces, 18+ verified identity gate on apply/post flows (D-043 composition retained) | critical | 1 | pending |
|
||||
| REQ-6-002 | AI-powered tagging (from REQ-F-012): skills/seniority/category extraction from posting text via the LLM structured-output layer (D-020) — deterministic mock-first, provider-agnostic; tags persisted with the posting; tag facets drive the search filter sidebar | high | 2 | pending |
|
||||
| REQ-6-001 | Job posting backend (from REQ-F-011, pilot-scaled): postings store (6th D-027 store family — SQLite, insert-safe, protocol-wrapped), employer posting lifecycle (draft → published → closed), ingestion adapter contract (employer-authored postings + seeded corpus at pilot scale; 3M+ external aggregation preserved by the adapter interface), marketplace API routes replacing the mock-data reads on job board/detail/employer surfaces, 18+ verified identity gate on apply/post flows (D-043 composition retained) | critical | 1 | complete |
|
||||
| REQ-6-002 | AI-powered tagging (from REQ-F-012): skills/seniority/category extraction from posting text via the LLM structured-output layer (D-020) — deterministic mock-first, provider-agnostic; tags persisted with the posting; tag facets drive the search filter sidebar | high | 2 | complete |
|
||||
|
||||
### Search & Matching
|
||||
|
||||
| ID | Description | Priority | Phase | Status |
|
||||
|----|-------------|----------|-------|--------|
|
||||
| REQ-6-003 | Semantic vector search (from REQ-F-013): embedding provider protocol (mock-first, deterministic; real provider env-configured per D-014), vector store at pilot scale (SQLite-local — no pgvector before the Postgres migration), candidate-competency ↔ posting-requirement similarity ranking, match-score surfacing on job cards + candidate matches (replaces mock match scores) | critical | 3 | pending |
|
||||
| REQ-6-003 | Semantic vector search (from REQ-F-013): embedding provider protocol (mock-first, deterministic; real provider env-configured per D-014), vector store at pilot scale (SQLite-local — no pgvector before the Postgres migration), candidate-competency ↔ posting-requirement similarity ranking, match-score surfacing on job cards + candidate matches (replaces mock match scores) | critical | 3 | complete |
|
||||
|
||||
### Enrichment & Parsing
|
||||
|
||||
| ID | Description | Priority | Phase | Status |
|
||||
|----|-------------|----------|-------|--------|
|
||||
| REQ-6-004 | Company enrichment (from REQ-F-014): employer profile enrichment from posting/company data (descriptions, social links, logo refs) via LLM structured output; enrich-on-post with manual founder override path; enriched data stored separately from raw (provenance marked) | medium | 4 | pending |
|
||||
| REQ-6-005 | Resume/profile parsing (from REQ-F-015): learner profile auto-fill from an uploaded resume — LLM structured extraction mapping to the competency-profile shape, learner-review-before-save (never silently overwrite), upload bounded (size/format guard, house pattern) | medium | 4 | pending |
|
||||
| REQ-6-004 | Company enrichment (from REQ-F-014): employer profile enrichment from posting/company data (descriptions, social links, logo refs) via LLM structured output; enrich-on-post with manual founder override path; enriched data stored separately from raw (provenance marked) | medium | 4 | complete |
|
||||
| REQ-6-005 | Resume/profile parsing (from REQ-F-015): learner profile auto-fill from an uploaded resume — LLM structured extraction mapping to the competency-profile shape, learner-review-before-save (never silently overwrite), upload bounded (size/format guard, house pattern) | medium | 4 | complete |
|
||||
|
||||
### SEO & Programmatic Pages
|
||||
|
||||
| ID | Description | Priority | Phase | Status |
|
||||
|----|-------------|----------|-------|--------|
|
||||
| REQ-6-006 | SEO-optimized programmatic pages (from REQ-F-016): server-rendered job/stack/landing pages with metadata (title/description/OG), sitemap.xml + robots.txt, JSON-LD structured data (JobPosting schema), static-export compatible (D-039 single-port deploy unchanged) | high | 5 | pending |
|
||||
| REQ-6-006 | SEO-optimized programmatic pages (from REQ-F-016): server-rendered job/stack/landing pages with metadata (title/description/OG), sitemap.xml + robots.txt, JSON-LD structured data (JobPosting schema), static-export compatible (D-039 single-port deploy unchanged) | high | 5 | complete |
|
||||
|
||||
## v0.5 Requirements (Complete — Real Server Voice, KYC/Identity, Sandbox Environments, Seq-Lease; shipped as v0.4.5)
|
||||
|
||||
@@ -222,9 +396,9 @@
|
||||
| ID | Description | Priority | Milestone | Status |
|
||||
|----|-------------|----------|-----------|--------|
|
||||
| REQ-F-017 | Identity verification and age-gating (16+/18+) — real KYC backend | high | v0.5 | activated → complete (REQ-5-003/004) |
|
||||
| REQ-F-018 | Payment processing and subscription management | high | v0.3+ | deferred |
|
||||
| REQ-F-018 | Payment processing and subscription management | high | v0.9 | activated → REQ-9-001..005 |
|
||||
| REQ-F-019 | Human tutor marketplace (third-party courses) | medium | v0.4+ | deferred |
|
||||
| REQ-F-020 | CIRR-style placement tracking and audit | medium | v0.5+ | deferred |
|
||||
| REQ-F-020 | CIRR-style placement tracking and audit | medium | v0.5+ | activated → REQ-11-001..005 |
|
||||
|
||||
---
|
||||
|
||||
@@ -244,16 +418,26 @@
|
||||
|
||||
## Traceability Matrix
|
||||
|
||||
### v0.6 (active)
|
||||
### v0.11 (complete)
|
||||
|
||||
| Requirement | Phase | Status |
|
||||
|-------------|-------|--------|
|
||||
| REQ-6-001 | 1 | pending |
|
||||
| REQ-6-002 | 2 | pending |
|
||||
| REQ-6-003 | 3 | pending |
|
||||
| REQ-6-004 | 4 | pending |
|
||||
| REQ-6-005 | 4 | pending |
|
||||
| REQ-6-006 | 5 | pending |
|
||||
| REQ-11-001 | 1 | complete |
|
||||
| REQ-11-002 | 2 | complete |
|
||||
| REQ-11-003 | 3 | complete |
|
||||
| REQ-11-004 | 4 | complete |
|
||||
| REQ-11-005 | 5 | complete |
|
||||
|
||||
### v0.6 (complete)
|
||||
|
||||
| Requirement | Phase | Status |
|
||||
|-------------|-------|--------|
|
||||
| REQ-6-001 | 1 | complete |
|
||||
| REQ-6-002 | 2 | complete |
|
||||
| REQ-6-003 | 3 | complete |
|
||||
| REQ-6-004 | 4 | complete |
|
||||
| REQ-6-005 | 4 | complete |
|
||||
| REQ-6-006 | 5 | complete |
|
||||
|
||||
### v0.5 (complete)
|
||||
|
||||
@@ -338,4 +522,4 @@
|
||||
| REQ-025 | 5 | complete |
|
||||
| REQ-026 | 6 | complete |
|
||||
| REQ-027 | 6 | complete |
|
||||
| REQ-028 | 6 | complete |
|
||||
| REQ-028 | 6 | complete |
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
+95
-9
@@ -2,7 +2,13 @@
|
||||
|
||||
## Overview
|
||||
|
||||
**Milestone v0.6 — Marketplace Engine (ACTIVE, started 2026-09-21).** The real marketplace backend behind the existing surfaces: job posting backend + aggregation adapter (REQ-6-001), AI tagging (REQ-6-002), semantic vector search + match scoring (REQ-6-003), company enrichment + resume parsing (REQ-6-004/005), SEO programmatic pages (REQ-6-006). Scope decision D-047 (auto-decided at SPECIFY, full autonomy). Tags on the v0.5.x line (v0.5.0 phase 0 → v0.5.N final = milestone release); branch `milestone/v0.6-marketplace-engine`.
|
||||
**Milestone v0.11 — COMPLETE (shipped as v0.10.6, 2026-10-22).** Feature milestone: CIRR-style placement tracking and audit (REQ-F-020 activated per D-098) — the machinery that makes the guiding outcome (≥1,000 placements, CIRR-style third-party audit) measurable: the placement store + hash-chained evidence ledger, the employer-side application state machine (submitted → in_review → interview → offer → hired/rejected/withdrawn), placement reporting surfaces (per-employer, per-learner, aggregate toward ≥1,000), the audit-grade export (cohort snapshot + evidence bundles + methodology + chain head), learner-side placement visibility. Tags on the v0.10.x line (P0 → v0.10.0 … P6 → v0.10.6 = milestone release); branch `milestone/v0.11-placement-tracking`.
|
||||
|
||||
**Milestone v0.10 — B2B Employer Network (COMPLETE, shipped as v0.9.6, 2026-10-01).** Feature milestone: real employer auth/accounts + self-serve (D-085). Employers become principals — registered accounts with sessions, employer-entity claim/verify, the employer dashboard converting from the v0.1 mockup to real data, self-serve posting management with the v0.9 entitlement enforcement intact, and self-serve checkout over the v0.9 billing catalog (superseding D-076 operator mediation; admin operator routes retained as fallback + oversight). Tags on the v0.9.x line (P0 → v0.9.0 … P6 → v0.9.6 = milestone release); branch `milestone/v0.10-b2b-employer-network`.
|
||||
|
||||
**Milestone v0.9 — Payment Engine (COMPLETE, shipped as v0.8.6, 2026-09-30).** Payment processing and subscription management (REQ-F-018 activated per D-074): the billing module (provider protocol mock+stripe, 7th D-027 store, HMAC webhooks), catalog + pricing surface, operator-mediated checkout, entitlement enforcement, full subscription lifecycle. Founder scope decision D-074; clarify D-075..D-084; grill G-301+. Tags on the v0.8.x line (v0.8.0 phase 0 → v0.8.6 final = milestone release); branch `milestone/v0.9-payment-engine`.
|
||||
|
||||
**Milestone v0.6 — Marketplace Engine (COMPLETE, shipped as v0.5.6, 2026-09-26).** The real marketplace backend behind the existing surfaces: job posting backend + aggregation adapter (REQ-6-001), AI tagging (REQ-6-002), semantic vector search + match scoring (REQ-6-003), company enrichment + resume parsing (REQ-6-004/005), SEO programmatic pages (REQ-6-006). Scope decision D-047 (auto-decided at SPECIFY, full autonomy). Tags on the v0.5.x line (v0.5.0 phase 0 → v0.5.N final = milestone release); branch `milestone/v0.6-marketplace-engine`.
|
||||
|
||||
**Hotfix v0.4.7 (2026-09-21) — pre-public hardening.** The 4 P1 flags from the v0.5 final review closed: HMAC ingest tokens on the WS grading input (LAN poisoning closed), nonce+counter defense-id mint (same-ms collision closed), browser-mode client SR/TTS per the descriptor contract (gap closed), 8 browser-voice module pins. Deployed via `nextcraft deploy --service`; site 200, service enabled.
|
||||
|
||||
@@ -26,19 +32,95 @@
|
||||
|
||||
---
|
||||
|
||||
## v0.9 (Complete — Shipped as v0.8.6, 2026-09-30)
|
||||
|
||||
Payment processing and subscription management (REQ-F-018 activated per D-074, auto-decided at SPECIFY under full autonomy): posting packages (single/bundle/enterprise), talent-access plans, subscription tiers with real checkout, provider webhooks (HMAC-verified, idempotent), posting-creation entitlement enforcement, and a full subscription lifecycle (renew/cancel/upgrade/past_due grace) — all behind a provider-agnostic `PaymentProvider` protocol, mock-first (D-014 pattern; tests never call Stripe). The pricing page (REQ-017) gains its real backend. Out of scope: employer auth/accounts (B2B network — post-payments per A-407), multi-currency, tax/VAT beyond passthrough, invoice PDFs, CIRR tracking (REQ-F-020). Tags on the v0.8.x line (P0 → v0.8.0 … P6 → v0.8.6 = milestone release); branch `milestone/v0.9-payment-engine`.
|
||||
|
||||
## Phase List
|
||||
|
||||
### v0.6 (active)
|
||||
### v0.11 (complete — shipped as v0.10.6, 2026-10-22)
|
||||
|
||||
| # | Name | Status | Depends On | Requirements | Success Criteria |
|
||||
|---|------|--------|------------|--------------|------------------|
|
||||
| 0 | Pre-execution | complete (v0.10.0) | — | — | Specify (D-098), clarify, research, plan, grill, MVP/UX check complete (shipped as v0.10.0) |
|
||||
| 1 | Placement store + evidence ledger | complete (v0.10.1) | 0 | REQ-11-001 | `ai_service/placements/` module: 9th D-027 store (PlacementRow + PlacementEventRow, hash-chained append-only ledger), evidence resolved from source rows only (G-302 doctrine), `create_all` idempotent on the shared DB file, Protocol + SQLite pair |
|
||||
| 2 | Application state machine | complete (v0.10.2) | 1 | REQ-11-002 | Employer routes extend the v0.6 application status from submitted-only to the full hiring lifecycle; claimed-entity authorization (403 cross-entity, G-311 gate order); every transition ledger-logged; hired creates the placement; admin oversight retained |
|
||||
| 3 | Placement reporting | complete (v0.10.3) | 2 | REQ-11-003 | Aggregate counts from the ledger (per employer, per cohort month, cumulative toward ≥1,000); employer dashboard placements section; learner outcome states; admin network overview counts |
|
||||
| 4 | Audit export | complete (v0.10.4) | 3 | REQ-11-004 | Admin-gated export: cohort snapshot + per-placement evidence bundles + methodology doc + chain head hash; JSON + human-readable summary; re-export reproducibility test |
|
||||
| 5 | Learner placement visibility | complete (v0.10.5) | 4 | REQ-11-005 | Learner application outcomes + full state history; hired learners see their placement record; honest no-badge-until-placed (A-304) |
|
||||
| 6 | Final review + ship | complete (v0.10.6) | 1-5 | — | Review SHIP — 0 P0s, 2 P1 doc-level findings dispositioned with recorded follow-ups (the PLAN Must-Have test_e2e_audit.py name vs test_export.py::test_e2e_audit_proof; the D-112 census omitting the employers/store.py two-line audit-vocabulary addition); audit PASS — D-112 reconstruction clean (27 branch commits vs the census), branch/commit discipline green; ship: v0.10.5 tagged at the ship per the recorded deferral (e32e54e7aa), milestone merged to main (PR #6), v0.10.6 tagged at the merge, release lanes fired, milestone branch deleted |
|
||||
|
||||
---
|
||||
|
||||
## Phase List (v0.10 — complete)
|
||||
|
||||
| # | Name | Status | Depends On | Requirements | Success Criteria |
|
||||
|---|------|--------|------------|--------------|------------------|
|
||||
| 0 | Pre-execution | complete (v0.9.0) | — | — | Specify (D-085), clarify (D-086..D-097), research (R-55..R-66), plan, grill (G-311..G-320), MVP/UX check complete (shipped as v0.9.0, release 948) |
|
||||
| 1 | Employer auth foundation | complete (v0.9.1) | 0 | REQ-10-001 | `ai_service/employers/` module: account store (8th D-027 family, 4 tables) + scrypt hashed credentials (params pinned) + hashed server-side sessions (7-day lazy TTL) + register/login/logout/me routes + dual D-088 auth throttles + CORS Authorization preflight + PII scrub; fail-closed secrets; tests never call a cloud (shipped as v0.9.1, release 949) |
|
||||
| 2 | Employer entity claim | complete (v0.9.2) | 1 | REQ-10-002 | Claim route over existing EmployerRow entities with stdlib-only claim_evidence normalization (advisory-only per D-089/A-304); G-316 partial UNIQUE index closes the pending-claim TOCTOU; one account : one entity bound at approve with same-transaction audit provenance; admin claim review/approve/reject — 5 operator routes fail-closed, 403 matrix 20 probes; rejection frees entities; claimed-entity authorization enforced (shipped as v0.9.2, release 950) |
|
||||
| 3 | Employer account surface | complete (v0.9.3) | 2 | REQ-10-003 | Employer dashboard real-data conversion (mock imports → runtime fetches, A-406 pattern); login/register UI; session-gated shell; own-postings view; dual-schema wire pins (shipped as v0.9.3, release 951) |
|
||||
| 4 | Self-serve posting management | complete (v0.9.4) | 3 | REQ-10-004 | Employer-principal posting routes with own-entity authorization; D-091 shared entitlement gate (one helper, byte-identical principal gates); create/edit/publish/close on the claimed entity with G-311 gate order, G-317 provenance stamps, G-318 own-drafts guard + admin re-tag parity; PostingManager honest 402 CTA / 403 claim states per G-320b; admin routes retained (shipped as v0.9.4, release 952) |
|
||||
| 5 | Self-serve checkout + admin overview | complete (v0.9.5) | 4 | REQ-10-005 | Employer-principal checkout over the v0.9 catalog via the REAL webhook path with buyer = the session's claimed entity (supersedes D-076; admin operator routes retained as fallback); own-session mock-complete closes the G-301 class; own entitlement view with honest states; pricing CTAs → employer-login per D-079-supersession with enterprise Contact Sales pin retained; admin network overview — accounts, advisory-evidence claim queue, audit — per D-094/A-304 (shipped as v0.9.5, release 953) |
|
||||
| 6 | Final review + ship | complete (v0.9.6) | 1-5 | — | Final review verdict SHIP — 2 P0s found + fixed (the /me claim-state leak over stale sessions, the dead billing confirm button), 3 P1s dispositioned; audit PASS — reconstruction clean, discipline green, 2 minor notes; ship gates green (1031 ai-service + 101 web tests, build clean); milestone tagged v0.9.6 (final v0.9.x patch = milestone release, release 954); release with full asset matrix + registry image via the tag lane (D-064); milestone merged to main |
|
||||
|
||||
---
|
||||
|
||||
## Phase List (v0.9 — complete)
|
||||
|
||||
| # | Name | Status | Depends On | Requirements | Success Criteria |
|
||||
|---|------|--------|------------|--------------|------------------|
|
||||
| 0 | Pre-execution | complete (v0.8.0) | — | — | Specify (D-074), clarify (D-075+), research (R-33+), plan, grill (G-301+), MVP/UX check complete; shipped as v0.8.0 |
|
||||
| 1 | Billing foundation | complete (v0.8.1) | 0 | REQ-9-001 | `ai_service/billing/` module: PaymentProvider protocol + deterministic mock + SQLite store (7th D-027 family) + HMAC webhook verification + env-gated provider selection; tests never call a real provider |
|
||||
| 2 | Catalog + pricing surface | complete (v0.8.2) | 1 | REQ-9-002 | Seeded catalog (posting packages + talent-access plans) via `/v1/billing/catalog`; pricing page runtime client fetch with honest loading/error states; tier copy data-driven |
|
||||
| 3 | Checkout + webhook flow | complete (v0.8.3) | 2 | REQ-9-003 | `POST /v1/billing/admin/checkout` (admin-gated, D-076) + `POST /v1/billing/webhook` (HMAC-verified, idempotent event processing, at-least-once tolerance, local-row state resolution per G-302); entitlement granted on checkout.completed |
|
||||
| 4 | Entitlement enforcement | complete (v0.8.4) | 3 | REQ-9-004 | Posting creation enforces package limits (honest 402 + upgrade CTA); expired/cancelled degrade to 402; admin surface shows per-employer entitlement state |
|
||||
| 5 | Subscription lifecycle | complete (v0.8.5) | 4 | REQ-9-005 | Subscription state machine (trialing/active/past_due/cancelled/expired); idempotent renewals; manual admin grant/revoke with provenance; full billing event audit log; past_due grace window |
|
||||
| 6 | Final review + ship | complete (v0.8.6) | 1-5 | — | Review clean; audit pass; milestone tagged v0.8.6 (final v0.8.x patch = milestone release); release with full asset matrix + registry image; milestone merged to main |
|
||||
|
||||
---
|
||||
|
||||
## v0.8 (Complete — Shipped as v0.7.6)
|
||||
|
||||
Ship Anywhere: installable on any Debian-based Linux server via docker (Gitea registry image, honest sandbox degrade per D-068), .deb packages (amd64+arm64, advisory postinst per D-067), and arch-aware binary (x64+arm64, R-24 arch-resolve) — with release consistency enforced by pre-commit hooks + Gitea Actions (3-runner fleet on CT 113 as committed fleet-as-code, machine-made releases with the 8-asset matrix + registry image on every release), the CLI carrying the full suite (guide + channel-aware doctor, D-066/D-072), and the evidence-backed admin runbook (G-210 parity-pinned). 7 phases (P0–P6), all 5 requirements (REQ-8-001..005) complete. Tags v0.7.0–v0.7.5 per phase, milestone release v0.7.6 (release 936). Final review CLEAN (G-201..G-210 honored — the smoke gate caught 4 real image bugs pre-ship, each fixed in-phase); audit PASS (reconstruction + discipline green).
|
||||
|
||||
## Phase List
|
||||
|
||||
### v0.8 (complete)
|
||||
|
||||
| # | Name | Status | Depends On | Requirements | Success Criteria |
|
||||
|---|------|--------|------------|--------------|------------------|
|
||||
| 0 | Pre-execution | complete (v0.7.0) | — | — | Specification, clarify (D-063..D-072), research (R-1..R-32), plan (rails→artifacts→onboarding→guides), grill (G-201..G-210), MVP/UX check complete (shipped as v0.7.0, release 913) |
|
||||
| 1 | Release-consistency rails | complete (v0.7.1) | 0 | REQ-8-001 | 3 org-level runners green on CT 113 (hybrid labels, sibling mode); ci.yaml push lanes green; hello-world × 3 labels; release.yaml builds assets on tag (v0.7.1 release machine-made); pre-commit both-direction proof; secrets audit clean |
|
||||
| 2 | Docker image channel | complete (v0.7.2) | 1 | REQ-8-002 | Multi-stage image (unprivileged, /health, state volume) pushed to the Gitea registry on every phase release; honest sandbox degrade (probe + notice + 503 remediation); in-container CLI semantics; smoke gate in workflow |
|
||||
| 3 | Debian-native channel | complete (v0.7.3) | 2 | REQ-8-003 | arm64 QEMU-free cross-build; .deb x64+arm64 (advisory postinst); install.sh arch-resolve; full asset matrix (2 binaries + 2 checksums + 2 debs) on every release |
|
||||
| 4 | CLI onboarding | complete (v0.7.4) | 3 | REQ-8-004 | Channel-aware doctor; nextcraft guide offline; honest in-container refusals; docker/deb E2Es env-gated green; guide↔runbook parity test |
|
||||
| 5 | Admin guides | complete (v0.7.5) | 4 | REQ-8-005 | deploy/README.md full runbook (3 channels × install/upgrade, upgrade matrix, troubleshooting, evidence appendix); README quickstart; every recipe evidence-backed |
|
||||
| 6 | Final review + ship | complete (v0.7.6) | 1-5 | — | Review clean; audit pass; milestone tagged v0.7.6 (final v0.7.x patch = milestone release, release 936); release with full asset matrix + registry image; milestone merged to main | Review clean; audit pass; milestone tagged v0.7.6 (final v0.7.x patch = milestone release); release with full asset matrix + image tags; milestone merged to main |
|
||||
|
||||
### v0.7 (complete)
|
||||
|
||||
| # | Name | Status | Depends On | Requirements | Success Criteria |
|
||||
|---|------|--------|------------|--------------|------------------|
|
||||
| 0 | Pre-execution | complete | — | — | Specify, clarify (D-052..D-061), research (44-50), plan (D-062 waves), grill (G-101..G-110), MVP/UX check complete (shipped as v0.6.0) |
|
||||
| 1 | Harness wiring | complete (v0.6.1) | 0 | REQ-7-001 | Coverage in all 3 workspaces; timeouts 60s/180s probe-proven; markers fast/real_server/userns strict; web tests in turbo; leaks fixed; fast subset <60s |
|
||||
| 2 | Suite composition | complete (v0.6.2) | 1 | REQ-7-002 | 10 trivial tests cut with recorded per-assertion triage; 8 cross-boundary pins kept (CWD-independent); tests/helpers/ consolidation zero-behavior-change; droppings swept |
|
||||
| 3 | Warning elimination | complete (v0.6.3) | 2 | REQ-7-003 | session.exec ×14; ResourceWarning sites closed at source; filterwarnings=error + 2 scoped ignores; full suite ZERO warnings |
|
||||
| 4 | Lint & suppression hygiene | complete (v0.6.4) | 3 | REQ-7-004 | ESLint 6/6 workspaces; 20 violations fixed; 80 noqa removed (6 live fixed at source); dead exports gone; version single-source; engines |
|
||||
| 5 | Type & dependency hardening | complete (v0.6.5) | 4 | REQ-7-005 | mypy relaxed-first green (178 files, 27 ignores dispositioned); recharts 3.10.1 proven; transitive audit recorded |
|
||||
| 6 | Final review + ship | complete (v0.6.6) | 1-5 | — | Purity gate zero feat:; review SHIP verdict; audit PASS; milestone tagged v0.6.6; release with binary assets; milestone merged to main |
|
||||
|
||||
### v0.6 (complete)
|
||||
|
||||
| # | Name | Status | Depends On | Requirements | Success Criteria |
|
||||
|---|------|--------|------------|--------------|------------------|
|
||||
| 0 | Pre-execution | complete | — | — | Specification, clarify, research, plan, grill, MVP/UX check complete; .ciagent/ files updated for v0.6 (shipped as v0.5.0) |
|
||||
| 1 | Postings backend + aggregation adapter | complete (v0.5.1) | 0 | REQ-6-001 | Postings store + lifecycle + `/v1/marketplace/*` routes live; job board/detail/employer surfaces read real data; 18+ gates composed per D-043; seeded ingestion adapter proven |
|
||||
| 2 | AI tagging | complete (v0.5.2) | 1 | REQ-6-002 | Posting text → skills/seniority/category tags via LLM structured output (mock-first); tag facets drive search filters; tags persisted |
|
||||
| 3 | Semantic vector search | in-progress | 2 | REQ-6-003 | Embedding provider protocol (mock-first) + SQLite-local vectors; competency↔posting similarity ranking; match scores surface on job cards + candidate matches |
|
||||
| 4 | Enrichment + resume parsing | pending | 3 | REQ-6-004, REQ-6-005 | Employer enrichment from posting data with provenance; resume upload → profile auto-fill with learner review gate; bounded uploads |
|
||||
| 5 | SEO programmatic pages | pending | 4 | REQ-6-006 | Metadata + JSON-LD + sitemap/robots on job/stack/landing pages; static-export compatible (single-port deploy unchanged) |
|
||||
| 6 | Final review + ship | pending | 1-5 | — | Review clean; audit passes; milestone tagged (final v0.5.x patch); release with binary assets on Gitea; milestone merged to main |
|
||||
| 3 | Semantic vector search | complete (v0.5.3) | 2 | REQ-6-003 | Embedding provider protocol (mock-first) + SQLite-local vectors; competency↔posting similarity ranking; match scores surface on job cards + candidate matches |
|
||||
| 4 | Enrichment + resume parsing | complete (v0.5.4) | 3 | REQ-6-004, REQ-6-005 | Employer enrichment from posting data with provenance; resume upload → profile auto-fill with learner review gate; bounded uploads |
|
||||
| 5 | SEO programmatic pages | complete (v0.5.5) | 4 | REQ-6-006 | Metadata + JSON-LD + sitemap/robots on job/stack/landing pages; static-export compatible (single-port deploy unchanged) |
|
||||
| 6 | Final review + ship | complete (v0.5.6) | 1-5 | — | Review clean; audit passes; milestone tagged (final v0.5.x patch); release with binary assets on Gitea; milestone merged to main |
|
||||
|
||||
---
|
||||
|
||||
@@ -126,9 +208,13 @@
|
||||
| v0.4.7 | 2026-09-21 | Pre-public hardening (the 4 P1 flags from the v0.5 final review): HMAC ingest tokens on the WS grading input (LAN trace-poisoning closed, per-boot secret, manager mints / endpoint verifies), nonce+counter defense-id mint (same-ms PK collision closed), browser-mode client SR/TTS implemented per the descriptor contract (the v0.5 gap), 8 browser-voice module pins. 488 backend (+10), web 22/22 (+8), CLI 61/61. Deployed via `nextcraft deploy --service`; site 200, service enabled. |
|
||||
| v0.4.6 | 2026-09-21 | Site-down hotfix + one-command deploy: `nextcraft deploy [--service]` (clone/update → install → venv → export build → restart → verify), systemd unit generation (reboot persistence), toolchain discovery (nvm/PNPM_HOME/corepack + split installs), loud mount-less boot, verify live mount probe, subcommand flag dispatch. Deployed live via the command itself; nextcraft.coreci.dev → 200 HTML. |
|
||||
|
||||
## v0.6 (Active — Marketplace Engine)
|
||||
## v0.7 (Complete — Shipped as v0.6.6)
|
||||
|
||||
Real backend behind the marketplace surfaces: postings store + aggregation adapter + marketplace API (REQ-6-001), AI tagging (REQ-6-002), embedding-backed semantic search + match scores (REQ-6-003), company enrichment + resume parsing (REQ-6-004/005), SEO programmatic pages (REQ-6-006). 7 phases (P0–P6). Scope D-047 (auto-decided at SPECIFY). Tags v0.5.0+ on the v0.5.x line; final patch = milestone release.
|
||||
Test Harness Review (NFR refinement-only, founder directive post-v0.6): coverage measured in all three workspaces (pytest-cov 95% branch, c8 web 95.9%/cli 76.9%); pytest-timeout safety net (60s/180s dual-tier, signal method, both probe-proven); markers fast/real_server/userns under --strict-markers with a 620-test fast subset completing in ~56s; web tests inside the turbo pipeline; CLI E2E env-gated. Suite composition: 10 trivial tests cut with per-assertion recorded triage (D-057), 8 cross-boundary/regression pins kept in CWD-independent pins.test.ts; duplicated harness infra consolidated into tests/helpers/ (KillableProxy split into two semantics-distinct helpers per G-101); deterministic waits replace sleeps where hooks exist; sandbox droppings swept + session-end fixtures. Warning elimination: 1,716 warnings/run → ZERO (14 session.query→session.exec sites, 14 ResourceWarning sites closed at source, filterwarnings=error with exactly 2 scoped upstream ignores). Lint hygiene: ESLint live in all 6 workspaces (was none), 20 violations fixed, 80 inert noqa removed (6 live ones fixed at source), RUF100 enforced, dead exports gone, version single-sourced 0.6.5, engines everywhere. Type & dependency hardening: mypy 2.3.1 relaxed-first green over 178 files (215 errors found: ~140 fixed at source incl. 8+ genuine bugs, 34 scoped suppressions; all 27 original ignores dispositioned); recharts 2.15.4→3.10.1 (deprecated direct dep resolved); transitive audit recorded (4 dev-only remain, none actionable). 7 phases (P0-P6). All 5 requirements (REQ-7-001..005) complete. Tags v0.6.0-v0.6.5 per phase, milestone release v0.6.6.
|
||||
|
||||
## v0.6 (Complete — Shipped as v0.5.6)
|
||||
|
||||
Real backend behind the marketplace surfaces: postings store + aggregation adapter + marketplace API (REQ-6-001), AI tagging (REQ-6-002), embedding-backed semantic search + match scores (REQ-6-003), company enrichment + resume parsing (REQ-6-004/005), SEO programmatic pages (REQ-6-006). 7 phases (P0–P6), all 6 requirements complete. Tags v0.5.0–v0.5.5 per phase, milestone release v0.5.6. Final review CLEAN (all G-101..G-110 honored, MH-M1..M6 met); audit PASS.
|
||||
|
||||
## v0.5 (Complete — Shipped as v0.4.5)
|
||||
|
||||
@@ -153,4 +239,4 @@ AI Tutor Architecture: Six AI tutor agents (Coach, Tutor, Lab, Assessor, Proctor
|
||||
|
||||
## v0.1 (Complete — Shipped as v0.1.0)
|
||||
|
||||
UI/UX Prototype: High-fidelity interactive prototype of all four Nextcraft surfaces. 7 phases (P0 + P1-P6 execution + P7 final). All 28 requirements complete. Tags v0.0.1–v0.0.7, milestone release v0.1.0.
|
||||
UI/UX Prototype: High-fidelity interactive prototype of all four Nextcraft surfaces. 7 phases (P0 + P1-P6 execution + P7 final). All 28 requirements complete. Tags v0.0.1–v0.0.7, milestone release v0.1.0.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"version": "0.7.0",
|
||||
"version": "0.8.0",
|
||||
"autonomy": {
|
||||
"level": "full",
|
||||
"decision_confidence_threshold": 0.6,
|
||||
@@ -46,9 +46,9 @@
|
||||
"projects": [],
|
||||
"active_project": null,
|
||||
"milestone": {
|
||||
"version": "v0.6",
|
||||
"name": "marketplace-engine",
|
||||
"version": "v0.11",
|
||||
"name": "placement-tracking",
|
||||
"type": "feature",
|
||||
"branch": "milestone/v0.6-marketplace-engine"
|
||||
"branch": "milestone/v0.11-placement-tracking"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
# Build context hygiene (v0.8 P2): secrets and runtime droppings never
|
||||
# enter an image layer. The .env* exclusion is the hard rule — the v1.8
|
||||
# class of leak (tokens) must be structurally impossible here.
|
||||
.git
|
||||
.gitignore
|
||||
.dockerignore
|
||||
.env
|
||||
.env.*
|
||||
**/.env
|
||||
**/.env.*
|
||||
!.env.example
|
||||
.ciagent
|
||||
**/.ciagent
|
||||
**/.venv
|
||||
**/node_modules
|
||||
**/__pycache__
|
||||
**/*.pyc
|
||||
**/.pytest_cache
|
||||
**/.mypy_cache
|
||||
**/.ruff_cache
|
||||
**/.turbo
|
||||
**/coverage
|
||||
**/dist
|
||||
apps/web/out
|
||||
apps/web/.next
|
||||
**/*.tsbuildinfo
|
||||
.turbo
|
||||
node_modules
|
||||
*.log
|
||||
@@ -0,0 +1,130 @@
|
||||
# Push lanes — every branch, every push (REQ-8-001, D-063).
|
||||
#
|
||||
# Two jobs, two runner labels, NEVER wholesale `turbo lint`/`turbo typecheck`
|
||||
# in the node lane (RESEARCH R-8): those turbo tasks pull in
|
||||
# @nextcraft/ai-service#lint/typecheck, which hard-fail without the Python
|
||||
# venv (apps/ai-service/scripts/lint.sh:8, typecheck.sh:13) — a venv that
|
||||
# does not exist in the node:24-bookworm job container. The node lane runs
|
||||
# lint/typecheck via `pnpm --filter` over the 5 TS workspaces only; the
|
||||
# python lane invokes the three ai-service bash scripts directly (no pnpm
|
||||
# needed in that container at all).
|
||||
#
|
||||
# Concurrency: serialize per-ref so a rapid-fire branch push reuses one lane
|
||||
# instead of stacking jobs on the capacity-1 runners (R-4).
|
||||
name: CI
|
||||
|
||||
on: push
|
||||
|
||||
concurrency:
|
||||
group: ci-${{ gitea.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
node:
|
||||
# Fleet label `node` -> container docker.io/library/node:24-bookworm
|
||||
# (deploy/ci/docker-compose.yaml, R-3 label map).
|
||||
runs-on: node
|
||||
steps:
|
||||
# actions/checkout@v4 downloads from github.com (DEFAULT_ACTIONS_URL
|
||||
# default). github.com egress is verified reachable from the LAN;
|
||||
# the CT-local probe is still pending (Wave 1-1 blocked on founder
|
||||
# deploy-key install). If checkout fails at the first real run, the
|
||||
# fallback is raw git fetch steps using the automatic job token:
|
||||
# - run: |
|
||||
# git init -q .
|
||||
# git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git"
|
||||
# git fetch --depth=1 origin "$GITHUB_SHA"
|
||||
# git checkout FETCH_HEAD
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
# Optional pnpm store cache (R-12). Depends on the runner cache server
|
||||
# being reachable from job containers (R-5: cache.host = CT IP + a
|
||||
# published port — configured in deploy/ci/). If the cache server
|
||||
# ETIMEDOUTs on first real runs, drop this block (fallback: a
|
||||
# volume-mounted pnpm store per R-12, or no cache at all — install is
|
||||
# affordable on the LAN). continue-on-error keeps cache flakiness
|
||||
# from ever turning the lane red; repeated timeouts = delete.
|
||||
- name: Cache pnpm store
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.local/share/pnpm/store
|
||||
key: pnpm-${{ runner.os }}-${{ hashFiles('pnpm-lock.yaml') }}
|
||||
restore-keys: pnpm-${{ runner.os }}-
|
||||
continue-on-error: true
|
||||
|
||||
# pnpm 12.3.4 is pinned by root package.json `packageManager`.
|
||||
# node:24-bookworm still bundles corepack (24.x retains it, deprecated
|
||||
# — Node >= 25 dropped it; R-11). Fallback if corepack is absent:
|
||||
# npm i -g pnpm@12.3.4
|
||||
- name: Enable pnpm
|
||||
run: corepack enable pnpm
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
# Lint: per-workspace filters over the 5 TS workspaces ONLY — never
|
||||
# `turbo lint` (see header note).
|
||||
- name: Lint (TS workspaces)
|
||||
run: >-
|
||||
pnpm --filter web --filter @nextcraft/cli --filter @nextcraft/ui
|
||||
--filter @nextcraft/types --filter @nextcraft/mock-data lint
|
||||
|
||||
# Typecheck: same filter set, per-workspace tsc --noEmit.
|
||||
- name: Typecheck (TS workspaces)
|
||||
run: >-
|
||||
pnpm --filter web --filter @nextcraft/cli --filter @nextcraft/ui
|
||||
--filter @nextcraft/types --filter @nextcraft/mock-data typecheck
|
||||
|
||||
- name: Web tests (node:test via tsx)
|
||||
run: pnpm web:test
|
||||
|
||||
# CLI default test script (tsx --test tests/*.test.ts) excludes the
|
||||
# env-gated E2E (apps/cli/package.json `test:e2e`, CLI_E2E=1) — the
|
||||
# fresh-clone E2E stays out of job containers per D-063.
|
||||
- name: CLI tests (node:test via tsx, E2E env-gated out)
|
||||
run: pnpm cli:test
|
||||
|
||||
python:
|
||||
# Fleet label `python` -> container docker.io/library/python:3.11-bookworm
|
||||
# (R-3). The three scripts below are self-contained venv-relative bash
|
||||
# (R-9) — no pnpm, no node, no turbo in this lane.
|
||||
#
|
||||
# P1 CI finding: actions/checkout@v4 is a NODE-based action — it cannot
|
||||
# exec in the python:3.11-bookworm container (exit 127: "node" not in
|
||||
# $PATH). This lane checks out via raw git steps with the automatic job
|
||||
# token instead (the R-8 fallback path, promoted to primary here).
|
||||
runs-on: python
|
||||
steps:
|
||||
- name: Checkout (raw git — node actions cannot run in this container)
|
||||
run: |
|
||||
git init -q .
|
||||
git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git"
|
||||
git fetch --depth=1 origin "$GITHUB_SHA"
|
||||
git checkout FETCH_HEAD
|
||||
|
||||
# NOTE: no actions/cache here — it is a node-based action and this
|
||||
# container has no node (exit 127; same class as the checkout finding).
|
||||
# The venv rebuild is ~25s warm — acceptable without cache; pip's own
|
||||
# HTTP cache is cold but the LAN is fast. Revisit only if the lane
|
||||
# slows materially (volume-mounted store per R-12, or a pip download
|
||||
# cache directory via container options).
|
||||
|
||||
# bootstrap.sh is idempotent: creates .venv (with the --without-pip +
|
||||
# get-pip fallback for Debian-without-ensurepip) and pip-installs
|
||||
# the project with [dev] extras (ruff, mypy, pytest).
|
||||
- name: Bootstrap ai-service venv
|
||||
run: bash apps/ai-service/scripts/bootstrap.sh
|
||||
|
||||
- name: Lint (ruff)
|
||||
run: bash apps/ai-service/scripts/lint.sh
|
||||
|
||||
- name: Typecheck (mypy, D-058 baseline)
|
||||
run: bash apps/ai-service/scripts/typecheck.sh
|
||||
|
||||
# Fast pytest lane per D-063: -m "not real_server and not userns"
|
||||
# (scripts/test.sh FAST=1). real_server/userns tiers stay local-only
|
||||
# — job containers genuinely cannot run them (docker default seccomp
|
||||
# denies the nested `unshare --user` the backend needs; R-8).
|
||||
- name: Tests (fast lane)
|
||||
run: FAST=1 bash apps/ai-service/scripts/test.sh
|
||||
@@ -0,0 +1,28 @@
|
||||
# Fleet proof (REQ-8-001, MH-1c): workflow_dispatch one-step echo job per
|
||||
# fleet label. Dispatching this workflow proves all three runners
|
||||
# register, pull their job image, and execute a job. Observed green in the
|
||||
# Actions tab = the runner fleet is verified end-to-end.
|
||||
#
|
||||
# Labels (R-3 fleet map, deploy/ci/docker-compose.yaml):
|
||||
# node -> node:24-bookworm (nc-runner-node)
|
||||
# ubuntu-latest -> runner-images:ubuntu-latest (nc-runner-node, hybrid)
|
||||
# python -> python:3.11-bookworm (nc-runner-python)
|
||||
name: Hello fleet
|
||||
|
||||
on: workflow_dispatch
|
||||
|
||||
jobs:
|
||||
node:
|
||||
runs-on: node
|
||||
steps:
|
||||
- run: echo "hello from node"
|
||||
|
||||
python:
|
||||
runs-on: python
|
||||
steps:
|
||||
- run: echo "hello from python"
|
||||
|
||||
ubuntu-latest:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- run: echo "hello from ubuntu-latest"
|
||||
@@ -0,0 +1,377 @@
|
||||
# Release lane — tag push only (REQ-8-001, D-063, R-14/R-15).
|
||||
#
|
||||
# Fires on `v*` tag pushes. Builds the x64 SEA binary stamped with the tag,
|
||||
# generates the sha256 sidecar, and attaches both to the tag's Gitea
|
||||
# release via the REST API (the same mechanics as scripts/release-assets.sh
|
||||
# — that script stays untouched as the MANUAL fallback with its
|
||||
# .env-only token resolution, per D-064/R-14).
|
||||
#
|
||||
# Within-phase proof (G-203): at verify time push a temporary
|
||||
# `v0.7.1-rc1`-style tag to the phase-branch head, observe this workflow
|
||||
# build + attach green (release immediately deleted or pre-release), then
|
||||
# delete the tag. The phase ship tag remains the real artifact.
|
||||
#
|
||||
# Token precedence (R-13): the automatic job token (auto-provided as the
|
||||
# GITHUB_TOKEN env / `${{ github.token }}` / `${{ gitea.token }}`) HAS
|
||||
# releases scope and can create releases + attach assets, but it CANNOT
|
||||
# publish packages (upstream-confirmed). The repo secret GITEA_TOKEN (a
|
||||
# founder-set PAT), when present, WINS (lowest level wins). This workflow
|
||||
# uses `${{ secrets.GITEA_TOKEN }}` when set, else the automatic token.
|
||||
#
|
||||
# Extension points (P2/P3, G-202: this workflow is the shared rail):
|
||||
# [P2] after "Build binary": docker build + login + push to
|
||||
# git.coreci.dev/coreci/nextcraft:$TAG + :latest with
|
||||
# secrets.REGISTRY_TOKEN, plus the five-assertion smoke gate (G-204).
|
||||
# [P3] arm64 cross-build (G-201 ladder) + both .deb packages (R-22/R-23)
|
||||
# join the attach step below — full asset matrix per D-064.
|
||||
name: Release
|
||||
|
||||
on:
|
||||
push:
|
||||
tags: ['v*']
|
||||
|
||||
jobs:
|
||||
release:
|
||||
# Fleet label `release` -> container node:24-bookworm (R-3: node +
|
||||
# dpkg-deb + git + curl; the deb toolchain ships with bookworm).
|
||||
runs-on: release
|
||||
env:
|
||||
# Token precedence per R-13: repo secret GITEA_TOKEN (PAT) wins when
|
||||
# present; else the automatic job token (releases scope is enough for
|
||||
# release-id resolution + asset upload — R-14). Never echo this.
|
||||
RELEASE_TOKEN: ${{ secrets.GITEA_TOKEN || github.token }}
|
||||
steps:
|
||||
- name: Checkout tag
|
||||
uses: actions/checkout@v4
|
||||
|
||||
# P2: the release lane builds/pushes the docker image. The job
|
||||
# container (node:24-bookworm) has no docker CLI and no daemon — the
|
||||
# host daemon is bind-mounted into this job via the runner's
|
||||
# container.options (deploy/ci/config-runner-release.yaml, sibling
|
||||
# mode); only the CLI is missing. Bookworm main ships docker.io
|
||||
# (engine+cli — the engine stays dormant; the socket is the host's).
|
||||
- name: Install docker CLI (host daemon is socket-mounted)
|
||||
run: |
|
||||
apt-get update -qq && apt-get install -y -qq docker.io >/dev/null
|
||||
docker version --format 'client {{.Client.Version}} / server {{.Server.Version}}'
|
||||
|
||||
- name: Enable pnpm
|
||||
run: corepack enable pnpm
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
# build:binary stamps NEXTCRAFT_VERSION_STAMP from the tag argument
|
||||
# (build-binary.mjs validates it; `--version` reports it — G-102).
|
||||
- name: Build x64 binary (SEA)
|
||||
run: pnpm --filter @nextcraft/cli build:binary ${{ gitea.ref_name }} --arch x64
|
||||
|
||||
# P3 (REQ-8-003, R-25/G-201): arm64 is QEMU-free — the ONLY
|
||||
# arch-specific step (the node binary copy) uses the official arm64
|
||||
# node tarball; esbuild + postject are file surgery, nothing arm64
|
||||
# executes on the x64 runner. The G-201 fallback ladder lives in
|
||||
# PLAN MH-3a: if the probe ever fails, binfmt-full then x64-only
|
||||
# deferral — never a red lane.
|
||||
- name: Build arm64 binary (SEA, QEMU-free cross-build)
|
||||
run: pnpm --filter @nextcraft/cli build:binary ${{ gitea.ref_name }} --arch arm64
|
||||
|
||||
# P3 (R-22/R-23, D-067): deb packages for both arches — binary +
|
||||
# docs, advisory postinst, Version = tag minus v.
|
||||
- name: Build debs (x64 + arm64)
|
||||
run: |
|
||||
bash scripts/build-deb.sh ${{ gitea.ref_name }} x64
|
||||
bash scripts/build-deb.sh ${{ gitea.ref_name }} arm64
|
||||
|
||||
# Deb smoke (MH-3b): the amd64 deb installs in a fresh debian
|
||||
# container and its binary speaks (the arm64 deb cannot exec on this
|
||||
# x64 runner — its checksum + structure are the release-side proof).
|
||||
# The deb enters via STDIN tar — sibling-mode bind mounts resolve on
|
||||
# the HOST, and the job workspace path does not exist there (R-7's
|
||||
# documented gotcha; docker build works because it TARs the context).
|
||||
- name: Deb smoke — fresh-container install + advisory doctor
|
||||
run: |
|
||||
set -euo pipefail
|
||||
TAG="${{ gitea.ref_name }}"
|
||||
VER="${TAG#v}"
|
||||
DEB="apps/cli/dist/deb/nextcraft_${VER}_amd64.deb"
|
||||
[ -f "$DEB" ] || { echo "missing $DEB"; exit 1; }
|
||||
tar -cf - -C "$(dirname "$DEB")" "$(basename "$DEB")" \
|
||||
| docker run --rm -i --rm debian:bookworm bash -c '
|
||||
set -e
|
||||
mkdir -p /deb && tar -xf - -C /deb
|
||||
DEB_FILE="/deb/$(basename /deb/nextcraft_*.deb)"
|
||||
dpkg -i "$DEB_FILE" >/tmp/dpkg.log 2>&1 || true # advisory postinst: exit 0
|
||||
/usr/bin/nextcraft --version
|
||||
dpkg-deb --field "$DEB_FILE" Package Version Architecture
|
||||
'
|
||||
|
||||
- name: Verify artifacts
|
||||
run: |
|
||||
set -euo pipefail
|
||||
for A in x64 arm64; do
|
||||
BIN="apps/cli/dist/nextcraft-linux-$A"
|
||||
SUM="$BIN.sha256"
|
||||
[ -f "$BIN" ] || { echo "missing $BIN"; exit 1; }
|
||||
[ -f "$SUM" ] || { echo "missing $SUM"; exit 1; }
|
||||
# The sidecar names the bare file — verify from the dist dir.
|
||||
(cd "$(dirname "$BIN")" && sha256sum -c "$(basename "$SUM")")
|
||||
echo "$A size: $(stat -c%s "$BIN") bytes"
|
||||
done
|
||||
for D in apps/cli/dist/deb/*.deb; do
|
||||
[ -f "$D.sha256" ] || { echo "missing $D.sha256"; exit 1; }
|
||||
(cd "$(dirname "$D")" && sha256sum -c "$(basename "$D.sha256")")
|
||||
done
|
||||
|
||||
# Resolve the release id for the tag (the release is auto-created by
|
||||
# Gitea on tag push if the repo setting is on; if not, create it
|
||||
# first). Same call as scripts/release-assets.sh:32-49 (R-14).
|
||||
- name: Resolve release id
|
||||
run: |
|
||||
set -euo pipefail
|
||||
TAG="${{ gitea.ref_name }}"
|
||||
BASE="https://git.coreci.dev/api/v1/repos/coreci/nextcraft"
|
||||
RESPONSE="$(curl -sS -w '\n%{http_code}' \
|
||||
-H "Authorization: token $RELEASE_TOKEN" \
|
||||
"$BASE/releases/tags/$TAG")"
|
||||
BODY="$(echo "$RESPONSE" | sed '$d')"
|
||||
CODE="$(echo "$RESPONSE" | tail -1)"
|
||||
if [ "$CODE" = "404" ]; then
|
||||
echo "release for $TAG not found — creating it"
|
||||
BODY="$(curl -sS -f -X POST \
|
||||
-H "Authorization: token $RELEASE_TOKEN" \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d "{\"tag_name\": \"$TAG\", \"name\": \"$TAG\"}" \
|
||||
"$BASE/releases")"
|
||||
else
|
||||
echo "$CODE" | grep -q '^2' || { echo "release lookup failed: $CODE"; echo "$BODY"; exit 1; }
|
||||
fi
|
||||
RELEASE_ID="$(echo "$BODY" | python3 -c 'import json,sys; print(json.load(sys.stdin)["id"])')"
|
||||
echo "release id: $RELEASE_ID"
|
||||
echo "RELEASE_ID=$RELEASE_ID" >> "$GITHUB_ENV"
|
||||
|
||||
# Attach the FULL asset matrix (D-064): 2 binaries + 2 checksums +
|
||||
# 2 debs + 2 deb checksums. actions/upload-artifact is a DIFFERENT
|
||||
# mechanism (job artifacts via the cache server, not release
|
||||
# downloads) — do NOT use it here (R-14). curl multipart is the API.
|
||||
- name: Attach asset matrix to release
|
||||
run: |
|
||||
set -euo pipefail
|
||||
BASE="https://git.coreci.dev/api/v1/repos/coreci/nextcraft"
|
||||
upload() {
|
||||
local file="$1" name="$2"
|
||||
curl -sS -f -X POST \
|
||||
-H "Authorization: token $RELEASE_TOKEN" \
|
||||
-F "attachment=@$file" \
|
||||
"$BASE/releases/$RELEASE_ID/assets?name=$name" >/dev/null
|
||||
echo "attached $name"
|
||||
}
|
||||
for A in x64 arm64; do
|
||||
upload "apps/cli/dist/nextcraft-linux-$A" "nextcraft-linux-$A"
|
||||
upload "apps/cli/dist/nextcraft-linux-$A.sha256" "nextcraft-linux-$A.sha256"
|
||||
done
|
||||
TAG="${{ gitea.ref_name }}"
|
||||
VER="${TAG#v}"
|
||||
for D in amd64 arm64; do
|
||||
upload "apps/cli/dist/deb/nextcraft_${VER}_${D}.deb" "nextcraft_${VER}_${D}.deb"
|
||||
upload "apps/cli/dist/deb/nextcraft_${VER}_${D}.deb.sha256" "nextcraft_${VER}_${D}.deb.sha256"
|
||||
done
|
||||
|
||||
# -- P2 extension (REQ-8-002, R-20, D-065): build + push the docker
|
||||
# image to the Gitea registry on every phase release ----------------
|
||||
# The job token cannot publish packages (R-13, upstream-confirmed);
|
||||
# REGISTRY_TOKEN (repo Actions secret, self-served at P1: G-205) is
|
||||
# the PAT with package-write.
|
||||
- name: Build docker image
|
||||
run: |
|
||||
set -euo pipefail
|
||||
TAG="${{ gitea.ref_name }}"
|
||||
docker build \
|
||||
--build-arg NEXTCRAFT_VERSION="$TAG" \
|
||||
-t "git.coreci.dev/coreci/nextcraft:$TAG" \
|
||||
-t "git.coreci.dev/coreci/nextcraft:latest" \
|
||||
.
|
||||
|
||||
- name: Push image to the Gitea registry
|
||||
run: |
|
||||
set -euo pipefail
|
||||
echo "${{ secrets.REGISTRY_TOKEN }}" | docker login git.coreci.dev \
|
||||
-u coreci --password-stdin
|
||||
TAG="${{ gitea.ref_name }}"
|
||||
docker push "git.coreci.dev/coreci/nextcraft:$TAG"
|
||||
docker push "git.coreci.dev/coreci/nextcraft:latest"
|
||||
|
||||
# Smoke gate (G-204, five pinned assertions): a red image = red
|
||||
# release. Probes run via docker exec INSIDE the container — the
|
||||
# job container's 127.0.0.1 is not the host, and the smoke container
|
||||
# publishes no ports (the admin-facing port map is the admin's call,
|
||||
# not the gate's).
|
||||
- name: Smoke gate — unprivileged run proves the honest degrade
|
||||
run: |
|
||||
set -euo pipefail
|
||||
TAG="${{ gitea.ref_name }}"
|
||||
CID=""
|
||||
cleanup() { [ -n "$CID" ] && docker rm -f "$CID" >/dev/null 2>&1 || true; }
|
||||
trap cleanup EXIT
|
||||
CID="$(docker run -d "git.coreci.dev/coreci/nextcraft:$TAG")"
|
||||
echo "container $CID up"
|
||||
|
||||
# 1. /health 200 within the window (in-container urllib — slim
|
||||
# has no curl; the HEALTHCHECK does the same)
|
||||
ok=""
|
||||
for i in $(seq 1 30); do
|
||||
if docker exec "$CID" python3 -c "import urllib.request,sys; sys.exit(0 if urllib.request.urlopen('http://127.0.0.1:8420/health', timeout=3).status == 200 else 1)" 2>/dev/null; then ok=1; break; fi
|
||||
sleep 2
|
||||
done
|
||||
[ -n "$ok" ] || { echo "FAIL: /health never returned 200"; docker logs "$CID" 2>&1 | tail -30; exit 1; }
|
||||
echo "assert 1/5: /health 200"
|
||||
|
||||
# 2. GET / is HTML with a real document marker (not just non-JSON
|
||||
# — the v0.4.6 lesson; G-204). One-line python: checks the
|
||||
# doctype/html prefix on the FULL lowered head, not a 6-char
|
||||
# slice (rc6 finding — the slice truncated the marker).
|
||||
docker exec "$CID" python3 -c "import urllib.request,sys; body = urllib.request.urlopen('http://127.0.0.1:8420/', timeout=5).read(); head = body.lstrip()[:32].lower(); sys.exit(0 if (head.startswith(b'<!doctype') or head.startswith(b'<html')) else 1)" \
|
||||
|| { echo "FAIL: / is not HTML"; exit 1; }
|
||||
echo "assert 2/5: / serves HTML"
|
||||
|
||||
# 3. degrade boot notice present in container logs (unprivileged
|
||||
# default → seccomp blocks userns → loud notice, D-068).
|
||||
# Retry window: the /health probe can pass in the same instant
|
||||
# the boot log is still flushing (rc4 finding — 60ms race);
|
||||
# the notice check polls up to 15s, it does not trust timing.
|
||||
ok=""
|
||||
for i in $(seq 1 15); do
|
||||
if docker logs "$CID" 2>&1 | grep -q "SANDBOX FABRIC DEGRADED"; then ok=1; break; fi
|
||||
sleep 1
|
||||
done
|
||||
[ -n "$ok" ] \
|
||||
|| { echo "FAIL: degrade boot notice absent"; docker logs "$CID" 2>&1 | tail -30; exit 1; }
|
||||
echo "assert 3/5: degrade notice logged"
|
||||
|
||||
# 4. fabric env-create is refused BEFORE the fabric (503 degraded
|
||||
# or 403 gate-first — both prove the degrade path short-circuits
|
||||
# learner env creation; a 201 would prove the fabric ran, which
|
||||
# an unprivileged container cannot allow). The probe python is
|
||||
# written to a file first (a yaml block scalar cannot embed
|
||||
# unindented command substitution continuations).
|
||||
cat > /tmp/smoke_probe.py << 'PYEOF'
|
||||
import urllib.request, urllib.error, json, sys
|
||||
req = urllib.request.Request('http://127.0.0.1:8420/v1/sandboxes',
|
||||
data=json.dumps({'learner_id':'smoke','task_id':'t'}).encode(),
|
||||
headers={'Content-Type':'application/json'}, method='POST')
|
||||
try:
|
||||
print(urllib.request.urlopen(req, timeout=5).status)
|
||||
except urllib.error.HTTPError as e:
|
||||
print(e.code)
|
||||
except Exception:
|
||||
print('ERR')
|
||||
sys.stdout.flush()
|
||||
PYEOF
|
||||
docker cp /tmp/smoke_probe.py "$CID":/tmp/smoke_probe.py
|
||||
STATUS="$(docker exec "$CID" python3 /tmp/smoke_probe.py)"
|
||||
[ "$STATUS" = "503" ] || [ "$STATUS" = "403" ] \
|
||||
|| { echo "FAIL: env-create was $STATUS (expected 503 degraded or 403 gate)"; exit 1; }
|
||||
echo "assert 4/5: degraded env-create refused ($STATUS)"
|
||||
|
||||
# 5. in-container CLI speaks (embedded doctor reports the docker
|
||||
# channel — D-066) + clean stop
|
||||
docker exec "$CID" nextcraft --version \
|
||||
|| { echo "FAIL: embedded CLI does not run"; exit 1; }
|
||||
echo "assert 5/5: embedded CLI alive + clean stop"
|
||||
docker rm -f "$CID" >/dev/null && CID=""
|
||||
# -- R1 deploy leg (REQ-v1-003 machinery set c18619; hep APPROVE c18623;
|
||||
# vehicle call c18634: the last mile is THIS pipeline, not an SRE infra
|
||||
# detour). Pipeline-only host refresh of the product host - no manual
|
||||
# host pokes. Provenance = this job's run id + the post-deploy identity
|
||||
# read below. The footer is retired as a freshness marker (it is the
|
||||
# code's own label - c18624 correction, confirmed by hep): freshness
|
||||
# reads are machine-read (/health + / serving HTML + the /v1/placements/
|
||||
# admin route registration in /openapi.json).
|
||||
#
|
||||
# One-time plumbing preconditions (declared for the MR review; NOT a
|
||||
# routing of the refresh to SRE - SRE keeps the R3 re-probe lane only):
|
||||
# * DEPLOY_SSH_KEY - repo Actions secret: the least-scope deploy key
|
||||
# authorized on the product host's deploy account (deploy@10.0.0.105
|
||||
# per deploy/README.md topology). One-time grant via the SRE/console
|
||||
# precedent (deploy/ci README G-206 pattern; self-serve secret PUT
|
||||
# precedent: REGISTRY_TOKEN, HTTP 201 on 2026-09-27).
|
||||
# * (optional hardening) DEPLOY_HOSTKEY - repo Actions secret holding
|
||||
# the product host's complete ssh public host-key line; when set it
|
||||
# is PINNED (StrictHostKeyChecking=yes), else accept-new.
|
||||
# A missing DEPLOY_SSH_KEY at run time fails this leg LOUDLY - a red
|
||||
# Actions tab on a tag is a red deploy by design (deploy/README.md);
|
||||
# it is never silently skipped (set R1: the gate stays clearable on
|
||||
# evidence). The release/asset path is untouched: a deploy-leg
|
||||
# precondition failure cannot damage artifact shipping.
|
||||
deploy:
|
||||
needs: release
|
||||
runs-on: release
|
||||
steps:
|
||||
- name: Preflight - fail loud when the leg is unconfigured
|
||||
env:
|
||||
DEPLOY_SSH_KEY: ${{ secrets.DEPLOY_SSH_KEY }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
echo "deploy preflight: run id $GITHUB_RUN_ID / run #$GITHUB_RUN_NUMBER / job $GITHUB_JOB_ID / sha $GITHUB_SHA"
|
||||
[ -n "$DEPLOY_SSH_KEY" ] || { echo "FATAL: DEPLOY_SSH_KEY unset - deploy leg unconfigured; host NOT refreshed this release; release artifacts stand (release job already green)"; exit 1; }
|
||||
|
||||
- name: Refresh the product host over the declared ssh channel
|
||||
env:
|
||||
DEPLOY_SSH_KEY: ${{ secrets.DEPLOY_SSH_KEY }}
|
||||
DEPLOY_HOSTKEY: ${{ secrets.DEPLOY_HOSTKEY }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
trap 'rm -f /tmp/dk /tmp/kh' EXIT
|
||||
apt-get update -qq && apt-get install -y -qq openssh-client >/dev/null
|
||||
install -m 600 /dev/null /tmp/dk
|
||||
printf '%s\n' "$DEPLOY_SSH_KEY" > /tmp/dk
|
||||
unset DEPLOY_SSH_KEY
|
||||
if [ -n "${DEPLOY_HOSTKEY:-}" ]; then
|
||||
printf '%s\n' "$DEPLOY_HOSTKEY" > /tmp/kh
|
||||
SSH_PIN="-oUserKnownHostsFile=/tmp/kh -oStrictHostKeyChecking=yes"
|
||||
else
|
||||
SSH_PIN="-oStrictHostKeyChecking=accept-new"
|
||||
fi
|
||||
TAG="${{ gitea.ref_name }}"
|
||||
ssh -i /tmp/dk -o BatchMode=yes $SSH_PIN deploy@10.0.0.105 bash -s "$TAG" << 'REMOTE'
|
||||
set -euo pipefail
|
||||
TAG="$1"
|
||||
if command -v nextcraft >/dev/null 2>&1; then
|
||||
echo "channel: binary/deb - the one-command upgrade (idempotent, self-verifying per deploy/README.md)"
|
||||
nextcraft deploy --service --ref "$TAG"
|
||||
elif [ -n "$(docker ps --format '{{.Names}}' | grep -x nextcraft || true)" ]; then
|
||||
echo "channel: docker - README upgrade (pull + recreate; nextcraft-state persists)"
|
||||
docker pull git.coreci.dev/coreci/nextcraft:"$TAG"
|
||||
docker rm -f nextcraft
|
||||
docker run -d --name nextcraft -p 8420:8420 -v nextcraft-state:/home/nextcraft/.nextcraft git.coreci.dev/coreci/nextcraft:"$TAG"
|
||||
else
|
||||
echo "FATAL: no nextcraft channel on $(hostname) (no nextcraft on PATH; no docker container named nextcraft) - failing loud"
|
||||
exit 1
|
||||
fi
|
||||
echo "--- channel verify (advisory; the identity read below is canonical)"
|
||||
command -v nextcraft >/dev/null 2>&1 && nextcraft --version || true
|
||||
REMOTE
|
||||
RC=$?
|
||||
echo "host refresh done (rc=$RC); provenance: run id $GITHUB_RUN_ID / run #$GITHUB_RUN_NUMBER / job $GITHUB_JOB_ID / tag $TAG / sha $GITHUB_SHA"
|
||||
exit $RC
|
||||
|
||||
- name: Post-deploy identity read - the R1 provenance surface
|
||||
run: |
|
||||
set -euo pipefail
|
||||
TAG="${{ gitea.ref_name }}"
|
||||
echo "waiting for the stack to settle..."
|
||||
OK=""
|
||||
for i in $(seq 1 12); do
|
||||
CODE_H="$(curl -sS -o /tmp/h -m 15 -w '%{http_code}' https://nextcraft.coreci.dev/health || true)"
|
||||
if [ "$CODE_H" = "200" ] && grep -q '"status"' /tmp/h; then OK=1; break; fi
|
||||
sleep 5
|
||||
done
|
||||
[ -n "$OK" ] || { echo "FAIL: /health never returned 200 within the window"; exit 1; }
|
||||
echo "assert 1/3: /health 200 - $(head -c 200 /tmp/h)"
|
||||
CODE_R="$(curl -sS -o /tmp/r -m 15 -w '%{http_code}' https://nextcraft.coreci.dev/)"
|
||||
head -c 64 /tmp/r | tr -d '[:space:]' | head -c 9 | grep -qiE '^<!doctype|^<html' || { echo "FAIL: / is not HTML (code $CODE_R)"; exit 1; }
|
||||
echo "assert 2/3: / serves HTML ($CODE_R)"
|
||||
CODE_O="$(curl -sS -o /tmp/o -m 25 -w '%{http_code}' https://nextcraft.coreci.dev/openapi.json)"
|
||||
grep -q '"/v1/placements/admin' /tmp/o || { echo "FAIL: counting surface NOT registered on the served build (/openapi.json has no /v1/placements/admin routes) - honest red; R2 root-cause owns the diagnosis per c18619"; exit 1; }
|
||||
echo "assert 3/3: /v1/placements/admin registered in /openapi.json"
|
||||
echo "(advisory served version: $(grep -o '"version":"[^"]*"' /tmp/o | head -1))"
|
||||
echo "PROVENANCE (R1): deploy run id $GITHUB_RUN_ID / run #$GITHUB_RUN_NUMBER / job $GITHUB_JOB_ID / tag $TAG / head $GITHUB_SHA - identity reads green"
|
||||
@@ -44,6 +44,7 @@ yarn-error.log*
|
||||
|
||||
# Test coverage
|
||||
coverage/
|
||||
.coverage
|
||||
.nyc_output/
|
||||
|
||||
# Python tooling caches
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
shamefully-hoist=true
|
||||
strict-peer-dependencies=false
|
||||
pnpm-approved-builds=esbuild,core-js-pure
|
||||
pnpm-approved-builds=esbuild,core-js-pure
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
# Pre-commit hooks (D-070) — local hygiene mirroring the CI lanes.
|
||||
#
|
||||
# Design contract (G-209): every hook is LOCAL-ONLY (no network at hook
|
||||
# time — the mirror-style hooks below are fetched once at `pre-commit
|
||||
# install`/`pre-commit run` time from github.com, which this LAN reaches;
|
||||
# the language:system hooks run zero network). Hooks FAIL LOUD when the
|
||||
# toolchain is missing (D-070: a contributor without the toolbox gets an
|
||||
# explicit pointer, not a silent skip) — the no-toolbox escape is
|
||||
# `git commit --no-verify` (or `SKIP=...`), documented in README.md with
|
||||
# the loud note that CI still gates every push.
|
||||
#
|
||||
# Scope discipline mirrors .gitea/workflows/ci.yaml: ruff only touches
|
||||
# ai-service python; eslint/tsc only touch the TS workspaces; hygiene is
|
||||
# repo-wide.
|
||||
repos:
|
||||
# ---- basic hygiene (repo-wide, zero toolchain required)
|
||||
- repo: https://github.com/pre-commit/pre-commit-hooks
|
||||
rev: v4.6.0
|
||||
hooks:
|
||||
- id: trailing-whitespace
|
||||
- id: end-of-file-fixer
|
||||
- id: check-merge-conflict
|
||||
- id: check-added-large-files
|
||||
|
||||
# ---- ruff (ai-service python, D-063 lane parity)
|
||||
# Runs the venv-relative binary exactly like apps/ai-service/scripts/lint.sh
|
||||
# (venv is the repo's authority for the python toolchain). FAILS LOUD with
|
||||
# a bootstrap hint if the venv is missing — never a silent skip.
|
||||
- repo: local
|
||||
hooks:
|
||||
- id: ruff
|
||||
name: ruff check (ai-service)
|
||||
entry: apps/ai-service/scripts/lint.sh
|
||||
language: system
|
||||
types: [python]
|
||||
files: ^apps/ai-service/
|
||||
pass_filenames: false
|
||||
|
||||
# ---- eslint (TS workspaces, ONE root flat config at eslint.config.mjs)
|
||||
# Each workspace's `lint` script is `eslint .` resolving that config
|
||||
# upward, so a single root invocation is exact parity with the node
|
||||
# lane's per-workspace runs. `pnpm` resolves via PATH or corepack
|
||||
# (same discovery as nextcraft doctor); FAILS LOUD if neither exists.
|
||||
- id: eslint
|
||||
name: eslint (TS workspaces)
|
||||
entry: bash -c 'PNPM="$(command -v pnpm || echo "corepack pnpm")"; $PNPM exec eslint apps/web apps/cli packages/ui packages/types packages/mock-data'
|
||||
language: system
|
||||
files: ^(apps/web|apps/cli|packages/ui|packages/types|packages/mock-data)/.*\.(ts|tsx|mjs|cjs)$
|
||||
pass_filenames: false
|
||||
|
||||
# ---- tsc --noEmit per TS workspace (node-lane parity: pnpm --filter
|
||||
# over the same five workspaces; the tsconfig graph stays per-project)
|
||||
# (the shared PCMD discovery is repeated per hook because pre-commit
|
||||
# hooks run isolated entries)
|
||||
- id: tsc-web
|
||||
name: tsc --noEmit (web)
|
||||
entry: bash -c 'PNPM="$(command -v pnpm || echo "corepack pnpm")"; $PNPM --filter web typecheck'
|
||||
language: system
|
||||
files: ^apps/web/.*\.tsx?$
|
||||
pass_filenames: false
|
||||
- id: tsc-cli
|
||||
name: tsc --noEmit (cli)
|
||||
entry: bash -c 'PNPM="$(command -v pnpm || echo "corepack pnpm")"; $PNPM --filter @nextcraft/cli typecheck'
|
||||
language: system
|
||||
files: ^apps/cli/.*\.tsx?$
|
||||
pass_filenames: false
|
||||
- id: tsc-ui
|
||||
name: tsc --noEmit (ui)
|
||||
entry: bash -c 'PNPM="$(command -v pnpm || echo "corepack pnpm")"; $PNPM --filter @nextcraft/ui typecheck'
|
||||
language: system
|
||||
files: ^packages/ui/.*\.tsx?$
|
||||
pass_filenames: false
|
||||
- id: tsc-types
|
||||
name: tsc --noEmit (types)
|
||||
entry: bash -c 'PNPM="$(command -v pnpm || echo "corepack pnpm")"; $PNPM --filter @nextcraft/types typecheck'
|
||||
language: system
|
||||
files: ^packages/types/.*\.tsx?$
|
||||
pass_filenames: false
|
||||
- id: tsc-mock-data
|
||||
name: tsc --noEmit (mock-data)
|
||||
entry: bash -c 'PNPM="$(command -v pnpm || echo "corepack pnpm")"; $PNPM --filter @nextcraft/mock-data typecheck'
|
||||
language: system
|
||||
files: ^packages/mock-data/.*\.tsx?$
|
||||
pass_filenames: false
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
# Nextcraft — single-port docker image (v0.8 P2, REQ-8-002, R-16..R-19)
|
||||
#
|
||||
# Topology: uvicorn :8420 serves BOTH the API (/v1/*, /health) and the
|
||||
# exported web UI (everything else) — the same single-port production
|
||||
# shape as `nextcraft deploy` (D-039). Deps are pre-loaded in image
|
||||
# layers; runtime is unprivileged by default (honest sandbox degrade:
|
||||
# ai_service/sandbox/capability.py probes + api/sandboxes.py 503s with
|
||||
# remediation — D-068/G-208).
|
||||
#
|
||||
# Build context is the repo root. Build args:
|
||||
# NEXTCRAFT_VERSION — stamped into the embedded CLI (`--version`)
|
||||
#
|
||||
# Stages:
|
||||
# 1. web-export — node:24-bookworm: pnpm workspace install, static
|
||||
# export (NEXT_PUBLIC_AI_SERVICE_URL=self), SEA CLI binary build
|
||||
# 2. venv — python:3.11-bookworm: production deps only (no [dev])
|
||||
# 3. runtime — python:3.11-slim-bookworm: non-root, venv + package +
|
||||
# export + CLI, /health healthcheck, state volume
|
||||
|
||||
# -- stage 1: web export + CLI binary ---------------------------------------
|
||||
FROM node:24-bookworm AS web-export
|
||||
ARG NEXTCRAFT_VERSION=0.0.0-dev
|
||||
WORKDIR /repo
|
||||
|
||||
# Toolchain: corepack ships with node 24 (deprecated but present).
|
||||
RUN corepack enable pnpm
|
||||
|
||||
# Workspace manifests first (layer-cacheable install).
|
||||
COPY package.json pnpm-workspace.yaml pnpm-lock.yaml .npmrc tsconfig.json ./
|
||||
COPY apps/web/package.json apps/web/
|
||||
COPY apps/cli/package.json apps/cli/
|
||||
COPY packages/types/package.json packages/types/
|
||||
COPY packages/ui/package.json packages/ui/
|
||||
COPY packages/mock-data/package.json packages/mock-data/
|
||||
RUN pnpm install --frozen-lockfile
|
||||
|
||||
# Sources (web build needs all workspaces; CLI build needs its tree).
|
||||
COPY apps ./apps
|
||||
COPY packages ./packages
|
||||
|
||||
# Static export (same command as the deploy path): the export lands in
|
||||
# apps/web/out and is served same-origin by uvicorn.
|
||||
ENV NEXT_PUBLIC_AI_SERVICE_URL=self
|
||||
RUN pnpm --filter web build
|
||||
|
||||
# Embedded CLI (D-066): doctor/verify/guide work in-container; the daemon
|
||||
# commands refuse honestly (see apps/cli/src — NC_CONTAINER detection).
|
||||
RUN pnpm --filter @nextcraft/cli build:binary "$NEXTCRAFT_VERSION"
|
||||
|
||||
# -- stage 2: python venv ----------------------------------------------------
|
||||
FROM python:3.11-bookworm AS venv
|
||||
WORKDIR /repo
|
||||
# The full source tree installs the package (bootstrap.sh's mechanism
|
||||
# without [dev]: production deps only — the image runs the app, it never
|
||||
# lints/tests it; the runner lanes own that).
|
||||
COPY apps/ai-service /repo/apps/ai-service
|
||||
RUN python3 -m venv /opt/venv && \
|
||||
/opt/venv/bin/pip install --no-cache-dir --upgrade pip && \
|
||||
/opt/venv/bin/pip install --no-cache-dir /repo/apps/ai-service
|
||||
|
||||
# -- stage 3: runtime --------------------------------------------------------
|
||||
FROM python:3.11-slim-bookworm AS runtime
|
||||
WORKDIR /opt/nextcraft
|
||||
|
||||
# Non-root user; home carries the state volume (~/.nextcraft semantics —
|
||||
# config.py anchors db/sandboxes under $HOME/.nextcraft, R-17).
|
||||
RUN useradd --create-home --uid 10001 nextcraft
|
||||
|
||||
# venv from stage 2 (production deps only).
|
||||
COPY --from=venv /opt/venv /opt/venv
|
||||
ENV PATH=/opt/venv/bin:$PATH
|
||||
|
||||
# The installed ai_service package is IN the venv's site-packages; the
|
||||
# source tree rides along for transparency (PYTHONPATH prefers the
|
||||
# installed package).
|
||||
COPY --from=venv /repo/apps/ai-service /opt/nextcraft/ai-service-src
|
||||
RUN rm -rf /opt/nextcraft/ai-service-src/.venv
|
||||
|
||||
# Web export from stage 1.
|
||||
COPY --from=web-export /repo/apps/web/out /opt/nextcraft/web-out
|
||||
ENV AI_WEB_STATIC_DIR=/opt/nextcraft/web-out
|
||||
|
||||
# Image marker: NC_CONTAINER=1 (context for the CLI container-mode
|
||||
# branches and the degrade boot notice; the capability PROBE — not this
|
||||
# marker — decides degrade, D-068).
|
||||
ENV NC_CONTAINER=1
|
||||
|
||||
# Embedded CLI (D-066).
|
||||
COPY --from=web-export /repo/apps/cli/dist/nextcraft-linux-x64 /usr/local/bin/nextcraft
|
||||
RUN chmod 0755 /usr/local/bin/nextcraft
|
||||
|
||||
# App dir + state: db/sandboxes under /home/nextcraft/.nextcraft (R-17).
|
||||
# The state root is pre-created with correct ownership BEFORE the VOLUME
|
||||
# declaration — an anonymous volume copies the image's directory CONTENTS
|
||||
# and ownership at first use, so the app (uid 10001) can mkdir its data/
|
||||
# and sandboxes/ subdirs on a clean boot (rc5 smoke-gate finding: the
|
||||
# bare useradd home did not carry a writable .nextcraft).
|
||||
RUN mkdir -p /home/nextcraft/.nextcraft/data \
|
||||
&& chown -R nextcraft:nextcraft /opt/nextcraft /home/nextcraft/.nextcraft
|
||||
WORKDIR /opt/nextcraft/ai-service-src
|
||||
USER nextcraft
|
||||
ENV AI_HOST=0.0.0.0 AI_PORT=8420
|
||||
|
||||
EXPOSE 8420
|
||||
# slim has no curl — the healthcheck speaks python (stdlib urllib).
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \
|
||||
CMD ["python3", "-c", "import urllib.request,sys; sys.exit(0 if urllib.request.urlopen('http://127.0.0.1:8420/health', timeout=4).status == 200 else 1)"]
|
||||
|
||||
VOLUME ["/home/nextcraft/.nextcraft"]
|
||||
|
||||
CMD ["python3", "-m", "uvicorn", "ai_service.main:app", "--host", "0.0.0.0", "--port", "8420"]
|
||||
@@ -1,16 +1,26 @@
|
||||
# Nextcraft
|
||||
|
||||
AI-native outcome school + marketplace — graduates prove what they can build, not what they can write.
|
||||
**TL;DR** — AI-native outcome school + marketplace — graduates prove what they can build, not what they can write. This file is the front door: three install channels, dev setup from a clone, and the CLI reference; the admin runbook for standing the stack up on a server lives in [deploy/README.md](deploy/README.md).
|
||||
|
||||
## Quickstart
|
||||
|
||||
One-liner install (linux x64):
|
||||
nextcraft installs on any Debian-based Linux server through **three channels** (full recipes in [deploy/README.md](deploy/README.md) or `nextcraft guide`):
|
||||
|
||||
```sh
|
||||
# 1. docker — the whole stack pre-loaded (API + UI + CLI in one image):
|
||||
docker run -d --name nextcraft -p 8420:8420 \
|
||||
-v nextcraft-state:/home/nextcraft/.nextcraft \
|
||||
git.coreci.dev/coreci/nextcraft:<release-tag>
|
||||
|
||||
# 2. deb — apt-shaped (amd64 + arm64):
|
||||
dpkg -i nextcraft_<ver>_<arch>.deb && nextcraft deploy --service
|
||||
|
||||
# 3. binary — the one-liner (linux x64 + arm64):
|
||||
curl -fsSL https://git.coreci.dev/coreci/nextcraft/raw/main/scripts/install.sh | sh
|
||||
nextcraft deploy --service
|
||||
```
|
||||
|
||||
That downloads the latest release's `nextcraft` CLI binary, verifies its sha256 checksum, and installs it to `~/.local/bin` (PATH hint printed if needed). Every release ships fresh binaries — re-run the one-liner to upgrade.
|
||||
The binary download verifies sha256 + version stamps before install (mismatch = hard stop). Every release ships fresh binaries, debs, and a registry image — all machine-made by the [release workflow](.gitea/workflows/release.yaml).
|
||||
|
||||
### Server (deploy the whole stack, one command)
|
||||
|
||||
@@ -31,6 +41,31 @@ nextcraft dev # run the ai-service dev server on :8420 (web dev server:
|
||||
|
||||
The E2E test (`apps/cli/tests/fresh-clone-e2e.test.ts`) proves this exact sequence on a fresh clone.
|
||||
|
||||
#### Pre-commit hooks (optional, recommended)
|
||||
|
||||
The repo ships a `.pre-commit-config.yaml` that mirrors the CI lanes locally: ruff over the ai-service python, eslint over the five TS workspaces (one root flat config), `tsc --noEmit` per workspace, plus whitespace/merge-conflict/large-file hygiene. Hooks are local-only and fail loud.
|
||||
|
||||
```sh
|
||||
pip install pre-commit # or: pipx install pre-commit
|
||||
pre-commit install
|
||||
```
|
||||
|
||||
From then on every `git commit` runs the hooks on the staged changes. First run may fetch the hygiene hook repo (github.com, reachable from this LAN).
|
||||
|
||||
**No toolbox? The honest skip path:** if you don't have the ruff/eslint/tsc toolchain set up (e.g. no ai-service venv yet — run `nextcraft bootstrap` first), hooks will fail loud with a pointer. The simplest honest escape for a contributor without the toolbox is:
|
||||
|
||||
```sh
|
||||
git commit --no-verify
|
||||
```
|
||||
|
||||
or skip specific hooks for one commit:
|
||||
|
||||
```sh
|
||||
SKIP=ruff,eslint,tsc-web,tsc-cli,tsc-ui,tsc-types,tsc-mock-data git commit
|
||||
```
|
||||
|
||||
**Loud note: CI still gates.** Skipping locally changes nothing about the push lanes — `.gitea/workflows/ci.yaml` runs lint + typecheck + tests on every push to every branch. A `--no-verify` commit that breaks lint gets caught at push time, just later and more publicly.
|
||||
|
||||
### No binary / non-linux?
|
||||
|
||||
The installer degrades to printed source instructions. Manual equivalent:
|
||||
@@ -86,8 +121,10 @@ Durable state (SQLite DB, sandbox workdirs, daemon pid/log) lives in `~/.nextcra
|
||||
|
||||
## Status
|
||||
|
||||
**Milestone v0.5** — Real Server Voice, KYC/Identity, Sandbox Environments, Seq-Lease (shipped as v0.4.5)
|
||||
**Milestone v0.8** — Ship Anywhere (in progress): installable on any Debian-based server via every mainstream channel — docker image (Gitea registry, honest sandbox degrade), .deb packages (amd64+arm64, advisory postinst), arch-aware one-liner binary — with release consistency enforced by pre-commit hooks + Gitea Actions pipelines (runner fleet on CT 113, machine-made releases), the CLI carrying the full suite (`nextcraft guide`, channel-aware doctor), and the admin runbook (deploy/README.md).
|
||||
|
||||
Prior: v0.3 Credential Engines (shipped v0.2.8) · v0.2 AI Tutor Architecture (v0.2.0) · v0.1 UI/UX Prototype (v0.1.0)
|
||||
Prior: v0.7 Test Harness Review (shipped as v0.6.6) · **Milestone v0.6** — Marketplace Engine (shipped as v0.5.6): real job-postings backend behind the marketplace surfaces (6th SQLite store family + seeded ingestion adapter + admin authoring surface), AI tagging with facet-driven filters, embedding-backed semantic search with computed match scores, employer enrichment with per-field provenance, resume-to-profile auto-fill with an explicit confirm gate, and SEO programmatic pages (metadata, JSON-LD, dynamic sitemap/robots).
|
||||
|
||||
Initialized via CIAgent v0.7.0
|
||||
Prior: v0.5 Real Server Voice, KYC/Identity, Sandbox Environments, Seq-Lease (shipped as v0.4.5) · v0.3 Credential Engines (v0.2.8) · v0.2 AI Tutor Architecture (v0.2.0) · v0.1 UI/UX Prototype (v0.1.0)
|
||||
|
||||
Initialized via CIAgent v0.7.0
|
||||
|
||||
@@ -83,9 +83,21 @@ AI_VOICE_PROVIDER=mock
|
||||
# AI_ADMIN_TOKEN=
|
||||
# P5 (D-056) placeholder: the deployed origin for sitemap.xml / robots.txt
|
||||
# absolute URLs (e.g. https://nextcraft.example). Unset → SEO phase
|
||||
# serves the empty static-page set with a boot warning (G-105).
|
||||
# serves the empty-page set with a boot warning (G-105).
|
||||
# AI_PUBLIC_BASE_URL=
|
||||
|
||||
# --- Employer auth throttles (REQ-10-001, D-088) ---
|
||||
# Documentation of the ACTIVE defaults (a-313) — both knobs are always
|
||||
# on as Settings ints; these env entries override for ops tuning.
|
||||
# (a) Failed logins allowed per email per rolling 15-min window
|
||||
# (default 5 → 429 with an honest "wait" detail; a successful
|
||||
# login clears the window).
|
||||
# AI_EMPLOYER_LOGIN_FAILURES_PER_WINDOW=5
|
||||
# (b) Well-formed login+register attempts per rolling 60-s window
|
||||
# across all emails (default 30 → 429; failed passwords count —
|
||||
# the credential-stuffing bound, G-314).
|
||||
# AI_EMPLOYER_AUTH_ATTEMPTS_PER_MIN=30
|
||||
|
||||
# --- Semantic search embeddings (REQ-6-003, D-051) ---
|
||||
# 'mock' (default — deterministic 256-dim feature-hash, pure stdlib, no
|
||||
# key needed; tests never call a real embeddings API) or 'openai-embed'.
|
||||
@@ -103,3 +115,18 @@ AI_EMBED_PROVIDER=mock
|
||||
# -H "Authorization: Bearer $AI_EMBED_API_KEY" \
|
||||
# -H 'Content-Type: application/json' \
|
||||
# -d '{"model":"'"$AI_EMBED_MODEL"'","input":["Nextcraft probe"]}' | jq -e '.data[0].embedding | length'
|
||||
|
||||
# --- Billing / Payment Engine (REQ-9-001, D-075, D-077) ---
|
||||
# Payment provider: 'mock' (default — deterministic, zero-network; tests
|
||||
# NEVER call a real payment API) or 'stripe' (real Stripe-compatible REST,
|
||||
# P3+). Unknown names raise at the factory; the boot falls back to mock
|
||||
# with a loud log (G-11).
|
||||
# AI_PAYMENT_PROVIDER=mock
|
||||
# Real provider API key (Stripe-style sk_test_... placeholder — NEVER a
|
||||
# real key here; real keys live in .ciagent/.env.secrets, env-only per
|
||||
# D-014, never logged, SecretStr in Settings). 'mock' ignores it.
|
||||
# AI_PAYMENT_API_KEY=
|
||||
# Webhook HMAC secret (whsec_... style; UNSET → per-boot random → signed
|
||||
# webhooks FAIL CLOSED with 401 until configured — correct for a payment
|
||||
# surface). Set a fixed value only when a provider actually delivers.
|
||||
# AI_WEBHOOK_SECRET=
|
||||
|
||||
@@ -265,4 +265,4 @@ scripts/ bootstrap.sh dev.sh test.sh lint.sh
|
||||
tests/ pytest — mock provider only
|
||||
```
|
||||
|
||||
Boundary rules: `llm/` imports nothing from `agents/` or `api/`; `agents/` imports nothing from `api/`.
|
||||
Boundary rules: `llm/` imports nothing from `agents/` or `api/`; `agents/` imports nothing from `api/`.
|
||||
|
||||
@@ -1,3 +1,38 @@
|
||||
"""Nextcraft AI tutor service — six LLM agents behind a provider-agnostic layer."""
|
||||
"""Nextcraft AI tutor service — six LLM agents behind a provider-agnostic layer.
|
||||
|
||||
__version__ = "0.2.0"
|
||||
Version single-source (D-061): pyproject.toml is the ONE place the version
|
||||
literal lives. `__version__` (and FastAPI's `version=`) resolve from, in order:
|
||||
|
||||
1. the installed distribution metadata (pip install -e builds it from
|
||||
pyproject at install time), falling back to
|
||||
2. the source tree's pyproject.toml via tomllib (un-installed source runs).
|
||||
|
||||
No fallback literal exists — drift is structurally impossible: if pyproject
|
||||
bumps, both paths follow. Path 2 only degrades when neither metadata nor a
|
||||
pyproject.toml exists (a bare directory copy), reported as "unknown".
|
||||
"""
|
||||
|
||||
import tomllib
|
||||
from importlib.metadata import PackageNotFoundError
|
||||
from importlib.metadata import version as _dist_version
|
||||
from pathlib import Path
|
||||
|
||||
_DIST_NAME = "nextcraft-ai-service"
|
||||
|
||||
|
||||
def _resolve_version() -> str:
|
||||
try:
|
||||
return _dist_version(_DIST_NAME)
|
||||
except PackageNotFoundError:
|
||||
pass
|
||||
# Un-installed source run: read the source tree's pyproject.toml
|
||||
# (ai_service/__init__.py → ../pyproject.toml).
|
||||
pyproject = Path(__file__).resolve().parent.parent / "pyproject.toml"
|
||||
try:
|
||||
data = tomllib.loads(pyproject.read_text(encoding="utf-8"))
|
||||
return str(data["project"]["version"])
|
||||
except (OSError, KeyError, tomllib.TOMLDecodeError):
|
||||
return "unknown"
|
||||
|
||||
|
||||
__version__ = _resolve_version()
|
||||
|
||||
@@ -6,6 +6,7 @@ The default pipeline: build_messages() → provider.stream_chat()/chat().
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from collections.abc import AsyncIterator
|
||||
from typing import TypeVar
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
@@ -15,6 +16,8 @@ from ..llm.base import LLMProvider
|
||||
from ..llm.types import Message
|
||||
from .structured import structured_completion
|
||||
|
||||
T = TypeVar("T", bound=BaseModel)
|
||||
|
||||
|
||||
class BaseAgent(ABC):
|
||||
"""A tutor agent: system prompt + message assembly + provider delegation."""
|
||||
@@ -64,10 +67,15 @@ class BaseAgent(ABC):
|
||||
history: list[Message] | None = None,
|
||||
user_input: str = "",
|
||||
learner_context: LearnerContext | None = None,
|
||||
schema: type[BaseModel] | None = None,
|
||||
schema: type[T] | None = None,
|
||||
schema_hint: str = "",
|
||||
) -> BaseModel:
|
||||
"""Non-streaming completion parsed into a pydantic model (D-020 defense)."""
|
||||
) -> T:
|
||||
"""Non-streaming completion parsed into a pydantic model (D-020 defense).
|
||||
|
||||
P5: generic over `schema` — the returned model is the schema's own
|
||||
type, so callers (assessor/proctor) get concrete types, no casts.
|
||||
`schema=None` raises before T is ever produced.
|
||||
"""
|
||||
if schema is None:
|
||||
raise ValueError("structured_reply requires a schema")
|
||||
messages = self.build_messages(history, user_input, learner_context)
|
||||
|
||||
@@ -39,7 +39,7 @@ class ExaminerAgent(BaseAgent):
|
||||
|
||||
name = "examiner"
|
||||
|
||||
def system_prompt(self, learner_context=None) -> str: # noqa: ANN001
|
||||
def system_prompt(self, learner_context=None) -> str:
|
||||
"""Examiner is context-free (digest-anonymous, D-028 mirror)."""
|
||||
return SYSTEM_PROMPT
|
||||
|
||||
|
||||
@@ -28,15 +28,19 @@ class AgentSession:
|
||||
|
||||
|
||||
class SessionStore(Protocol):
|
||||
def get(self, session_id: str) -> AgentSession | None: ...
|
||||
def create(
|
||||
# P5 (D-058): the protocol was previously declared sync while the
|
||||
# shipped implementation is async — every API call site awaited a
|
||||
# non-awaitable per the old signature. The protocol now tells the
|
||||
# truth: all five methods are async (InMemorySessionStore's shape).
|
||||
async def get(self, session_id: str) -> AgentSession | None: ...
|
||||
async def create(
|
||||
self, session_id: str, agent: str, learner_id: str = "seed-learner-1"
|
||||
) -> AgentSession: ...
|
||||
def append(self, session_id: str, message: Message) -> None: ...
|
||||
def history_window(
|
||||
async def append(self, session_id: str, message: Message) -> None: ...
|
||||
async def history_window(
|
||||
self, session_id: str, max_messages: int = DEFAULT_WINDOW
|
||||
) -> list[Message]: ...
|
||||
def delete(self, session_id: str) -> None: ...
|
||||
async def delete(self, session_id: str) -> None: ...
|
||||
|
||||
|
||||
class InMemorySessionStore:
|
||||
|
||||
@@ -54,11 +54,12 @@ detail instead of rubric scores), so consumers read ONE shape.
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
from typing import Any, cast
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from ..agents.assessor import AssessorAgent
|
||||
from ..agents.registry import AgentRegistry
|
||||
from ..agents.structured import StructuredOutputError
|
||||
from ..config import Settings
|
||||
@@ -103,7 +104,9 @@ async def assessment_evaluate(
|
||||
status_code=404,
|
||||
detail=f"no stored grade for {body.learner_id}/{body.task_id} - grade first",
|
||||
)
|
||||
agent = registry.get(provider, settings, "assessor")
|
||||
# P5: registry.get returns BaseAgent; "assessor" is registered as
|
||||
# AssessorAgent (register_builtin_agents) — the cast states that mapping.
|
||||
agent = cast(AssessorAgent, registry.get(provider, settings, "assessor"))
|
||||
learner_context = get_learner_context(body.learner_id)
|
||||
try:
|
||||
coaching = await agent.coach_grade(grade, learner_context)
|
||||
|
||||
@@ -0,0 +1,345 @@
|
||||
"""/v1/billing — billing API (REQ-9-002/9-003, D-078/D-079/G-302).
|
||||
|
||||
P2: the public catalog read (advertising — no auth).
|
||||
P3: the public webhook receiver. Webhook discipline (risk-1/G-302):
|
||||
`await request.body()` FIRST — the exact un-parsed bytes verify the
|
||||
HMAC before ANY parsing; unsigned/bad signatures 401, never process.
|
||||
Event payloads are UNTRUSTED ID REFERENCES — session/subscription
|
||||
state resolves from LOCAL rows; unknown targets land as `unmatched`
|
||||
billing events (200, no entitlement). Provider event ids dedupe
|
||||
verbatim (at-least-once tolerance, R-45); grants are idempotent per
|
||||
SESSION (G-303 — the store's UniqueConstraints enforce exactly-once).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request, Response
|
||||
from pydantic import BaseModel
|
||||
|
||||
from ..billing.base import Package, Plan, WebhookSignatureError
|
||||
from ..billing.store import BillingStore
|
||||
from .deps import get_billing_store
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(prefix="/v1/billing", tags=["billing"])
|
||||
|
||||
|
||||
class CatalogResponse(BaseModel):
|
||||
"""The catalog wire shape (REQ-9-002; pinned field-for-field by
|
||||
packages/types/billing.ts via apps/web/tests/pins.test.ts — G-108
|
||||
discipline)."""
|
||||
|
||||
packages: list[Package]
|
||||
plans: list[Plan]
|
||||
|
||||
|
||||
@router.get("/catalog", response_model=CatalogResponse)
|
||||
def get_catalog(
|
||||
store: BillingStore = Depends(get_billing_store),
|
||||
) -> CatalogResponse:
|
||||
"""The seeded catalog, price-ascending (D-078 — one source of
|
||||
truth; idempotent seeding happened at app boot)."""
|
||||
packages, plans = store.list_catalog()
|
||||
return CatalogResponse(packages=packages, plans=plans)
|
||||
|
||||
|
||||
def _get_payment_provider(request: Request):
|
||||
"""The selected provider via app.state DI (main.py wires the
|
||||
factory + G-11 fallback)."""
|
||||
return request.app.state.payment_provider
|
||||
|
||||
|
||||
# -- webhook (Task 3-2-02, G-302) ----------------------------------------------
|
||||
|
||||
|
||||
async def process_webhook_event(
|
||||
*,
|
||||
store: BillingStore,
|
||||
provider: object,
|
||||
raw_body: bytes,
|
||||
signature_header: str,
|
||||
) -> dict[str, object]:
|
||||
"""The REAL webhook processing path (G-301's E2E proof runs through
|
||||
here; the HTTP route + the mock-complete route share it).
|
||||
|
||||
Order (risk-1): verify HMAC over the exact bytes FIRST, then parse,
|
||||
then dedupe, then process. 200 fast on every authenticated path —
|
||||
duplicates and unknown targets are recorded, never errors (R-45's
|
||||
at-least-once + G-306's unknown-target tolerance).
|
||||
|
||||
Crash-safety (final-review fix): the event id is recorded AFTER
|
||||
its effects commit. The old order (record id → process) made a
|
||||
crash between the two permanent: every retry deduped as
|
||||
"duplicate" while the grant never happened — the entitlement was
|
||||
lost forever. The new order keeps a bounded replay window: a
|
||||
replay re-runs processing (a no-op for grants — G-303's per-session
|
||||
UniqueConstraint is the exactly-once backstop) and re-records the
|
||||
audit rows for that one event only until its id lands."""
|
||||
from ..billing.base import PaymentProvider
|
||||
|
||||
assert isinstance(provider, PaymentProvider)
|
||||
try:
|
||||
verified = provider.verify_webhook(raw_body, signature_header)
|
||||
except WebhookSignatureError as exc:
|
||||
logger.warning("billing webhook rejected: %s", exc)
|
||||
raise HTTPException(status_code=401, detail=str(exc)) from exc
|
||||
except ValueError as exc:
|
||||
# G-306 (never 500): a correctly-SIGNED event whose type the
|
||||
# provider cannot normalize onto our canonical vocabulary
|
||||
# (Stripe's real streams deliver many event types) is honest
|
||||
# unmatched audit material, never a crashed receiver — Stripe
|
||||
# disables endpoints on error storms. The transport was
|
||||
# AUTHENTICATED (compare_digest passed) before the parse, so the
|
||||
# failure is name-level, not trust-level. WebhookSignatureError
|
||||
# is a ValueError subclass — the specific except above wins for
|
||||
# actual signature failures (401), this arm only sees
|
||||
# normalize_event's unmapped-name raise.
|
||||
store.insert_billing_event(
|
||||
"unmatched",
|
||||
"unmapped.event",
|
||||
detail={"reason": f"unmapped provider event: {exc}"},
|
||||
)
|
||||
return {"status": "unmatched", "processed": False}
|
||||
event = verified.event
|
||||
# Dedupe VERBATIM on the provider event id (R-43/D-083) — checked
|
||||
# BEFORE the effects (fast-path a known replay), recorded AFTER
|
||||
# they commit (the crash-safety half of the final-review fix). A
|
||||
# crash between the two leaves the id UN-recorded, so the provider's
|
||||
# retry re-runs the effects — a no-op for grants (G-303's
|
||||
# per-session UniqueConstraint is the exactly-once backstop) — and
|
||||
# lands the key then. The old order (record → process) made that
|
||||
# crash permanent: every retry answered "duplicate" while the grant
|
||||
# never happened.
|
||||
if not store.has_provider_event(verified.provider_event_id):
|
||||
result = _process_canonical_event(store, event.name, dict(event.payload))
|
||||
store.insert_provider_event(
|
||||
verified.provider_event_id, event.name, dict(event.payload)
|
||||
)
|
||||
return {"status": "ok", "processed": result}
|
||||
return {"status": "duplicate", "processed": False}
|
||||
|
||||
|
||||
def _process_canonical_event(
|
||||
store: BillingStore, name: str, payload: dict[str, object]
|
||||
) -> str:
|
||||
"""G-302: the payload is UNTRUSTED — id references only. State
|
||||
resolves from LOCAL rows; unknown targets land as unmatched audit
|
||||
rows (never a 500, G-306)."""
|
||||
if name == "checkout.completed":
|
||||
session_id = str(payload.get("session_id", ""))
|
||||
local = store.get_checkout_session_by_provider_id(session_id)
|
||||
if local is None:
|
||||
store.insert_billing_event(
|
||||
"unmatched",
|
||||
name,
|
||||
detail={"reason": "unknown session", "session_id": session_id},
|
||||
)
|
||||
return "unmatched"
|
||||
# R-37 predicate: complete AND paid — NEVER status alone (async
|
||||
# methods can leave a session complete with payment still
|
||||
# processing). Final-review fix: the payload's payment_status
|
||||
# (attacker-immutable: it is inside the HMAC) gates the flip +
|
||||
# the grant; an unpaid/processing completion is recorded, not
|
||||
# granted, and a later paid delivery grants.
|
||||
payment_status = str(payload.get("payment_status", "unpaid"))
|
||||
if payment_status not in ("paid", "no_payment_required"):
|
||||
store.insert_billing_event(
|
||||
"unmatched",
|
||||
name,
|
||||
detail={
|
||||
"reason": f"payment_status {payment_status!r} not paid",
|
||||
"session_id": local.id,
|
||||
},
|
||||
)
|
||||
return "processing"
|
||||
# Status resolves from the LOCAL row's snapshot (the route flips
|
||||
# it on completion), never the payload's other fields.
|
||||
store.complete_checkout_session(local.id, payment_status=payment_status)
|
||||
_grant_entitlement(store, local)
|
||||
store.insert_billing_event(
|
||||
"provider",
|
||||
name,
|
||||
employer_id=local.employer_id,
|
||||
detail={"session_id": local.id},
|
||||
)
|
||||
return "granted"
|
||||
if name == "invoice.paid":
|
||||
subscription_ref = str(payload.get("subscription_id", ""))
|
||||
extended = store.extend_subscription_period(subscription_ref, days=30)
|
||||
if extended is None:
|
||||
store.insert_billing_event(
|
||||
"unmatched",
|
||||
name,
|
||||
detail={
|
||||
"reason": "unknown subscription",
|
||||
"subscription_id": subscription_ref,
|
||||
},
|
||||
)
|
||||
return "unmatched"
|
||||
store.insert_billing_event(
|
||||
"provider", name, employer_id=extended.employer_id
|
||||
)
|
||||
return "renewed"
|
||||
if name == "invoice.payment_failed":
|
||||
subscription_ref = str(payload.get("subscription_id", ""))
|
||||
subscription = store.get_subscription_by_provider_id(subscription_ref)
|
||||
if subscription is None:
|
||||
store.insert_billing_event(
|
||||
"unmatched",
|
||||
name,
|
||||
detail={
|
||||
"reason": "unknown subscription",
|
||||
"subscription_id": subscription_ref,
|
||||
},
|
||||
)
|
||||
return "unmatched"
|
||||
try:
|
||||
store.transition_subscription(subscription.id, "past_due")
|
||||
except Exception:
|
||||
# Already reflected (out-of-order tolerance, G-306) — record.
|
||||
store.insert_billing_event(
|
||||
"unmatched",
|
||||
name,
|
||||
detail={"reason": "already past_due", "subscription_id": subscription_ref},
|
||||
)
|
||||
return "already"
|
||||
store.insert_billing_event(
|
||||
"provider", name, employer_id=subscription.employer_id
|
||||
)
|
||||
return "past_due"
|
||||
if name == "subscription.cancelled":
|
||||
subscription_ref = str(payload.get("subscription_id", ""))
|
||||
subscription = store.get_subscription_by_provider_id(subscription_ref)
|
||||
if subscription is None:
|
||||
store.insert_billing_event(
|
||||
"unmatched",
|
||||
name,
|
||||
detail={
|
||||
"reason": "unknown subscription",
|
||||
"subscription_id": subscription_ref,
|
||||
},
|
||||
)
|
||||
return "unmatched"
|
||||
try:
|
||||
store.transition_subscription(subscription.id, "cancelled")
|
||||
except Exception:
|
||||
store.insert_billing_event(
|
||||
"unmatched",
|
||||
name,
|
||||
detail={"reason": "already cancelled", "subscription_id": subscription_ref},
|
||||
)
|
||||
return "already"
|
||||
store.insert_billing_event(
|
||||
"provider", name, employer_id=subscription.employer_id
|
||||
)
|
||||
return "cancelled"
|
||||
if name == "subscription.renewed":
|
||||
# R-43: renewal = invoice.paid on a recurring subscription; the
|
||||
# corroborating customer.subscription.updated is recorded here.
|
||||
return _process_canonical_event(store, "invoice.paid", payload)
|
||||
store.insert_billing_event(
|
||||
"unmatched", name, detail={"reason": "unhandled canonical name"}
|
||||
)
|
||||
return "unhandled"
|
||||
|
||||
|
||||
def _grant_entitlement(store: BillingStore, session_row: object) -> str:
|
||||
"""Create the purchase or subscription from the LOCAL snapshot
|
||||
(D-078 prices; G-303 exactly-once per session — the store's
|
||||
UniqueConstraint refuses a second grant; the refusal is the
|
||||
already-granted answer, recorded not raised)."""
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from ..billing.store import CheckoutSessionRow
|
||||
|
||||
assert isinstance(session_row, CheckoutSessionRow)
|
||||
if session_row.mode == "payment":
|
||||
package, _, _item = store.get_catalog_item(session_row.item_id)
|
||||
if package is not None:
|
||||
try:
|
||||
store.create_purchase_from_session(
|
||||
session_row,
|
||||
posts_limit=package.posts_limit,
|
||||
duration_days=package.duration_days,
|
||||
)
|
||||
return "granted"
|
||||
except IntegrityError:
|
||||
# G-303: a distinct event id announced the SAME
|
||||
# completion — the grant already happened; the 200 is
|
||||
# the honest answer (never a 500, R-45).
|
||||
store.insert_billing_event(
|
||||
"unmatched",
|
||||
"checkout.completed",
|
||||
employer_id=session_row.employer_id,
|
||||
detail={
|
||||
"reason": "already granted",
|
||||
"session_id": session_row.id,
|
||||
},
|
||||
)
|
||||
return "already"
|
||||
# Final-review fix: the item vanished from the catalog AFTER the
|
||||
# checkout row snapshotted it (an operator deleted a seed id) —
|
||||
# record the anomaly; the caller's "granted"-shaped answer must
|
||||
# never silently mask a missing grant (the audit log answers
|
||||
# "why does this employer have no entitlement?").
|
||||
store.insert_billing_event(
|
||||
"unmatched",
|
||||
"checkout.completed",
|
||||
employer_id=session_row.employer_id,
|
||||
detail={
|
||||
"reason": "catalog item missing at grant time",
|
||||
"item_id": session_row.item_id,
|
||||
"session_id": session_row.id,
|
||||
},
|
||||
)
|
||||
return "no-item"
|
||||
_, plan, _item = store.get_catalog_item(session_row.item_id)
|
||||
if plan is not None:
|
||||
# Upsert keyed on the provider ref — replay-safe by construction.
|
||||
# Final-review fix: the ref is the mock provider's DOCUMENTED
|
||||
# convention (`sub_mock_{session_id without its cs_ prefix}`,
|
||||
# mock.py confirm_completion) — the old `sub_prov_…` spelling
|
||||
# made the store row's provider_subscription_id a key the
|
||||
# provider never knew, so every provider lifecycle call
|
||||
# (cancel/update) resolved None and desynced from local state.
|
||||
store.create_subscription_from_session(
|
||||
session_row,
|
||||
provider_subscription_id=(
|
||||
f"sub_mock_{session_row.provider_session_id.removeprefix('cs_')}"
|
||||
),
|
||||
interval=plan.interval,
|
||||
)
|
||||
return "granted"
|
||||
store.insert_billing_event(
|
||||
"unmatched",
|
||||
"checkout.completed",
|
||||
employer_id=session_row.employer_id,
|
||||
detail={
|
||||
"reason": "catalog item missing at grant time",
|
||||
"item_id": session_row.item_id,
|
||||
"session_id": session_row.id,
|
||||
},
|
||||
)
|
||||
return "no-item"
|
||||
|
||||
|
||||
@router.post("/webhook")
|
||||
async def billing_webhook(
|
||||
request: Request,
|
||||
store: BillingStore = Depends(get_billing_store),
|
||||
) -> Response:
|
||||
"""Public provider webhook receiver (server-to-server; CORS
|
||||
irrelevant). Risk-1 discipline: the RAW BODY is read + verified
|
||||
BEFORE any parsing — a pre-parsed body breaks the HMAC."""
|
||||
raw_body = await request.body()
|
||||
signature = request.headers.get("Stripe-Signature", "")
|
||||
await process_webhook_event(
|
||||
store=store,
|
||||
provider=_get_payment_provider(request),
|
||||
raw_body=raw_body,
|
||||
signature_header=signature,
|
||||
)
|
||||
return Response(content='{"received": true}', media_type="application/json")
|
||||
@@ -0,0 +1,536 @@
|
||||
"""/v1/billing/admin — operator billing API (REQ-9-003, D-076).
|
||||
|
||||
Operator-mediated checkout: at pilot there are no employer principals
|
||||
(A-407 — employers are data, not principals), so the operator buys on
|
||||
an employer's behalf. Every route sits behind `require_admin`
|
||||
(fail-closed, R-51 — copied verbatim from marketplace_admin.py); the
|
||||
checkout records operator_ref + employer_id provenance (D-076).
|
||||
|
||||
The mock-complete route (D-082, amended G-301) is admin-gated AND
|
||||
mounted only under provider=mock — the operator completing a session
|
||||
after out-of-band payment is the honest pilot flow.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from ..billing.base import (
|
||||
CheckoutSessionSpec,
|
||||
)
|
||||
from ..billing.store import BillingStore
|
||||
from ..config import Settings
|
||||
from .deps import get_billing_store
|
||||
from .marketplace_admin import require_admin
|
||||
|
||||
router = APIRouter(prefix="/v1/billing/admin", tags=["billing-admin"])
|
||||
|
||||
|
||||
# -- contracts ----------------------------------------------------------------
|
||||
|
||||
|
||||
class CheckoutCreate(BaseModel):
|
||||
"""The operator's checkout request (D-076): which catalog item, on
|
||||
behalf of which employer."""
|
||||
|
||||
item_id: str = Field(min_length=1)
|
||||
employer_id: str = Field(min_length=1)
|
||||
|
||||
|
||||
class CheckoutResponse(BaseModel):
|
||||
"""The created session handle + the local reconciliation id."""
|
||||
|
||||
session_id: str
|
||||
provider_session_id: str
|
||||
url: str
|
||||
mode: str
|
||||
|
||||
|
||||
class MockCompleteRequest(BaseModel):
|
||||
"""D-082/G-301: the operator completes a mock session after
|
||||
out-of-band payment. Admin-gated + mock-provider-only."""
|
||||
|
||||
provider_session_id: str = Field(min_length=1)
|
||||
|
||||
|
||||
class MockCompleteResponse(BaseModel):
|
||||
completed: bool
|
||||
payment_status: str
|
||||
|
||||
|
||||
class EntitlementResponse(BaseModel):
|
||||
"""The per-employer entitlement summary (REQ-9-004): active
|
||||
purchase (posts used/limit/expiry) + subscription state. The admin
|
||||
surface renders this (G-308's token-gated fetch)."""
|
||||
|
||||
employer_id: str
|
||||
purchase: dict[str, object] | None
|
||||
subscription: dict[str, object] | None
|
||||
|
||||
|
||||
# -- checkout (Task 3-2-01, G-310) ---------------------------------------------
|
||||
|
||||
|
||||
@router.post("/checkout", status_code=201, response_model=CheckoutResponse)
|
||||
async def create_checkout(
|
||||
body: CheckoutCreate,
|
||||
request: Request,
|
||||
store: BillingStore = Depends(get_billing_store),
|
||||
settings: Settings = Depends(require_admin),
|
||||
) -> CheckoutResponse:
|
||||
"""Create a provider checkout session for a catalog item on an
|
||||
employer's behalf (D-076). The catalog item snapshot (name +
|
||||
price_cents, D-078) rides the session and the local reconciliation
|
||||
row; success/cancel URLs default from public_base_url (G-310)."""
|
||||
package, plan, item = store.get_catalog_item(body.item_id)
|
||||
if item is None:
|
||||
raise HTTPException(status_code=404, detail="unknown catalog item")
|
||||
mode = "subscription" if item["kind"] == "plan" else "payment"
|
||||
interval: str = str(item.get("interval", "") or "")
|
||||
if settings.public_base_url:
|
||||
success_url = (
|
||||
f"{settings.public_base_url}/marketplace/pricing?checkout=success"
|
||||
)
|
||||
cancel_url = (
|
||||
f"{settings.public_base_url}/marketplace/pricing?checkout=cancelled"
|
||||
)
|
||||
else:
|
||||
# Mock pilot path: the mock provider never redirects; empty is
|
||||
# honest (stripe factory validation rejects the empty case —
|
||||
# G-310's loud boot warning covers the stripe selection).
|
||||
success_url = ""
|
||||
cancel_url = ""
|
||||
# The reconciliation key is the LOCAL row id (R-34): persist the
|
||||
# snapshot row FIRST, then mint the spec against it. The provider
|
||||
# session id is bound AFTER the provider call — until then the
|
||||
# placeholder must be UNIQUE (final-review fix: a bare "pending"
|
||||
# collided on the provider_session_id UNIQUE constraint the moment
|
||||
# two checkouts raced — the second admin POST 500'd with
|
||||
# IntegrityError; a fresh uuid per row makes the placeholder a
|
||||
# proper placeholder).
|
||||
row = store.insert_checkout_session(
|
||||
provider_session_id=f"pending-{uuid.uuid4().hex[:16]}",
|
||||
employer_id=body.employer_id,
|
||||
item_id=str(item["id"]),
|
||||
item_name=str(item["name"]),
|
||||
price_cents=int(item["price_cents"]),
|
||||
mode=mode,
|
||||
)
|
||||
spec = CheckoutSessionSpec(
|
||||
mode=mode, # type: ignore[arg-type]
|
||||
item_id=str(item["id"]),
|
||||
price_cents=int(item["price_cents"]),
|
||||
item_name=str(item["name"]),
|
||||
interval=interval,
|
||||
success_url=success_url,
|
||||
cancel_url=cancel_url,
|
||||
client_reference_id=row.id,
|
||||
metadata={
|
||||
"employer_id": body.employer_id,
|
||||
"operator_ref": "operator",
|
||||
},
|
||||
)
|
||||
provider = request.app.state.payment_provider
|
||||
session = await provider.create_checkout_session(spec)
|
||||
# Pin the provider session id onto the local row (upsert by local
|
||||
# id — the row IS the reconciliation record, G-302).
|
||||
store.bind_provider_session_id(row.id, session.id)
|
||||
return CheckoutResponse(
|
||||
session_id=row.id,
|
||||
provider_session_id=session.id,
|
||||
url=session.url,
|
||||
mode=mode,
|
||||
)
|
||||
|
||||
|
||||
# -- mock-complete (D-082, amended G-301) ---------------------------------------
|
||||
|
||||
|
||||
@router.post(
|
||||
"/mock/complete", status_code=200, response_model=MockCompleteResponse
|
||||
)
|
||||
async def mock_complete(
|
||||
body: MockCompleteRequest,
|
||||
request: Request,
|
||||
store: BillingStore = Depends(get_billing_store),
|
||||
settings: Settings = Depends(require_admin),
|
||||
) -> MockCompleteResponse:
|
||||
"""Complete a MOCK checkout session after out-of-band payment
|
||||
(D-082/G-301): admin-gated, mounted only under provider=mock —
|
||||
this route 404s on a stripe-configured box (the factory-conditional
|
||||
mount lives in main.py). The completion mints a properly-signed
|
||||
event through the REAL webhook processing path."""
|
||||
from ..billing.mock import MockPaymentProvider
|
||||
|
||||
provider = request.app.state.payment_provider
|
||||
if not isinstance(provider, MockPaymentProvider):
|
||||
# main.py gates the mount; this arm is defense-in-depth.
|
||||
raise HTTPException(
|
||||
status_code=404, detail="mock-complete exists only under provider=mock"
|
||||
)
|
||||
session = store.get_checkout_session_by_provider_id(body.provider_session_id)
|
||||
if session is None:
|
||||
raise HTTPException(status_code=404, detail="unknown checkout session")
|
||||
try:
|
||||
session_after = await provider.confirm_completion(
|
||||
body.provider_session_id
|
||||
)
|
||||
except ValueError as exc:
|
||||
# G-301 idempotency (the mock's documented contract: the ROUTE
|
||||
# owns it): the provider refuses a re-completion ("not open" —
|
||||
# operator double-click) or lost its in-memory state across a
|
||||
# restart ("unknown session"). The provider's CURRENT view is
|
||||
# authoritative — resolve via retrieve_session and re-run the
|
||||
# REAL webhook path (idempotent per session, G-303); NEVER a
|
||||
# 500 on the payment surface (G-306).
|
||||
recovered = await provider.retrieve_session(body.provider_session_id)
|
||||
if recovered is None:
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=(
|
||||
"the provider no longer knows this session (a restart "
|
||||
"clears mock state) — create a new checkout"
|
||||
),
|
||||
) from exc
|
||||
if recovered.status != "complete":
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
detail=f"session is {recovered.status!r}, not completable",
|
||||
) from exc
|
||||
# Already complete at the provider: fall through with the
|
||||
# recovered truth — the re-minted event re-runs the grant path,
|
||||
# and G-303's per-session exactly-once refuses a second grant.
|
||||
session_after = recovered
|
||||
# Mint + process the signed event through the REAL webhook path
|
||||
# (direct handler call — same code path, G-301's E2E proof).
|
||||
from .billing import process_webhook_event
|
||||
|
||||
raw_body, header, event_id = provider.mint_event(
|
||||
"checkout.completed",
|
||||
{
|
||||
"session_id": body.provider_session_id,
|
||||
"payment_status": session_after.payment_status,
|
||||
},
|
||||
)
|
||||
await process_webhook_event(
|
||||
store=store,
|
||||
provider=provider,
|
||||
raw_body=raw_body,
|
||||
signature_header=header,
|
||||
)
|
||||
return MockCompleteResponse(
|
||||
completed=session_after.status == "complete",
|
||||
payment_status=session_after.payment_status,
|
||||
)
|
||||
|
||||
|
||||
# -- entitlements (Task 4-1-02) ------------------------------------------------
|
||||
|
||||
|
||||
@router.get(
|
||||
"/entitlements/{employer_id}", status_code=200, response_model=EntitlementResponse
|
||||
)
|
||||
def get_entitlement(
|
||||
employer_id: str,
|
||||
store: BillingStore = Depends(get_billing_store),
|
||||
settings: Settings = Depends(require_admin),
|
||||
) -> EntitlementResponse:
|
||||
"""The employer's entitlement state: active package (posts used/
|
||||
limit/expiry — lazy past_due grace per G-306) + subscription."""
|
||||
entitlement = store.get_entitlement(employer_id)
|
||||
return EntitlementResponse(
|
||||
employer_id=entitlement["employer_id"],
|
||||
purchase=entitlement["purchase"],
|
||||
subscription=entitlement["subscription"],
|
||||
)
|
||||
|
||||
|
||||
# -- subscription lifecycle + manual grants + event log (Task 5-1-02) -------------
|
||||
|
||||
|
||||
class LifecycleResponse(BaseModel):
|
||||
"""A provider-backed or manual lifecycle transition result."""
|
||||
|
||||
subscription_id: str
|
||||
status: str
|
||||
provider_action: str | None = None
|
||||
|
||||
|
||||
class ManualGrantRequest(BaseModel):
|
||||
"""D-080's manual path: the operator grants enterprise unlimited
|
||||
posts or a plan on an employer (remediation for failed webhooks —
|
||||
D-083: recorded with provenance)."""
|
||||
|
||||
note: str = ""
|
||||
|
||||
|
||||
@router.post(
|
||||
"/subscriptions/{subscription_id}/cancel",
|
||||
status_code=200,
|
||||
response_model=LifecycleResponse,
|
||||
)
|
||||
async def cancel_subscription(
|
||||
subscription_id: str,
|
||||
request: Request,
|
||||
store: BillingStore = Depends(get_billing_store),
|
||||
settings: Settings = Depends(require_admin),
|
||||
) -> LifecycleResponse:
|
||||
"""Cancel a subscription (R-46): the provider call first (stripe:
|
||||
DELETE / the mock: state-only), then the local transition. Manual
|
||||
cancellation records provenance (D-083)."""
|
||||
subscription = store.get_subscription(subscription_id)
|
||||
if subscription is None:
|
||||
raise HTTPException(status_code=404, detail="unknown subscription")
|
||||
provider_action: str | None = None
|
||||
provider = request.app.state.payment_provider
|
||||
if hasattr(provider, "cancel_subscription"):
|
||||
ref = await provider.cancel_subscription(subscription.provider_subscription_id)
|
||||
provider_action = f"cancel:{ref.status}" if ref else "cancel:unknown"
|
||||
try:
|
||||
updated = store.transition_subscription(subscription_id, "cancelled")
|
||||
except Exception as exc:
|
||||
raise HTTPException(status_code=409, detail=str(exc)) from exc
|
||||
assert updated is not None
|
||||
store.insert_billing_event(
|
||||
"manual",
|
||||
"cancel",
|
||||
employer_id=subscription.employer_id,
|
||||
operator="operator",
|
||||
detail={"subscription_id": subscription_id},
|
||||
)
|
||||
return LifecycleResponse(
|
||||
subscription_id=subscription_id,
|
||||
status=updated.status,
|
||||
provider_action=provider_action,
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/subscriptions/{subscription_id}/resume",
|
||||
status_code=200,
|
||||
response_model=LifecycleResponse,
|
||||
)
|
||||
def resume_subscription(
|
||||
subscription_id: str,
|
||||
store: BillingStore = Depends(get_billing_store),
|
||||
settings: Settings = Depends(require_admin),
|
||||
) -> LifecycleResponse:
|
||||
"""Resume past_due → active (the recovery transition; only the
|
||||
matrix's legal moves — InvalidTransition is the honest 409)."""
|
||||
subscription = store.get_subscription(subscription_id)
|
||||
if subscription is None:
|
||||
raise HTTPException(status_code=404, detail="unknown subscription")
|
||||
try:
|
||||
updated = store.transition_subscription(subscription_id, "active")
|
||||
except Exception as exc:
|
||||
raise HTTPException(status_code=409, detail=str(exc)) from exc
|
||||
assert updated is not None
|
||||
store.insert_billing_event(
|
||||
"manual",
|
||||
"resume",
|
||||
employer_id=subscription.employer_id,
|
||||
operator="operator",
|
||||
detail={"subscription_id": subscription_id},
|
||||
)
|
||||
return LifecycleResponse(subscription_id=subscription_id, status=updated.status)
|
||||
|
||||
|
||||
class UpgradeRequest(BaseModel):
|
||||
plan_id: str = Field(min_length=1)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/subscriptions/{subscription_id}/upgrade",
|
||||
status_code=200,
|
||||
response_model=LifecycleResponse,
|
||||
)
|
||||
async def upgrade_subscription(
|
||||
subscription_id: str,
|
||||
body: UpgradeRequest,
|
||||
request: Request,
|
||||
store: BillingStore = Depends(get_billing_store),
|
||||
settings: Settings = Depends(require_admin),
|
||||
) -> LifecycleResponse:
|
||||
"""G-305: upgrade is a plan_id transition WITHIN active (never a
|
||||
status move); the store records the manual billing_event with
|
||||
provenance. Stripe: the provider's update_subscription resolves
|
||||
items[0][id] inside (R-47 — the dual-charge guard)."""
|
||||
subscription = store.get_subscription(subscription_id)
|
||||
if subscription is None:
|
||||
raise HTTPException(status_code=404, detail="unknown subscription")
|
||||
_package, plan, item = store.get_catalog_item(body.plan_id)
|
||||
if plan is None or item is None:
|
||||
raise HTTPException(status_code=404, detail="unknown plan")
|
||||
provider = request.app.state.payment_provider
|
||||
if hasattr(provider, "update_subscription"):
|
||||
await provider.update_subscription(
|
||||
subscription.provider_subscription_id, int(item["price_cents"])
|
||||
)
|
||||
try:
|
||||
updated = store.upgrade_subscription(
|
||||
subscription_id,
|
||||
body.plan_id,
|
||||
str(item["name"]),
|
||||
int(item["price_cents"]),
|
||||
)
|
||||
except Exception as exc:
|
||||
raise HTTPException(status_code=409, detail=str(exc)) from exc
|
||||
assert updated is not None
|
||||
return LifecycleResponse(
|
||||
subscription_id=subscription_id,
|
||||
status=updated.status,
|
||||
provider_action=f"update:{body.plan_id}",
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/employers/{employer_id}/grant",
|
||||
status_code=201,
|
||||
response_model=EntitlementResponse,
|
||||
)
|
||||
def manual_grant(
|
||||
employer_id: str,
|
||||
request: Request,
|
||||
store: BillingStore = Depends(get_billing_store),
|
||||
settings: Settings = Depends(require_admin),
|
||||
) -> EntitlementResponse:
|
||||
"""D-080's manual unlimited grant (the enterprise path — operator
|
||||
remediation for failed webhooks; D-083: manual provenance in the
|
||||
audit log)."""
|
||||
session_row = store.insert_checkout_session(
|
||||
# Final-review fix: a per-call unique placeholder — a second
|
||||
# grant for the same employer collided on the
|
||||
# provider_session_id UNIQUE constraint (500) where the route
|
||||
# promises idempotent re-grants.
|
||||
provider_session_id=f"cs_manual_{uuid.uuid4().hex[:16]}",
|
||||
employer_id=employer_id,
|
||||
item_id="pkg-enterprise",
|
||||
item_name="Enterprise (manual grant)",
|
||||
price_cents=0,
|
||||
mode="payment",
|
||||
)
|
||||
store.create_purchase_from_session(
|
||||
session_row, posts_limit=None, duration_days=None
|
||||
)
|
||||
store.insert_billing_event(
|
||||
"manual",
|
||||
"grant",
|
||||
employer_id=employer_id,
|
||||
operator="operator",
|
||||
detail={"grant": "unlimited"},
|
||||
)
|
||||
entitlement = store.get_entitlement(employer_id)
|
||||
return EntitlementResponse(
|
||||
employer_id=employer_id,
|
||||
purchase=entitlement["purchase"],
|
||||
subscription=entitlement["subscription"],
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/employers/{employer_id}/revoke",
|
||||
status_code=200,
|
||||
response_model=EntitlementResponse,
|
||||
)
|
||||
def manual_revoke(
|
||||
employer_id: str,
|
||||
store: BillingStore = Depends(get_billing_store),
|
||||
settings: Settings = Depends(require_admin),
|
||||
) -> EntitlementResponse:
|
||||
"""Revoke every purchase grant for the employer (manual remediation
|
||||
— the inverse of the grant; provenance recorded)."""
|
||||
from sqlalchemy import text as _text
|
||||
from sqlmodel import Session as _Session
|
||||
|
||||
# Final-review fix: bind a NAIVE utcnow — the same format the ORM's
|
||||
# sqlite DATETIME processor writes. The old aware bind (+00:00
|
||||
# suffix) left mixed-format TEXT in the column; comparisons stayed
|
||||
# correct in practice (ISO prefix ordering) but the column held two
|
||||
# spellings of the same field. One format, one discipline.
|
||||
with _Session(store._engine) as session: # type: ignore[attr-defined]
|
||||
session.execute(
|
||||
_text(
|
||||
"UPDATE billing_purchases SET expires_at = :past "
|
||||
"WHERE employer_id = :employer_id"
|
||||
),
|
||||
{
|
||||
"past": _utc_now_minus_day().replace(tzinfo=None),
|
||||
"employer_id": employer_id,
|
||||
},
|
||||
)
|
||||
session.commit()
|
||||
store.insert_billing_event(
|
||||
"manual",
|
||||
"revoke",
|
||||
employer_id=employer_id,
|
||||
operator="operator",
|
||||
detail={"revoke": "all purchases"},
|
||||
)
|
||||
entitlement = store.get_entitlement(employer_id)
|
||||
return EntitlementResponse(
|
||||
employer_id=employer_id,
|
||||
purchase=entitlement["purchase"],
|
||||
subscription=entitlement["subscription"],
|
||||
)
|
||||
|
||||
|
||||
def _utc_now_minus_day():
|
||||
"""Naive-UTC (matches the ORM's sqlite DATETIME storage format —
|
||||
see the revoke route's binding note)."""
|
||||
from datetime import UTC, datetime, timedelta
|
||||
|
||||
return datetime.now(UTC).replace(tzinfo=None) - timedelta(days=1)
|
||||
|
||||
|
||||
class BillingEventRow_(BaseModel):
|
||||
"""The audit-trail wire row (REQ-9-005's queryable log)."""
|
||||
|
||||
id: int
|
||||
employer_id: str | None
|
||||
kind: str
|
||||
name: str
|
||||
detail: dict[str, object]
|
||||
operator: str | None
|
||||
created_at: str | None
|
||||
|
||||
|
||||
class BillingEventListResponse(BaseModel):
|
||||
events: list[BillingEventRow_]
|
||||
count: int
|
||||
|
||||
|
||||
@router.get(
|
||||
"/events", status_code=200, response_model=BillingEventListResponse
|
||||
)
|
||||
def list_events(
|
||||
employer_id: str | None = None,
|
||||
kind: str | None = None,
|
||||
name: str | None = None,
|
||||
limit: int = 100,
|
||||
store: BillingStore = Depends(get_billing_store),
|
||||
settings: Settings = Depends(require_admin),
|
||||
) -> BillingEventListResponse:
|
||||
"""The billing event log (REQ-9-005): every provider event, manual
|
||||
action (with operator provenance), and unmatched delivery —
|
||||
filterable by employer/kind/name."""
|
||||
rows = store.list_billing_events(
|
||||
employer_id=employer_id, kind=kind, name=name, limit=limit
|
||||
)
|
||||
return BillingEventListResponse(
|
||||
events=[
|
||||
BillingEventRow_(
|
||||
id=r.id or 0,
|
||||
employer_id=r.employer_id,
|
||||
kind=r.kind,
|
||||
name=r.name,
|
||||
detail=dict(r.detail),
|
||||
operator=r.operator,
|
||||
created_at=r.created_at.isoformat() if r.created_at else None,
|
||||
)
|
||||
for r in rows
|
||||
],
|
||||
count=len(rows),
|
||||
)
|
||||
@@ -42,7 +42,7 @@ from .deps import (
|
||||
get_voice_provider,
|
||||
get_voice_store,
|
||||
)
|
||||
from .identity import require_verified_age # noqa: E402 (gate dep, D-043)
|
||||
from .identity import require_verified_age
|
||||
|
||||
router = APIRouter(prefix="/v1/defense", tags=["defense"])
|
||||
|
||||
@@ -212,6 +212,14 @@ async def answer_defense(
|
||||
if audio is not None:
|
||||
stt_started = time.perf_counter()
|
||||
raw = await audio.read()
|
||||
# P3 (Task 3-2-01): the upload is fully consumed into memory —
|
||||
# no streaming path exists (G-107), so close the spooled file
|
||||
# HERE, before any guard below can raise (422 empty / 413
|
||||
# oversize / 502 provider all operate on `raw` only). FastAPI's
|
||||
# request-end file stack would also close it — close() is
|
||||
# idempotent on the spooled file — but the route must not rely
|
||||
# on GC-timing cleanup.
|
||||
await audio.close()
|
||||
if not raw:
|
||||
# Empty upload is a client error (422), not a provider crash
|
||||
# (500): validate before the provider call so every provider
|
||||
|
||||
@@ -5,12 +5,15 @@ from fastapi import Request
|
||||
from ..agents.examiner import ExaminerAgent
|
||||
from ..agents.registry import AgentRegistry
|
||||
from ..agents.session import SessionStore
|
||||
from ..billing.store import BillingStore
|
||||
from ..config import Settings
|
||||
from ..employers.store import EmployerStore
|
||||
from ..grading.engine import GradingEngine
|
||||
from ..grading.store import GradeStore
|
||||
from ..llm.base import LLMProvider
|
||||
from ..marketplace.embedding.base import EmbeddingProvider
|
||||
from ..marketplace.store import MarketplaceStore
|
||||
from ..placements.store import PlacementStore
|
||||
from ..sandbox.manager import SandboxManager
|
||||
from ..sandbox.workdir import SandboxDir
|
||||
from ..telemetry.ingest import TraceIntegrityMap
|
||||
@@ -87,6 +90,25 @@ def get_marketplace_store(request: Request) -> MarketplaceStore:
|
||||
return request.app.state.marketplace_store
|
||||
|
||||
|
||||
def get_billing_store(request: Request) -> BillingStore:
|
||||
"""v0.9 billing (D-080): the same app.state DI territory rule —
|
||||
billing routes compose the store, never import it."""
|
||||
return request.app.state.billing_store
|
||||
|
||||
|
||||
def get_employer_store(request: Request) -> EmployerStore:
|
||||
"""v0.10 employers (D-087): the same app.state DI territory rule —
|
||||
employer routes compose the store via app.state, never import it."""
|
||||
return request.app.state.employer_store
|
||||
|
||||
|
||||
def get_placement_store(request: Request) -> PlacementStore:
|
||||
"""v0.11 placements (D-100/D-112): the same app.state DI territory
|
||||
rule — placement routes compose the store via app.state, never
|
||||
import it."""
|
||||
return request.app.state.placement_store
|
||||
|
||||
|
||||
def get_embedding_provider(request: Request) -> EmbeddingProvider:
|
||||
"""v0.6 P3 (D-051): the embedding port via app.state DI — the
|
||||
search route + publish hooks compose it, never import it."""
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,287 @@
|
||||
"""/v1/employers/admin — employer claim operator surface (REQ-10-002, D-089/D-094).
|
||||
|
||||
Every route sits behind `require_admin` IMPORTED from
|
||||
marketplace_admin (the billing_admin.py:27 precedent, D-094 — one
|
||||
guard, never reimplemented): fail-closed 403 on no/missing/invalid
|
||||
token — the R-56 matrix; an UNSET AI_ADMIN_TOKEN 403s every route
|
||||
even with a candidate (the main.py boot warning covers the config
|
||||
class). Operator routes compose NO learner gate (D-097) and no
|
||||
employer-session gate — a different principal class, and the token
|
||||
namespaces cannot collide (this gate compares bytes; the session
|
||||
gate hash-looks-up — D-090).
|
||||
|
||||
D-089: evidence is ADVISORY — the queue returns the stored claim-time
|
||||
provenance snapshot as-is; approval is the EXPLICIT operator decision
|
||||
(auto-approval deferred: without email verification the match is
|
||||
forgeable, A-304 — never present unverified as verified). Every
|
||||
decision appends an employer_audit_events row with operator
|
||||
provenance in the SAME transaction as the claim update (decide_claim
|
||||
— all-or-nothing). The accounts wire contract carries NO password_hash
|
||||
(hash-at-rest, D-087 — never returned anywhere).
|
||||
|
||||
409 discipline (the decide arms' honest constraint 409s — details
|
||||
carry constraint names only, never account identifiers):
|
||||
- claim not pending (decided twice) → "claim is already decided"
|
||||
- the deciding account already holds an entity (the one-account-
|
||||
one-entity guard) → "the claim's account already holds an employer
|
||||
entity"
|
||||
- the entity already owned (the employer_accounts.employer_id UNIQUE
|
||||
surfacing on the approve flush) → "the employer entity is already
|
||||
owned" — surfaced, NEVER silently overwritten.
|
||||
Any OTHER IntegrityError re-raises (a 500) — never mask an unknown
|
||||
constraint violation as a decision.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Annotated, Literal
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from ..config import Settings
|
||||
from ..employers.base import EmployerClaim
|
||||
from ..employers.store import ClaimRow, EmployerStore
|
||||
from .deps import get_employer_store
|
||||
from .marketplace_admin import require_admin
|
||||
|
||||
router = APIRouter(prefix="/v1/employers/admin", tags=["employers-admin"])
|
||||
|
||||
#: Operator provenance stamped on every decision + audit event (the
|
||||
#: billing_admin "operator" precedent — route-level provenance; no
|
||||
#: per-operator accounts exist at pilot, D-094).
|
||||
OPERATOR = "operator"
|
||||
|
||||
|
||||
# -- contracts ----------------------------------------------------------------
|
||||
|
||||
|
||||
class AdminEmployerAccount(BaseModel):
|
||||
"""The accounts-list wire row (D-094): email, claimed entity,
|
||||
created_at, the UNVERIFIED marker. `email_verified` is
|
||||
`Literal[False]` (D-097 — structurally incapable of True: no email
|
||||
verification exists in v0.10, so the field can never carry it).
|
||||
password_hash is NEVER on the wire (D-087)."""
|
||||
|
||||
id: str
|
||||
email: str
|
||||
employer_id: str | None
|
||||
created_at: str
|
||||
#: D-097: the account is UNVERIFIED — displayed as such, never as
|
||||
#: verified (A-304's doctrine applied to the account surface).
|
||||
email_verified: Literal[False] = False
|
||||
|
||||
|
||||
class AdminAccountsResponse(BaseModel):
|
||||
accounts: list[AdminEmployerAccount]
|
||||
count: int
|
||||
|
||||
|
||||
class AdminClaimsResponse(BaseModel):
|
||||
"""The claim queue (D-089): status, the stored claim-time evidence
|
||||
snapshot — the domain-match signal rides evidence["match"],
|
||||
ADVISORY, never a verification — and the decided state
|
||||
(decided_by/decided_at, None while pending)."""
|
||||
|
||||
claims: list[EmployerClaim]
|
||||
count: int
|
||||
|
||||
|
||||
class ClaimDecisionResponse(BaseModel):
|
||||
"""The decided claim (status approved/rejected + operator
|
||||
provenance) — either decision arm returns the same shape."""
|
||||
|
||||
claim: EmployerClaim
|
||||
|
||||
|
||||
class AdminAuditEvent(BaseModel):
|
||||
"""The audit-trail wire row (D-089's queryable operator trail —
|
||||
the BillingEventRow_ shape, billing_admin.py:488)."""
|
||||
|
||||
id: int
|
||||
account_id: str | None
|
||||
employer_id: str | None
|
||||
kind: str
|
||||
name: str
|
||||
detail: dict[str, object]
|
||||
operator: str | None
|
||||
created_at: str | None
|
||||
|
||||
|
||||
class AdminAuditResponse(BaseModel):
|
||||
events: list[AdminAuditEvent]
|
||||
count: int
|
||||
|
||||
|
||||
def _claim_to_contract(row: ClaimRow) -> EmployerClaim:
|
||||
"""Store row → wire contract (created_at is always set on a row
|
||||
the store returned — insert/decide stamp it)."""
|
||||
assert row.created_at is not None # the store always stamps it
|
||||
return EmployerClaim(
|
||||
id=row.id,
|
||||
account_id=row.account_id,
|
||||
employer_id=row.employer_id,
|
||||
status=row.status, # type: ignore[arg-type]
|
||||
evidence=dict(row.evidence or {}),
|
||||
created_at=row.created_at,
|
||||
decided_by=row.decided_by,
|
||||
decided_at=row.decided_at,
|
||||
)
|
||||
|
||||
|
||||
# -- queue reads (D-094) ---------------------------------------------------------
|
||||
|
||||
|
||||
@router.get("/accounts", response_model=AdminAccountsResponse)
|
||||
def list_accounts(
|
||||
store: Annotated[EmployerStore, Depends(get_employer_store)],
|
||||
settings: Annotated[Settings, Depends(require_admin)],
|
||||
) -> AdminAccountsResponse:
|
||||
"""The accounts list: email, claimed entity, created_at, and the
|
||||
UNVERIFIED marker (D-097 — account emails are unverified and
|
||||
displayed as such; a claimed entity column shows the APPROVED
|
||||
ownership binding, never account verification)."""
|
||||
rows = store.list_accounts()
|
||||
return AdminAccountsResponse(
|
||||
accounts=[
|
||||
AdminEmployerAccount(
|
||||
id=account.id,
|
||||
email=account.email,
|
||||
employer_id=account.employer_id,
|
||||
created_at=account.created_at.isoformat() if account.created_at else "",
|
||||
email_verified=False, # D-097: UNVERIFIED, always False
|
||||
)
|
||||
for account in rows
|
||||
],
|
||||
count=len(rows),
|
||||
)
|
||||
|
||||
|
||||
@router.get("/claims", response_model=AdminClaimsResponse)
|
||||
def list_claims(
|
||||
store: Annotated[EmployerStore, Depends(get_employer_store)],
|
||||
settings: Annotated[Settings, Depends(require_admin)],
|
||||
status: str | None = None,
|
||||
) -> AdminClaimsResponse:
|
||||
"""The claim queue: status, the stored evidence snapshot (the
|
||||
domain-match signal is ADVISORY — the signal informs, the operator
|
||||
decides; match=false is the example.com corpus norm, R-65), and
|
||||
the decided state. Optional ?status= facet (the admin queue's
|
||||
consume-free read path)."""
|
||||
rows = store.list_claims(status=status)
|
||||
return AdminClaimsResponse(
|
||||
claims=[_claim_to_contract(row) for row in rows],
|
||||
count=len(rows),
|
||||
)
|
||||
|
||||
|
||||
# -- decisions (D-089 — the explicit operator action) ----------------------------
|
||||
|
||||
|
||||
def _decide(store: EmployerStore, claim_id: str, decision: str) -> EmployerClaim:
|
||||
"""The shared decide path: unknown claim → 404; the store's guard
|
||||
arms + the employer_accounts.employer_id UNIQUE surface as the
|
||||
honest 409s (constraint names only — never account identifiers);
|
||||
decide_claim appends the operator audit event in the SAME
|
||||
transaction as the decision."""
|
||||
try:
|
||||
row = store.decide_claim(claim_id, decision=decision, operator=OPERATOR)
|
||||
except IntegrityError as exc:
|
||||
message = str(getattr(exc, "orig", exc))
|
||||
if "employer_accounts.employer_id already set" in message:
|
||||
# decide_claim's account-already-owner guard — the
|
||||
# one-account-one-entity arm, hand-raised by the store.
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
detail=("the claim's account already holds an employer entity"),
|
||||
) from None
|
||||
if "UNIQUE constraint failed: employer_accounts.employer_id" in (message):
|
||||
# The approve flush refused: a DIFFERENT account already
|
||||
# owns the entity — surfaced, never silently overwritten.
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
detail="the employer entity is already owned",
|
||||
) from None
|
||||
if "is already" in message:
|
||||
# decide_claim's not-pending guard — deciding a decided
|
||||
# claim, the IntegrityError shape (the honest 409).
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
detail="claim is already decided",
|
||||
) from None
|
||||
# Unmapped IntegrityError — re-raise (a 500): never mask an
|
||||
# unknown constraint violation as a decision.
|
||||
raise
|
||||
if row is None:
|
||||
raise HTTPException(status_code=404, detail="unknown claim")
|
||||
return _claim_to_contract(row)
|
||||
|
||||
|
||||
@router.post("/claims/{claim_id}/approve", response_model=ClaimDecisionResponse)
|
||||
def approve_claim(
|
||||
claim_id: str,
|
||||
store: Annotated[EmployerStore, Depends(get_employer_store)],
|
||||
settings: Annotated[Settings, Depends(require_admin)],
|
||||
) -> ClaimDecisionResponse:
|
||||
"""Approve → the claim's account.employer_id is set (one account :
|
||||
one entity — the UNIQUE activates) + decided_by/decided_at + the
|
||||
operator audit event, all in one transaction. Evidence never
|
||||
auto-activates anything: the operator decision is the action."""
|
||||
row = _decide(store, claim_id, "approved")
|
||||
return ClaimDecisionResponse(claim=row)
|
||||
|
||||
|
||||
@router.post("/claims/{claim_id}/reject", response_model=ClaimDecisionResponse)
|
||||
def reject_claim(
|
||||
claim_id: str,
|
||||
store: Annotated[EmployerStore, Depends(get_employer_store)],
|
||||
settings: Annotated[Settings, Depends(require_admin)],
|
||||
) -> ClaimDecisionResponse:
|
||||
"""Reject → decided_by/decided_at + the operator audit event (same
|
||||
transaction); the entity is FREED for a new claim (the partial
|
||||
pending index never touches rejected rows, G-316)."""
|
||||
row = _decide(store, claim_id, "rejected")
|
||||
return ClaimDecisionResponse(claim=row)
|
||||
|
||||
|
||||
# -- audit trail (D-089's queryable operator trail) ------------------------------
|
||||
|
||||
|
||||
@router.get("/audit", response_model=AdminAuditResponse)
|
||||
def list_audit(
|
||||
store: Annotated[EmployerStore, Depends(get_employer_store)],
|
||||
settings: Annotated[Settings, Depends(require_admin)],
|
||||
account_id: str | None = None,
|
||||
employer_id: str | None = None,
|
||||
kind: str | None = None,
|
||||
name: str | None = None,
|
||||
limit: int = 100,
|
||||
) -> AdminAuditResponse:
|
||||
"""The queryable audit trail: every auth/claim event with operator
|
||||
provenance — the claim.submitted/claim.approved/claim.rejected
|
||||
names; decided_by/decided_at ride the claim rows the decision
|
||||
events reference (detail.claim_id joins them)."""
|
||||
rows = store.list_audit_events(
|
||||
account_id=account_id,
|
||||
employer_id=employer_id,
|
||||
kind=kind,
|
||||
name=name,
|
||||
limit=limit,
|
||||
)
|
||||
return AdminAuditResponse(
|
||||
events=[
|
||||
AdminAuditEvent(
|
||||
id=event.id or 0,
|
||||
account_id=event.account_id,
|
||||
employer_id=event.employer_id,
|
||||
kind=event.kind,
|
||||
name=event.name,
|
||||
detail=dict(event.detail or {}),
|
||||
operator=event.operator,
|
||||
created_at=event.created_at.isoformat() if event.created_at else None,
|
||||
)
|
||||
for event in rows
|
||||
],
|
||||
count=len(rows),
|
||||
)
|
||||
@@ -0,0 +1,99 @@
|
||||
"""The D-091 shared posting-entitlement gate (REQ-10-004, R-58).
|
||||
|
||||
ONE helper, TWO principal gates: the admin create route (v0.9,
|
||||
marketplace_admin) and the employer create route (v0.10 Task 4-1-02)
|
||||
both compose THIS — never a re-implemented copy (the no-drift shape;
|
||||
extraction is the only way "the exact v0.9 check parameterized" holds).
|
||||
The helper lives in api/ beside both callers — no billing/→api/
|
||||
boundary violation (billing/ stays ignorant of routes, D-027/D-048).
|
||||
|
||||
Wire contract (R-58 — byte-stable, D-080/D-084): the 402 detail dict is
|
||||
{reason, posts_used: 0, posts_limit: 0, upgrade_cta} with posts_used and
|
||||
posts_limit HARDCODED 0 in BOTH arms. The zeros are the v0.9 wire shape
|
||||
the web client's UpgradeRequiredError ignores (it consumes reason +
|
||||
upgrade_cta only, apps/web/lib/engine-client.ts) — do NOT "improve" them
|
||||
into live counts; the payload-parity test pins the bytes.
|
||||
|
||||
Edge ordering (mirrors the extracted v0.9 gate exactly):
|
||||
1. store-missing (None) → 503 fail-closed BEFORE any consume attempt —
|
||||
a payment gate never silently skips (the final-review fix).
|
||||
2. consume_posting → NoActivePackage → the no_active_package 402 arm.
|
||||
3. consume_posting → PackageExhausted → the posting_limit_reached arm.
|
||||
The gate runs BEFORE the caller's insert — a 402 consumes nothing,
|
||||
creates nothing. `consume_posting` itself (G-304 single conditional
|
||||
UPDATE) is untouched; this helper only maps its exceptions to the
|
||||
honest 402 arms.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import HTTPException
|
||||
|
||||
from ..billing.store import BillingStore, NoActivePackage, PackageExhausted
|
||||
|
||||
|
||||
def consume_posting_entitlement(
|
||||
store: BillingStore | None,
|
||||
employer_id: str,
|
||||
upgrade_cta: str,
|
||||
) -> None:
|
||||
"""Spend one posting post for `employer_id`, or raise the honest 402.
|
||||
|
||||
Args:
|
||||
store: the billing store from app.state (None = a wiring miss →
|
||||
503 fail-closed — posting creation is refused until the
|
||||
service is restarted, never an ungated insert).
|
||||
employer_id: the entity whose package is charged.
|
||||
upgrade_cta: the caller-principal's checkout pointer
|
||||
("/v1/billing/admin/checkout" from the admin route; the
|
||||
employer route passes its own) — interpolated into the two
|
||||
FIXED per-arm sentences, so the rendered upgrade_cta field
|
||||
differs per principal while reason/posts_used/posts_limit
|
||||
stay byte-identical across both gates (the D-091 parity).
|
||||
|
||||
Raises:
|
||||
HTTPException 503: the store is missing (fail-closed).
|
||||
HTTPException 402: no active package / all posts spent — the
|
||||
canonical dict payload (hardcoded zeros, R-58).
|
||||
"""
|
||||
if store is None:
|
||||
raise HTTPException(
|
||||
status_code=503,
|
||||
detail=(
|
||||
"billing entitlement store is unavailable — posting "
|
||||
"creation is refused until the service is restarted "
|
||||
"(the store wires at boot)"
|
||||
),
|
||||
)
|
||||
try:
|
||||
store.consume_posting(employer_id)
|
||||
except NoActivePackage:
|
||||
raise HTTPException(
|
||||
status_code=402,
|
||||
detail={
|
||||
"reason": "no_active_package",
|
||||
# R-58: hardcoded zeros — the wire contract, never live
|
||||
# counts (real limits render only from the entitlement
|
||||
# view; the client's UpgradeRequiredError consumes
|
||||
# reason + upgrade_cta alone).
|
||||
"posts_used": 0,
|
||||
"posts_limit": 0,
|
||||
"upgrade_cta": (
|
||||
"This employer has no active posting package — "
|
||||
f"purchase one via {upgrade_cta}."
|
||||
),
|
||||
},
|
||||
) from None
|
||||
except PackageExhausted:
|
||||
raise HTTPException(
|
||||
status_code=402,
|
||||
detail={
|
||||
"reason": "posting_limit_reached",
|
||||
"posts_used": 0,
|
||||
"posts_limit": 0,
|
||||
"upgrade_cta": (
|
||||
"This employer's posting package is exhausted — "
|
||||
f"buy more posts or upgrade via {upgrade_cta}."
|
||||
),
|
||||
},
|
||||
) from None
|
||||
@@ -9,11 +9,13 @@ D-016 envelope with agent=lab.
|
||||
|
||||
import json
|
||||
from collections.abc import AsyncIterator
|
||||
from typing import cast
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
from pydantic import BaseModel, Field
|
||||
from sse_starlette.sse import EventSourceResponse
|
||||
|
||||
from ..agents.lab import LabAgent
|
||||
from ..agents.registry import AgentRegistry
|
||||
from ..config import Settings
|
||||
from ..corpus.learner_context import get_learner_context
|
||||
@@ -41,7 +43,9 @@ async def lab_feedback(
|
||||
provider=Depends(get_provider),
|
||||
trace_store=Depends(get_trace_store),
|
||||
) -> EventSourceResponse:
|
||||
agent = registry.get(provider, settings, "lab")
|
||||
# P5: registry.get returns BaseAgent; "lab" is registered as LabAgent
|
||||
# (register_builtin_agents) — the cast states that mapping.
|
||||
agent = cast(LabAgent, registry.get(provider, settings, "lab"))
|
||||
learner_context = get_learner_context(body.learner_id)
|
||||
trace = (
|
||||
trace_store.get_trace(body.learner_id, body.task_id)
|
||||
|
||||
@@ -16,16 +16,34 @@ from __future__ import annotations
|
||||
|
||||
import time
|
||||
from collections import deque
|
||||
from datetime import date
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Request
|
||||
from pydantic import BaseModel, Field
|
||||
from pydantic import BaseModel, Field, ValidationError
|
||||
|
||||
from ..config import Settings
|
||||
from ..identity.store import IdentityStore
|
||||
from ..marketplace.base import Employer, Posting
|
||||
from ..marketplace.embedding.base import EmbeddingProvider
|
||||
from ..marketplace.enrichment import merge_employer
|
||||
from ..marketplace.resume import (
|
||||
MAX_RESUME_BYTES,
|
||||
ParsedProfile,
|
||||
ResumeFormatError,
|
||||
extract_resume_text,
|
||||
parse_resume,
|
||||
)
|
||||
from ..marketplace.search import FacetFilters, rank_postings
|
||||
from .deps import get_embedding_provider, get_marketplace_store, get_settings
|
||||
from ..placements.base import (
|
||||
InvalidTransition,
|
||||
LearnerApplicationStatusResponse,
|
||||
LearnerApplicationSummary,
|
||||
MineApplicationResponse,
|
||||
PlacementEventRead,
|
||||
PlacementRead,
|
||||
)
|
||||
from ..placements.store import PlacementRow
|
||||
from .deps import get_embedding_provider, get_marketplace_store, get_provider, get_settings
|
||||
from .identity import require_verified_age
|
||||
|
||||
router = APIRouter(prefix="/v1/marketplace", tags=["marketplace"])
|
||||
@@ -106,9 +124,18 @@ class PostingListResponse(BaseModel):
|
||||
facets: dict
|
||||
|
||||
|
||||
class ProvenanceField(BaseModel):
|
||||
"""P4-A (D-053/A-304): one merged employer field with its honest
|
||||
provenance — raw | llm | manual (+ the model that wrote llm copy)."""
|
||||
|
||||
value: object
|
||||
source: str
|
||||
model: str | None = None
|
||||
|
||||
|
||||
class EmployerResponse(BaseModel):
|
||||
"""Raw ingested fields (P1). P4 (D-053) merges enrichment on read and
|
||||
adds per-field {value, source} provenance markers."""
|
||||
"""Raw ingested fields (P1) + the P4-A `merged` section: per-field
|
||||
provenance-marked view (manual > llm > raw on read, D-053)."""
|
||||
|
||||
id: str
|
||||
source: str
|
||||
@@ -122,6 +149,7 @@ class EmployerResponse(BaseModel):
|
||||
website: str
|
||||
social_links: dict[str, str]
|
||||
culture: str
|
||||
merged: dict[str, ProvenanceField] | None = None
|
||||
|
||||
|
||||
class SkillBreakdownEntry(BaseModel):
|
||||
@@ -189,7 +217,9 @@ def _posting_response(posting: Posting) -> PostingResponse:
|
||||
)
|
||||
|
||||
|
||||
def _employer_response(employer: Employer) -> EmployerResponse:
|
||||
def _employer_response(
|
||||
employer: Employer, merged: dict[str, ProvenanceField] | None = None
|
||||
) -> EmployerResponse:
|
||||
return EmployerResponse(
|
||||
id=employer.id,
|
||||
source=employer.source,
|
||||
@@ -203,6 +233,7 @@ def _employer_response(employer: Employer) -> EmployerResponse:
|
||||
website=employer.website,
|
||||
social_links=dict(employer.social_links),
|
||||
culture=employer.culture,
|
||||
merged=merged,
|
||||
)
|
||||
|
||||
|
||||
@@ -262,7 +293,11 @@ async def search_postings(
|
||||
SearchEntry(
|
||||
posting=_posting_response(r.posting),
|
||||
match_score=round(r.score, 6) if has_query else None,
|
||||
skill_breakdown=r.skill_breakdown if has_query else [],
|
||||
# P5 scoped: search.skill_breakdown() yields raw dicts in the
|
||||
# exact entry shape (marketplace/ may not import api/ models —
|
||||
# D-048 boundary); pydantic coerces them into
|
||||
# SkillBreakdownEntry at this SearchEntry boundary.
|
||||
skill_breakdown=r.skill_breakdown if has_query else [], # type: ignore[arg-type]
|
||||
)
|
||||
for r in ranked
|
||||
],
|
||||
@@ -290,14 +325,28 @@ async def get_employer(
|
||||
employer_id: str,
|
||||
store=Depends(get_marketplace_store),
|
||||
) -> EmployerResponse:
|
||||
"""Honest 404 on unknown employers; raw fields in P1 (merged +
|
||||
provenance in P4, D-053)."""
|
||||
"""Honest 404 on unknown employers. Raw fields stay as-is; the P4-A
|
||||
`merged` section carries the per-field provenance view (manual >
|
||||
llm > raw, D-053/A-304 — LLM copy is visibly marked, never
|
||||
displayed as ingested fact)."""
|
||||
employer = store.get_employer(employer_id)
|
||||
if employer is None:
|
||||
raise HTTPException(
|
||||
status_code=404, detail=f"no employer with id {employer_id!r}"
|
||||
)
|
||||
return _employer_response(employer)
|
||||
rows = store.list_enrichment(employer_id)
|
||||
merged_raw = merge_employer(employer, rows) if rows else None
|
||||
merged = (
|
||||
{
|
||||
field: ProvenanceField(
|
||||
value=entry["value"], source=entry["source"], model=entry["model"]
|
||||
)
|
||||
for field, entry in merged_raw.items()
|
||||
}
|
||||
if merged_raw
|
||||
else None
|
||||
)
|
||||
return _employer_response(employer, merged=merged)
|
||||
|
||||
|
||||
# -- the real apply route (D-058; the G-18 stub's replacement) ------------------
|
||||
@@ -336,8 +385,346 @@ async def apply_posting(
|
||||
application, _created = store.insert_application(
|
||||
posting_id=body.posting_id, learner_id=body.learner_id
|
||||
)
|
||||
# G-323 (binding): the idempotent arm NEVER confirms a terminal
|
||||
# application — a withdrawn/rejected/hired row returns 409 (the
|
||||
# learner is told the honest state; recovery is visibility via the
|
||||
# application-status surface, not resurrection — no second row is
|
||||
# ever created; the (posting_id, learner_id) unique key stands).
|
||||
if application.status in ("withdrawn", "rejected", "hired"):
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
detail={
|
||||
"reason": "application_terminal",
|
||||
"status": application.status,
|
||||
},
|
||||
)
|
||||
return ApplyResponse(
|
||||
application_id=application.id,
|
||||
posting_id=application.posting_id,
|
||||
status=application.status,
|
||||
)
|
||||
|
||||
|
||||
# -- v0.11 P2: the learner withdraw route (D-104, REQ-11-002) --------------------
|
||||
|
||||
|
||||
class WithdrawBody(BaseModel):
|
||||
"""D-104: the pilot surface passes learner_id in the body (the G-5
|
||||
composition unchanged — the SAME stack as apply)."""
|
||||
|
||||
learner_id: str = Field(min_length=1)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/applications/{application_id}/withdraw", response_model=ApplyResponse
|
||||
)
|
||||
async def withdraw_application(
|
||||
application_id: str,
|
||||
body: WithdrawBody,
|
||||
request: Request,
|
||||
store=Depends(get_marketplace_store),
|
||||
settings: Settings = Depends(get_settings),
|
||||
) -> ApplyResponse:
|
||||
"""The learner's ONLY edit (D-099: withdrawn is learner- or
|
||||
operator-triggerable, NEVER an employer session). The D-043
|
||||
composition UNCHANGED: G-5 allowlist → verified 18+ → the EXISTING
|
||||
apply-rate window (no new throttle knob, D-088 scope untouched).
|
||||
Own application only (403 foreign); terminal → 409 (the matrix).
|
||||
"""
|
||||
_enforce_allowlist(body.learner_id, settings)
|
||||
await require_verified_age(18, body.learner_id, _identity_store(request))
|
||||
_check_apply_rate(body.learner_id)
|
||||
|
||||
application = store.get_application(application_id)
|
||||
if application is None:
|
||||
raise HTTPException(
|
||||
status_code=404, detail=f"no application with id {application_id!r}"
|
||||
)
|
||||
if application.learner_id != body.learner_id:
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="this application belongs to another learner",
|
||||
)
|
||||
from .deps import get_placement_store # local import — the territory rule
|
||||
|
||||
placements = get_placement_store(request)
|
||||
try:
|
||||
application, _placement = placements.transition_application(
|
||||
application_id,
|
||||
"withdrawn",
|
||||
actor_type="learner",
|
||||
actor_ref=f"learner:{body.learner_id}",
|
||||
)
|
||||
except InvalidTransition as exc:
|
||||
raise HTTPException(status_code=409, detail=str(exc)) from exc
|
||||
return ApplyResponse(
|
||||
application_id=application.id,
|
||||
posting_id=application.posting_id,
|
||||
status=application.status,
|
||||
)
|
||||
|
||||
|
||||
# -- v0.11 P5: the learner status reads (D-104/G-322, REQ-11-005) -------------------
|
||||
|
||||
|
||||
def _placement_read(row: PlacementRow) -> PlacementRead:
|
||||
"""The PlacementRow → PlacementRead conversion (the placements_admin
|
||||
helper mirrored — each route file owns its readers; start_date is
|
||||
the ISO DATE string on the row, a date on the wire, D-103)."""
|
||||
return PlacementRead(
|
||||
id=row.id,
|
||||
learner_id=row.learner_id,
|
||||
employer_id=row.employer_id,
|
||||
posting_id=row.posting_id,
|
||||
application_id=row.application_id,
|
||||
role_title=row.role_title,
|
||||
start_date=date.fromisoformat(row.start_date),
|
||||
status=row.status, # type: ignore[arg-type]
|
||||
created_at=row.created_at or _now(),
|
||||
decided_at=row.decided_at or _now(),
|
||||
)
|
||||
|
||||
|
||||
def _now():
|
||||
from datetime import UTC, datetime
|
||||
|
||||
return datetime.now(UTC)
|
||||
|
||||
|
||||
@router.get("/applications/mine", response_model=MineApplicationResponse)
|
||||
async def mine_application(
|
||||
request: Request,
|
||||
posting_id: str = Query(min_length=1),
|
||||
learner_id: str = Query(min_length=1),
|
||||
store=Depends(get_marketplace_store),
|
||||
settings: Settings = Depends(get_settings),
|
||||
) -> MineApplicationResponse:
|
||||
"""G-322 (binding): the mine point-read — the status panel's
|
||||
application DISCOVERY on revisit (the panel NEVER depends on
|
||||
client-persisted application_ids). Gate composition: G-5 allowlist
|
||||
→ verified 18+ (reads are free — the apply-rate window is the
|
||||
WRITE budget, A-408's distinct-action rule; no new throttle knob,
|
||||
D-088 untouched); no row → the honest 404 (the surface renders the
|
||||
apply CTA)."""
|
||||
_enforce_allowlist(learner_id, settings)
|
||||
await require_verified_age(18, learner_id, _identity_store(request))
|
||||
|
||||
application = store.get_application_by_posting_learner(posting_id, learner_id)
|
||||
if application is None:
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=f"no application by this learner on posting {posting_id!r}",
|
||||
)
|
||||
return MineApplicationResponse(
|
||||
application_id=application.id,
|
||||
status=application.status,
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/applications/{application_id}",
|
||||
response_model=LearnerApplicationStatusResponse,
|
||||
)
|
||||
async def learner_application_status(
|
||||
application_id: str,
|
||||
request: Request,
|
||||
learner_id: str = Query(min_length=1),
|
||||
store=Depends(get_marketplace_store),
|
||||
settings: Settings = Depends(get_settings),
|
||||
) -> LearnerApplicationStatusResponse:
|
||||
"""D-104 (REQ-11-005): the learner's-own outcome read — current
|
||||
status + the FULL id-ordered timestamped history for THIS
|
||||
application + the placement record when hired (one read, one
|
||||
truth source). Same gates as the mine-read (reads are free);
|
||||
foreign learner_id → 403 (the scoped query never renders another
|
||||
learner's events); unknown → 404."""
|
||||
_enforce_allowlist(learner_id, settings)
|
||||
await require_verified_age(18, learner_id, _identity_store(request))
|
||||
|
||||
application = store.get_application(application_id)
|
||||
if application is None:
|
||||
raise HTTPException(
|
||||
status_code=404, detail=f"no application with id {application_id!r}"
|
||||
)
|
||||
if application.learner_id != learner_id:
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail="this application belongs to another learner",
|
||||
)
|
||||
from .deps import get_placement_store # local import — the territory rule
|
||||
|
||||
placements = get_placement_store(request)
|
||||
events = [
|
||||
PlacementEventRead.model_validate(event, from_attributes=True)
|
||||
for event in placements.get_application_events(application_id)
|
||||
]
|
||||
row = placements.get_placement_by_application(application_id)
|
||||
return LearnerApplicationStatusResponse(
|
||||
application=LearnerApplicationSummary(
|
||||
id=application.id,
|
||||
posting_id=application.posting_id,
|
||||
learner_id=application.learner_id,
|
||||
status=application.status,
|
||||
created_at=application.created_at,
|
||||
),
|
||||
events=events,
|
||||
placement=_placement_read(row) if row is not None else None,
|
||||
)
|
||||
|
||||
|
||||
# -- P4-B: resume upload + confirm (REQ-6-005, D-054, A-410) --------------------
|
||||
|
||||
|
||||
class ResumeDraftResponse(BaseModel):
|
||||
"""The parse result — a DRAFT. Nothing persists without the explicit
|
||||
confirm call (the REQ-6-005 review gate)."""
|
||||
|
||||
status: str = "draft"
|
||||
profile: dict
|
||||
|
||||
|
||||
class ResumeConfirmBody(BaseModel):
|
||||
"""The learner's explicit save decision: the draft profile rides the
|
||||
body VERBATIM from the parse and the server RE-VALIDATES the shape
|
||||
against ParsedProfile before persisting (verifier P1 — a bare dict
|
||||
would accept arbitrary/type-confused payloads)."""
|
||||
|
||||
learner_id: str = Field(min_length=1)
|
||||
profile: dict
|
||||
|
||||
|
||||
class ResumeConfirmResponse(BaseModel):
|
||||
status: str = "confirmed"
|
||||
learner_id: str
|
||||
confirmed_at: str
|
||||
|
||||
|
||||
async def _require_verified_marketplace_learner(
|
||||
learner_id: str,
|
||||
settings: Settings,
|
||||
request: Request,
|
||||
) -> None:
|
||||
"""Learner-gated resume surface (D-043 composition order): G-5
|
||||
allowlist → verified identity → rate caps — same order as apply."""
|
||||
_enforce_allowlist(learner_id, settings)
|
||||
await require_verified_age(18, learner_id, _identity_store(request))
|
||||
_check_apply_rate(learner_id)
|
||||
|
||||
|
||||
@router.post("/resume", response_model=ResumeDraftResponse)
|
||||
async def upload_resume(
|
||||
request: Request,
|
||||
store=Depends(get_marketplace_store),
|
||||
settings: Settings = Depends(get_settings),
|
||||
provider=Depends(get_provider),
|
||||
) -> ResumeDraftResponse:
|
||||
"""Parse an uploaded resume into a profile DRAFT (multipart: `file`
|
||||
+ `learner_id` form field). Bounds (A-410): PDF/TXT/MD only, ≤2 MB,
|
||||
text-layer required (empty PDF extract → honest 422; no OCR in
|
||||
v0.6). Raw bytes never stored, never logged (A-305). The response
|
||||
is a DRAFT — the confirm route is the only persistence path."""
|
||||
|
||||
from starlette.datastructures import UploadFile as StarletteUploadFile
|
||||
|
||||
form = await request.form()
|
||||
try:
|
||||
learner_id = form.get("learner_id")
|
||||
if not isinstance(learner_id, str) or not learner_id:
|
||||
raise HTTPException(
|
||||
status_code=422, detail="learner_id form field required"
|
||||
)
|
||||
await _require_verified_marketplace_learner(learner_id, settings, request)
|
||||
|
||||
upload = form.get("file")
|
||||
# starlette's UploadFile base (fastapi's is a subclass — the raw
|
||||
# request.form() yields the base, so isinstance must use it).
|
||||
if not isinstance(upload, StarletteUploadFile):
|
||||
raise HTTPException(status_code=422, detail="file form field required")
|
||||
data = await upload.read()
|
||||
if len(data) > MAX_RESUME_BYTES:
|
||||
raise HTTPException(
|
||||
status_code=413,
|
||||
detail=f"resume too large ({len(data)} bytes; max {MAX_RESUME_BYTES})",
|
||||
)
|
||||
if len(data) == 0:
|
||||
raise HTTPException(status_code=422, detail="empty file")
|
||||
content_type = upload.content_type or ""
|
||||
try:
|
||||
text = extract_resume_text(data, content_type)
|
||||
except ResumeFormatError as exc:
|
||||
raise HTTPException(status_code=422, detail=str(exc)) from exc
|
||||
try:
|
||||
parsed = await parse_resume(provider, model=settings.model, text=text)
|
||||
except Exception as exc:
|
||||
raise HTTPException(
|
||||
status_code=502,
|
||||
detail="profile extraction failed — try again or edit manually",
|
||||
) from exc
|
||||
draft = ResumeDraftResponse(
|
||||
status="draft",
|
||||
profile={
|
||||
"name": parsed.name,
|
||||
"headline": parsed.headline,
|
||||
"skills": list(parsed.skills),
|
||||
"experience_bands": [
|
||||
b.model_dump() for b in parsed.experience_bands
|
||||
],
|
||||
"competencies": list(parsed.competencies),
|
||||
},
|
||||
)
|
||||
finally:
|
||||
# P3 (Task 3-2-01): this route parses the form manually (raw
|
||||
# request.form()), so FastAPI's request-end auto-close — which it
|
||||
# pushes ONLY for param-injected multipart bodies — never runs
|
||||
# here. The multipart parser has already spooled every file open
|
||||
# by the time any guard raises (learner_id 422, allowlist 403,
|
||||
# verified 403, rate 429 — the pre-read guards included), so the
|
||||
# close must span ALL paths. form.close() is starlette's
|
||||
# canonical cleanup for manually-parsed forms: it closes every
|
||||
# UploadFile the form carries. The bytes are fully in `data`
|
||||
# before any raise (G-107: no streaming path exists); the
|
||||
# response is materialized in `draft` — nothing reads the
|
||||
# spooled file after this point.
|
||||
await form.close()
|
||||
return draft
|
||||
|
||||
|
||||
@router.post("/resume/confirm", response_model=ResumeConfirmResponse)
|
||||
async def confirm_resume(
|
||||
body: ResumeConfirmBody,
|
||||
request: Request,
|
||||
store=Depends(get_marketplace_store),
|
||||
settings: Settings = Depends(get_settings),
|
||||
) -> ResumeConfirmResponse:
|
||||
"""The REQ-6-005 review gate: persist the learner-CONFIRMED profile
|
||||
to the learner_profile store table (G-104 — the D-027 family is the
|
||||
only persistence mechanism). G-5 → verified 18+ → rate caps, then
|
||||
a SHAPE RE-VALIDATION against ParsedProfile (verifier P1 — the
|
||||
confirm must never persist arbitrary/type-confused payloads the
|
||||
parse never produced), then an UPSERT (re-confirm replaces; the
|
||||
draft never persisted)."""
|
||||
await _require_verified_marketplace_learner(body.learner_id, settings, request)
|
||||
try:
|
||||
validated = ParsedProfile.model_validate(body.profile)
|
||||
except ValidationError as exc:
|
||||
raise HTTPException(
|
||||
status_code=422,
|
||||
detail={
|
||||
"reason": "invalid_profile_shape",
|
||||
"message": "the profile must match the parsed draft shape",
|
||||
"errors": [
|
||||
{"loc": list(e.get("loc", [])), "msg": e.get("msg", "")}
|
||||
for e in exc.errors()
|
||||
],
|
||||
},
|
||||
) from exc
|
||||
stored = store.save_learner_profile(
|
||||
body.learner_id, validated.model_dump(mode="json"), model=settings.model
|
||||
)
|
||||
return ResumeConfirmResponse(
|
||||
status="confirmed",
|
||||
learner_id=stored["learner_id"],
|
||||
confirmed_at=stored["confirmed_at"].isoformat()
|
||||
if stored["confirmed_at"]
|
||||
else "",
|
||||
)
|
||||
|
||||
@@ -19,13 +19,14 @@ import secrets
|
||||
import uuid
|
||||
from typing import Annotated, Any
|
||||
|
||||
from fastapi import APIRouter, Depends, Header, HTTPException
|
||||
from fastapi import APIRouter, Depends, Header, HTTPException, Request
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from ..config import Settings
|
||||
from ..llm.base import LLMProvider
|
||||
from ..marketplace.base import Posting
|
||||
from ..marketplace.embedding.base import EmbeddingProvider
|
||||
from ..marketplace.enrichment import ENRICHABLE_FIELDS, maybe_enrich_on_publish
|
||||
from ..marketplace.ingest import SeededCorpusSource, run_ingest
|
||||
from ..marketplace.search import embed_posting
|
||||
from ..marketplace.store import InvalidTransition, MarketplaceStore
|
||||
@@ -36,6 +37,7 @@ from .deps import (
|
||||
get_provider,
|
||||
get_settings,
|
||||
)
|
||||
from .entitlement import consume_posting_entitlement
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -64,13 +66,22 @@ def require_admin(
|
||||
"""D-057 fail-closed guard: constant-time compare (G-108) against the
|
||||
env-only AI_ADMIN_TOKEN (SecretStr — never repr'd/logged); UNSET → 403
|
||||
for EVERY request (never open). Returns the settings for the route
|
||||
handlers."""
|
||||
handlers.
|
||||
|
||||
Bytes compare: `secrets.compare_digest` raises TypeError on
|
||||
non-ASCII str candidates (final-review F-1 — an attacker-triggerable
|
||||
unhandled 500, fail-closed in outcome but noisy); comparing the
|
||||
UTF-8 encodings accepts ANY candidate bytes honestly (403 on
|
||||
mismatch) and stays constant-time."""
|
||||
configured = settings.admin_token.get_secret_value()
|
||||
if not configured or request_token is None:
|
||||
# Fail-closed: no configured token, or no candidate at all — the
|
||||
# surface is locked, not open (D-057).
|
||||
raise HTTPException(status_code=403, detail="admin token required")
|
||||
if not secrets.compare_digest(request_token, configured):
|
||||
if not secrets.compare_digest(
|
||||
request_token.encode("utf-8", "surrogatepass"),
|
||||
configured.encode("utf-8"),
|
||||
):
|
||||
raise HTTPException(status_code=403, detail="invalid admin token")
|
||||
return settings
|
||||
|
||||
@@ -119,6 +130,16 @@ class AdminPostingEdit(BaseModel):
|
||||
skills: list[str] | None = None
|
||||
|
||||
|
||||
class AdminEnrichmentOverride(BaseModel):
|
||||
"""P4-A (D-053): manual-override body — appends a manual-source row
|
||||
(never mutates llm rows). `value` for social_links is a JSON object
|
||||
string; the other fields are plain text."""
|
||||
|
||||
employer_id: str = Field(min_length=1)
|
||||
field: str = Field(min_length=1)
|
||||
value: str = Field(min_length=1)
|
||||
|
||||
|
||||
class AdminApplication(BaseModel):
|
||||
id: str
|
||||
posting_id: str
|
||||
@@ -137,11 +158,30 @@ class AdminApplicationsResponse(BaseModel):
|
||||
@router.post("/postings", status_code=201, response_model=AdminPostingResponse)
|
||||
async def create_posting(
|
||||
body: AdminPostingCreate,
|
||||
request: Request,
|
||||
store: MarketplaceStore = Depends(get_marketplace_store),
|
||||
settings: Settings = Depends(require_admin),
|
||||
) -> AdminPostingResponse:
|
||||
"""Create a DRAFT posting (founder authoring path, D-050 admin_api
|
||||
adapter — source=admin). Publish is a separate lifecycle call."""
|
||||
adapter — source=admin). Publish is a separate lifecycle call.
|
||||
|
||||
v0.10 P4 (D-091, Task 4-1-01): the inline gate is extracted into the
|
||||
shared api-layer helper `consume_posting_entitlement` (api/entitlement.
|
||||
py) — this admin route and the employer create route (Task 4-1-02)
|
||||
compose the SAME gate, never re-implemented copies. The admin
|
||||
principal passes the admin-checkout pointer; the 402 dict (hardcoded
|
||||
posts_used/posts_limit zeros, R-58) is byte-stable across both
|
||||
gates — the wire contract UpgradeRequiredError consumes unchanged.
|
||||
|
||||
Final-review fix preserved (fail-closed): the store is fetched via
|
||||
getattr(app.state); a wiring miss (None) makes the helper refuse
|
||||
with 503 — never an ungated 201.
|
||||
"""
|
||||
consume_posting_entitlement(
|
||||
getattr(request.app.state, "billing_store", None),
|
||||
body.employer_id,
|
||||
"/v1/billing/admin/checkout",
|
||||
)
|
||||
posting = Posting(
|
||||
id=f"adm-{uuid.uuid4().hex[:16]}",
|
||||
source="admin",
|
||||
@@ -151,6 +191,8 @@ async def create_posting(
|
||||
description=body.description,
|
||||
required_competencies=body.required_competencies,
|
||||
skills=body.skills,
|
||||
# P5: admin body carries str; Posting's Literal contract — the
|
||||
# store's validates hook rejects out-of-taxonomy values.
|
||||
seniority=body.seniority, # type: ignore[arg-type]
|
||||
category=body.category,
|
||||
location=body.location,
|
||||
@@ -181,6 +223,7 @@ async def publish_posting(
|
||||
store: MarketplaceStore = Depends(get_marketplace_store),
|
||||
settings: Settings = Depends(require_admin),
|
||||
embedder: EmbeddingProvider = Depends(get_embedding_provider),
|
||||
provider: LLMProvider = Depends(get_provider),
|
||||
) -> AdminPostingResponse:
|
||||
"""draft → published (the only valid move from draft; anything else
|
||||
409s). Stamps posted_at NOW when the row has none (G-102: seed-port
|
||||
@@ -188,7 +231,12 @@ async def publish_posting(
|
||||
|
||||
P3 embed-on-publish (Task 3-2-01): the published posting embeds
|
||||
now; failure = honest warning — the posting still publishes, the
|
||||
vector stays absent (search skips it)."""
|
||||
vector stays absent (search skips it).
|
||||
|
||||
P4-A enrich-on-first-publish (D-053): the employer's FIRST publish
|
||||
fires the one-shot profile extraction (no existing llm rows → run;
|
||||
re-publishing the same employer does not re-run). Failure = honest
|
||||
warning — the publish stands, no rows written."""
|
||||
try:
|
||||
stored = store.set_posting_status(posting_id, "published")
|
||||
except InvalidTransition as exc:
|
||||
@@ -198,6 +246,12 @@ async def publish_posting(
|
||||
status_code=404, detail=f"no posting with id {posting_id!r}"
|
||||
)
|
||||
await embed_posting(store, embedder, stored)
|
||||
try:
|
||||
await maybe_enrich_on_publish(
|
||||
store, provider, model=settings.model, employer_id=stored.employer_id
|
||||
)
|
||||
except Exception: # pragma: no cover - maybe_enrich swallows; belt+braces
|
||||
logger.exception("enrich-on-publish failed; publish stands")
|
||||
return AdminPostingResponse(
|
||||
id=stored.id,
|
||||
source=stored.source,
|
||||
@@ -208,6 +262,34 @@ async def publish_posting(
|
||||
)
|
||||
|
||||
|
||||
@router.post("/enrichment", status_code=201)
|
||||
async def manual_enrichment_override(
|
||||
body: AdminEnrichmentOverride,
|
||||
store: MarketplaceStore = Depends(get_marketplace_store),
|
||||
settings: Settings = Depends(require_admin),
|
||||
) -> dict:
|
||||
"""P4-A (D-053): founder manual override — APPENDS a manual-source
|
||||
row (read precedence manual > llm > raw picks it up); llm rows are
|
||||
NEVER mutated. Valid fields: description | social_links | logo."""
|
||||
if body.field not in ENRICHABLE_FIELDS:
|
||||
raise HTTPException(
|
||||
status_code=422,
|
||||
detail=f"field must be one of {ENRICHABLE_FIELDS}",
|
||||
)
|
||||
employer = store.get_employer(body.employer_id)
|
||||
if employer is None:
|
||||
raise HTTPException(
|
||||
status_code=404, detail=f"no employer with id {body.employer_id!r}"
|
||||
)
|
||||
row = store.append_enrichment(
|
||||
body.employer_id,
|
||||
field=body.field,
|
||||
value=body.value,
|
||||
source="manual",
|
||||
)
|
||||
return {"stored": True, "row": row}
|
||||
|
||||
|
||||
@router.post(
|
||||
"/postings/{posting_id}/close", response_model=AdminPostingResponse
|
||||
)
|
||||
|
||||
@@ -0,0 +1,330 @@
|
||||
"""Operator lane for placement oversight (D-106, REQ-11-002).
|
||||
|
||||
`require_admin` IMPORTED from marketplace_admin (the billing_admin.py
|
||||
import precedent — token namespaces cannot collide, D-090): one
|
||||
generic remediation transition route + revoke + the R-80 re-hire +
|
||||
the reporting/export reads (P3/P4 extend this router). No employer
|
||||
session, no learner gate — a third principal class (D-097).
|
||||
|
||||
OPERATOR = "operator" route-level provenance (employers_admin.py:54 —
|
||||
no per-operator accounts exist, D-094); every action is
|
||||
ledger-recorded with actor_type="operator" (the D-083 manual-grant
|
||||
lane) and answers in employer_audit_events via the P2 routes' own
|
||||
appends (operator transitions record through the placement ledger).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from datetime import date
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Response
|
||||
|
||||
from ..config import Settings
|
||||
from ..marketplace.store import MarketplaceStore
|
||||
from ..placements.base import (
|
||||
GUIDING_GOAL,
|
||||
AdminTransitionRequest,
|
||||
ApplicationTransitionResponse,
|
||||
HireTransitionRequest,
|
||||
PlacementOverview,
|
||||
PlacementRead,
|
||||
)
|
||||
from ..placements.store import PlacementRow, PlacementStore
|
||||
from .deps import get_marketplace_store, get_placement_store
|
||||
from .marketplace_admin import require_admin
|
||||
|
||||
#: D-094: route-level operator provenance — no per-operator accounts.
|
||||
OPERATOR = "operator"
|
||||
|
||||
router = APIRouter(prefix="/v1/placements/admin", tags=["placements-admin"])
|
||||
# The admin-token gate composes on EVERY route handler via the
|
||||
# Annotated[Settings, Depends(require_admin)] house pattern (the
|
||||
# employers_admin idiom — fail-closed; token namespaces cannot collide
|
||||
# with employer session tokens, D-090).
|
||||
AdminGate = Annotated[Settings, Depends(require_admin)]
|
||||
|
||||
|
||||
def _placement_read(row: PlacementRow) -> PlacementRead:
|
||||
return PlacementRead(
|
||||
id=row.id,
|
||||
learner_id=row.learner_id,
|
||||
employer_id=row.employer_id,
|
||||
posting_id=row.posting_id,
|
||||
application_id=row.application_id,
|
||||
role_title=row.role_title,
|
||||
start_date=date.fromisoformat(row.start_date),
|
||||
status=row.status, # type: ignore[arg-type]
|
||||
created_at=row.created_at or _now(),
|
||||
decided_at=row.decided_at or _now(),
|
||||
)
|
||||
|
||||
|
||||
def _now():
|
||||
from datetime import UTC, datetime
|
||||
|
||||
return datetime.now(UTC)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/applications/{application_id}/transition",
|
||||
response_model=ApplicationTransitionResponse,
|
||||
)
|
||||
async def admin_transition_application(
|
||||
application_id: str,
|
||||
body: AdminTransitionRequest,
|
||||
_gate: AdminGate,
|
||||
store: MarketplaceStore = Depends(get_marketplace_store),
|
||||
placements: PlacementStore = Depends(get_placement_store),
|
||||
) -> ApplicationTransitionResponse:
|
||||
"""The generic operator remediation route (D-106): ANY matrix-legal
|
||||
transition incl. withdrawn on a learner's behalf (remediation with
|
||||
provenance, the D-083 lane). G-327: `to` is a CLOSED Literal —
|
||||
unknown values die at pydantic (422), matrix-illegal known values
|
||||
reach the store (409 InvalidTransition). role_title/start_date
|
||||
are required iff to=hired (the honest 422 with required-fields
|
||||
detail, D-103)."""
|
||||
role_title: str | None = None
|
||||
start_date: date | None = None
|
||||
if body.to == "hired":
|
||||
if body.role_title is None or body.start_date is None:
|
||||
raise HTTPException(
|
||||
status_code=422,
|
||||
detail="role_title and start_date are required when to=hired (D-103)",
|
||||
)
|
||||
role_title, start_date = body.role_title, body.start_date
|
||||
try:
|
||||
application, placement = placements.transition_application(
|
||||
application_id,
|
||||
body.to,
|
||||
actor_type="operator",
|
||||
actor_ref=OPERATOR,
|
||||
role_title=role_title,
|
||||
start_date=start_date,
|
||||
)
|
||||
except Exception as exc:
|
||||
# The placements InvalidTransition (409) MUST be matched before
|
||||
# the ValueError arm — InvalidTransition subclasses ValueError.
|
||||
from ..placements.base import InvalidTransition
|
||||
|
||||
if isinstance(exc, InvalidTransition):
|
||||
raise HTTPException(status_code=409, detail=str(exc)) from exc
|
||||
if isinstance(exc, ValueError):
|
||||
raise HTTPException(status_code=422, detail=str(exc)) from exc
|
||||
raise
|
||||
return ApplicationTransitionResponse(
|
||||
application_id=application.id,
|
||||
status=application.status, # type: ignore[arg-type]
|
||||
placement=_placement_read(placement) if placement is not None else None,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/placements/{placement_id}/revoke", response_model=PlacementRead)
|
||||
async def admin_revoke_placement(
|
||||
placement_id: str,
|
||||
_gate: AdminGate,
|
||||
placements: PlacementStore = Depends(get_placement_store),
|
||||
) -> PlacementRead:
|
||||
"""D-102: the operator correction — the one active → revoked
|
||||
placement transition (operator-only by route). Unknown → 404;
|
||||
non-active → 409 (the matrix)."""
|
||||
try:
|
||||
revoked = placements.revoke_placement(placement_id, OPERATOR)
|
||||
except Exception as exc:
|
||||
from ..placements.base import InvalidTransition
|
||||
|
||||
if isinstance(exc, InvalidTransition):
|
||||
raise HTTPException(status_code=409, detail=str(exc)) from exc
|
||||
raise
|
||||
if revoked is None:
|
||||
raise HTTPException(
|
||||
status_code=404, detail=f"no placement with id {placement_id!r}"
|
||||
)
|
||||
return _placement_read(revoked)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/placements/by-application/{application_id}/re-hire",
|
||||
response_model=PlacementRead,
|
||||
)
|
||||
async def admin_rehire_placement(
|
||||
application_id: str,
|
||||
body: HireTransitionRequest,
|
||||
_gate: AdminGate,
|
||||
placements: PlacementStore = Depends(get_placement_store),
|
||||
) -> PlacementRead:
|
||||
"""THE R-80 RE-HIRE ROUTE: after the first hire the application is
|
||||
TERMINAL (hired → hired is a 409 on every matrix-validated
|
||||
surface — the coherence gap research found). The re-hire creates
|
||||
the FRESH PlacementRow + the placement.rehired ledger event
|
||||
WITHOUT touching the application's terminal status — the ledger
|
||||
reads hired → revoke → rehire as three events, never fabricating
|
||||
a second application transition. Structurally safe: revoked rows
|
||||
never match the partial WHERE status='active' (the G-316
|
||||
property). G-326: decided_at = the re-hire event's stamp."""
|
||||
try:
|
||||
rehired = placements.rehire_placement(
|
||||
application_id,
|
||||
role_title=body.role_title,
|
||||
start_date=body.start_date,
|
||||
actor_ref=OPERATOR,
|
||||
)
|
||||
except Exception as exc:
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from ..placements.base import InvalidTransition
|
||||
|
||||
if isinstance(exc, InvalidTransition):
|
||||
raise HTTPException(status_code=409, detail=str(exc)) from exc
|
||||
if isinstance(exc, ValueError):
|
||||
raise HTTPException(status_code=422, detail=str(exc)) from exc
|
||||
if isinstance(exc, IntegrityError):
|
||||
# the partial-unique arm: an ACTIVE placement already exists
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
detail="an active placement already exists for this "
|
||||
"application — revoke it before re-hiring",
|
||||
) from exc
|
||||
raise
|
||||
return _placement_read(rehired)
|
||||
|
||||
|
||||
# -- the reporting read (v0.11 P3, Task 3-1-01 — REQ-11-003, D-107) ---------------
|
||||
|
||||
|
||||
@router.get("/overview", response_model=PlacementOverview)
|
||||
async def placement_overview(
|
||||
_gate: AdminGate,
|
||||
placements: PlacementStore = Depends(get_placement_store),
|
||||
) -> PlacementOverview:
|
||||
"""The D-107 computation — counts from ROWS at query time (never
|
||||
denormalized counters, G-302/G-306): the guiding metric is DISTINCT
|
||||
learners with ≥1 active placement, all-time cumulative toward
|
||||
GUIDING_GOAL (a learner placed twice counts ONCE — the outcome's
|
||||
noun is learners); revoked excluded from every count (D-102);
|
||||
cohort month = the calendar month of start_date (YYYY-MM); orderings
|
||||
pinned (R-73: by_employer count desc then employer_id;
|
||||
by_cohort_month month ascending)."""
|
||||
rows = placements.list_placements(status="active")
|
||||
learner_ids = {row.learner_id for row in rows}
|
||||
by_employer: dict[str, int] = {}
|
||||
by_month: dict[str, int] = {}
|
||||
for row in rows:
|
||||
by_employer[row.employer_id] = by_employer.get(row.employer_id, 0) + 1
|
||||
month = row.start_date[:7] # ISO YYYY-MM (the calendar slice)
|
||||
by_month[month] = by_month.get(month, 0) + 1
|
||||
return PlacementOverview(
|
||||
total_active_placements=len(rows),
|
||||
distinct_learners_placed=len(learner_ids),
|
||||
guiding_goal=GUIDING_GOAL,
|
||||
by_employer=[
|
||||
{"employer_id": employer_id, "count": count}
|
||||
for employer_id, count in sorted(
|
||||
by_employer.items(), key=lambda kv: (-kv[1], kv[0])
|
||||
)
|
||||
],
|
||||
by_cohort_month=[
|
||||
{"month": month, "count": count}
|
||||
for month, count in sorted(by_month.items())
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
# -- the audit export (v0.11 P4, Tasks 4-1-01/4-1-02 — REQ-11-004, D-108) ----------
|
||||
|
||||
|
||||
@router.get("/export")
|
||||
async def placement_export(
|
||||
_gate: AdminGate,
|
||||
placements: PlacementStore = Depends(get_placement_store),
|
||||
) -> Response:
|
||||
"""GET /v1/placements/admin/export — ONE self-contained JSON
|
||||
document (D-108): {schema_version, generated_at, summary, cohort,
|
||||
evidence_bundles (EVERY placement, active + revoked — G-325),
|
||||
methodology (the G-321 statements + the three R-67 pilot gaps),
|
||||
ledger (every event + head_hash)}. Determinism per R-73: pinned
|
||||
orderings, no floats, generated_at excluded from comparison (the
|
||||
re-export test strips it)."""
|
||||
document = placements.build_export()
|
||||
return Response(
|
||||
content=json.dumps(document, sort_keys=True, separators=(",", ":")),
|
||||
media_type="application/json",
|
||||
)
|
||||
|
||||
|
||||
@router.get("/export/summary")
|
||||
async def placement_export_summary(
|
||||
_gate: AdminGate,
|
||||
placements: PlacementStore = Depends(get_placement_store),
|
||||
) -> Response:
|
||||
"""GET /v1/placements/admin/export/summary — text/markdown
|
||||
rendered FROM the same JSON document (one builder, two
|
||||
renderings — the anti-drift rule: the summary can never assert a
|
||||
number the export doesn't contain). G-328: the title carries the
|
||||
ATTESTATION language (employer-attested, operator-overseen) —
|
||||
never a verification claim."""
|
||||
document = placements.build_export()
|
||||
summary = document["summary"]
|
||||
methodology = document["methodology"]
|
||||
head = document["ledger"]["head_hash"]
|
||||
lines: list[str] = []
|
||||
lines.append("# Placement Audit Export — Summary")
|
||||
lines.append("")
|
||||
lines.append(
|
||||
"Employer-attested, operator-overseen placement records (NOT "
|
||||
"third-party employment verification — see Methodology)."
|
||||
)
|
||||
lines.append("")
|
||||
lines.append("## Totals")
|
||||
lines.append("")
|
||||
lines.append("| Metric | Count |")
|
||||
lines.append("|---|---|")
|
||||
lines.append(
|
||||
f"| Distinct learners placed (toward {GUIDING_GOAL}) "
|
||||
f"| {summary['distinct_learners_placed']} |"
|
||||
)
|
||||
lines.append(f"| Total active placements | {summary['total_active_placements']} |")
|
||||
lines.append(f"| Revoked placements | {summary['revoked_count']} |")
|
||||
lines.append("")
|
||||
lines.append("## By cohort month (employment start)")
|
||||
lines.append("")
|
||||
lines.append("| Month | Placements |")
|
||||
lines.append("|---|---|")
|
||||
for bucket in summary["by_cohort_month"]:
|
||||
lines.append(f"| {bucket['month']} | {bucket['count']} |")
|
||||
if not summary["by_cohort_month"]:
|
||||
lines.append("| (none recorded) | 0 |")
|
||||
lines.append("")
|
||||
lines.append("## Methodology")
|
||||
lines.append("")
|
||||
lines.append(f"### Placement definition\n\n{methodology['placement_definition']}\n")
|
||||
lines.append(f"### Counting rules\n\n{methodology['counting_rules']}\n")
|
||||
lines.append(f"### Verification\n\n{methodology['verification']}\n")
|
||||
lines.append(f"### Scope\n\n{methodology['scope']}\n")
|
||||
lines.append("## Verifying the export offline")
|
||||
lines.append("")
|
||||
lines.append(
|
||||
"Every ledger event is embedded in the JSON export. Re-walk the "
|
||||
"chain: for each event in id order, compute "
|
||||
"`sha256(canonical_json + prev_hash)` where canonical_json is "
|
||||
"the event's {id, application_id, placement_id, event_type, "
|
||||
"actor_type, actor_ref, payload, created_at} serialized with "
|
||||
"sorted keys and compact separators (created_at in UTC ISO-8601), "
|
||||
"and prev_hash starts at the all-zeros GENESIS constant. The "
|
||||
"final computed hash must equal head_hash:"
|
||||
)
|
||||
lines.append("")
|
||||
lines.append(f"`head_hash: {head}`")
|
||||
lines.append("")
|
||||
lines.append(
|
||||
"Then compare against a PRIOR export: its ledger.events must "
|
||||
"appear as an exact prefix of this export's events, and its "
|
||||
"head_hash must equal the hash at that prefix position "
|
||||
"(export-to-export continuity is the anchor against wholesale "
|
||||
"database replacement — see Verification)."
|
||||
)
|
||||
return Response(
|
||||
content="\n".join(lines),
|
||||
media_type="text/markdown",
|
||||
)
|
||||
@@ -5,10 +5,12 @@ variant seed cross-check, no corpus scenarios. The proctor coaches:
|
||||
a pydantic-validated ProctorAssessment (JSON response, not SSE).
|
||||
"""
|
||||
|
||||
from typing import cast
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from ..agents.proctor import ProctorAssessment
|
||||
from ..agents.proctor import ProctorAgent, ProctorAssessment
|
||||
from ..agents.registry import AgentRegistry
|
||||
from ..config import Settings
|
||||
from ..corpus.learner_context import get_learner_context
|
||||
@@ -41,7 +43,9 @@ async def proctor_signals(
|
||||
voice_store=Depends(get_voice_store),
|
||||
) -> ProctorAssessment:
|
||||
"""Real integrity inputs: live digest + defense signals + variant context."""
|
||||
agent = registry.get(provider, settings, "proctor")
|
||||
# P5: registry.get returns BaseAgent; "proctor" is registered as
|
||||
# ProctorAgent (register_builtin_agents) — the cast states that mapping.
|
||||
agent = cast(ProctorAgent, registry.get(provider, settings, "proctor"))
|
||||
learner_context = get_learner_context(body.learner_id)
|
||||
|
||||
trace = (
|
||||
|
||||
@@ -23,12 +23,14 @@ never part of the API contract.
|
||||
|
||||
import time
|
||||
from collections import deque
|
||||
from collections.abc import Set as AbstractSet
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request, Response
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
from ..config import Settings
|
||||
from ..sandbox.capability import DEGRADE_REMEDIATION, sandbox_fabric_degraded
|
||||
from ..sandbox.manager import (
|
||||
PoolFullError,
|
||||
SandboxHandleInfo,
|
||||
@@ -36,7 +38,9 @@ from ..sandbox.manager import (
|
||||
SandboxNotFoundError,
|
||||
)
|
||||
from ..sandbox.workdir import SandboxDir
|
||||
from ..variants.templates import get_template
|
||||
from .deps import get_sandbox_manager, get_sandbox_test_layout, get_settings
|
||||
from .identity import require_verified_age
|
||||
|
||||
router = APIRouter(prefix="/v1/sandboxes", tags=["sandboxes"])
|
||||
|
||||
@@ -94,10 +98,6 @@ class SnapshotResponse(BaseModel):
|
||||
# -- abuse control (G-5; middleware layer, not auth) ---------------------------
|
||||
|
||||
|
||||
from ..variants.templates import get_template # noqa: E402
|
||||
from .identity import require_verified_age # noqa: E402 (gate dep, D-043)
|
||||
|
||||
|
||||
def _enforce_allowlist(learner_id: str, settings: Settings) -> None:
|
||||
if learner_id not in settings.learner_allowlist:
|
||||
raise HTTPException(
|
||||
@@ -155,6 +155,19 @@ async def create_sandbox(
|
||||
)
|
||||
_check_per_learner_cap(await manager.list(), body.learner_id, settings)
|
||||
_check_global_create_rate(settings)
|
||||
# v0.8 honest degrade (D-068/G-208): when the namespace fabric cannot
|
||||
# work on this host (unprivileged container under docker's default
|
||||
# seccomp), env creation is rejected BEFORE the manager is touched —
|
||||
# same 503 class as PoolFullError, carrying the shared remediation
|
||||
# constant (the boot notice logs the same text; they cannot drift).
|
||||
# Structural backends (test stubs — no userns involved) declare
|
||||
# `structural = True` and are exempt: the stub-backed suite must stay
|
||||
# green inside job containers (D-063) while the REAL fabric degrades
|
||||
# honestly everywhere.
|
||||
manager_backend = getattr(manager, "_backend", None)
|
||||
structural = getattr(manager_backend, "structural", False)
|
||||
if not structural and sandbox_fabric_degraded():
|
||||
raise HTTPException(status_code=503, detail=DEGRADE_REMEDIATION)
|
||||
try:
|
||||
info = await manager.create(body.learner_id, task_id=body.task_id)
|
||||
except PoolFullError as exc:
|
||||
@@ -263,7 +276,7 @@ class ExecResponse(BaseModel):
|
||||
async def _workspace_dir(manager: SandboxManager, sandbox_id: str):
|
||||
"""Resolve the sandbox workspace (tracked layout or shell layout)."""
|
||||
info = await manager.get(sandbox_id) # raises SandboxNotFoundError -> 404
|
||||
backend = manager._backend # noqa: SLF001 - API owns the composition seam
|
||||
backend = manager._backend
|
||||
tracked = getattr(backend, "_tracked", {}).get(sandbox_id)
|
||||
if tracked is not None:
|
||||
return tracked.workspace, info
|
||||
@@ -359,7 +372,9 @@ _GENERIC_FIRST_TOKENS = frozenset(
|
||||
|
||||
|
||||
def _enforce_exec_policy(
|
||||
cmd: list[str], environment: str | None, allowed: set[str] | None = None
|
||||
# P5: AbstractSet[str] — the caller unions frozenset + set; membership
|
||||
# is all this function does with it.
|
||||
cmd: list[str], environment: str | None, allowed: AbstractSet[str] | None = None
|
||||
) -> None:
|
||||
"""422 with the allowed set when a design/sim command is out of policy.
|
||||
|
||||
@@ -368,7 +383,8 @@ def _enforce_exec_policy(
|
||||
template must not reject its own Run command)."""
|
||||
if environment not in ("design", "simulation"):
|
||||
return # build kind: unchanged v0.3 semantics
|
||||
allowed = set(allowed) if allowed is not None else set(_GENERIC_FIRST_TOKENS)
|
||||
if allowed is None:
|
||||
allowed = _GENERIC_FIRST_TOKENS
|
||||
first = cmd[0] if cmd else ""
|
||||
if first in ("sh", "bash"):
|
||||
raise HTTPException(
|
||||
@@ -399,14 +415,14 @@ async def exec_command(
|
||||
await manager.get(sandbox_id)
|
||||
except SandboxNotFoundError:
|
||||
raise HTTPException(status_code=404, detail=f"no sandbox {sandbox_id!r}") from None
|
||||
backend = manager._backend # noqa: SLF001 - API owns the composition seam
|
||||
handle = manager._handles.get(sandbox_id) # noqa: SLF001
|
||||
backend = manager._backend
|
||||
handle = manager._handles.get(sandbox_id)
|
||||
if handle is None:
|
||||
raise HTTPException(status_code=404, detail=f"no live handle {sandbox_id!r}")
|
||||
# REQ-5-005 (G-15): resolve the sandbox's variant environment by its
|
||||
# task_id (manager side-table) and enforce the per-kind command policy
|
||||
# BEFORE execution.
|
||||
task_id = manager._task_ids.get(sandbox_id) # noqa: SLF001 - composition seam
|
||||
task_id = manager._task_ids.get(sandbox_id)
|
||||
if task_id:
|
||||
variant = request.app.state.variant_store.get_by_task(task_id)
|
||||
if variant is not None:
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
"""Dynamic sitemap.xml + robots.txt (REQ-6-006, D-056, A-411).
|
||||
|
||||
Next `app/sitemap.ts` cannot work under `output: 'export'` — it
|
||||
enumerates at BUILD time and cannot see runtime postings. These plain
|
||||
FastAPI routes enumerate at REQUEST time: the static page list (a code
|
||||
constant) + every PUBLISHED posting (via the G-101 catch-all shells,
|
||||
each URL resolves — G-109, the sitemap never advertises what the
|
||||
deploy 404s).
|
||||
|
||||
Mount order (probe 6, verified): API routes beat the StaticFiles("/")
|
||||
export mount, so these win in single-port production. robots.txt
|
||||
points at the sitemap; per the robots spec the Sitemap directive must
|
||||
be an ABSOLUTE URL.
|
||||
|
||||
Unset AI_PUBLIC_BASE_URL (G-105): loud G-11 boot warning (main.py);
|
||||
the sitemap serves the EMPTY static-page set with a warning comment
|
||||
(never malformed or relative URLs) and robots omits the Sitemap
|
||||
directive; fail honest at request time; boot never crashes.
|
||||
|
||||
Pilot scale bound (A-403): postings are enumerated with limit=5000 —
|
||||
the tail beyond 5000 published postings is NOT listed (no sitemap
|
||||
pagination in v0.6; a sitemap index lands with the third adapter).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from xml.sax.saxutils import escape as _xml_escape
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
from fastapi.responses import Response
|
||||
|
||||
from ..config import Settings
|
||||
from .deps import get_marketplace_store, get_settings
|
||||
|
||||
router = APIRouter(include_in_schema=False)
|
||||
|
||||
#: The static page set (A-411 build-time-static pages) — code constant;
|
||||
#: runtime postings append at request time. G-109: every path is the
|
||||
#: page's real export path (the pricing page exports under
|
||||
#: /marketplace/pricing/, never /pricing/).
|
||||
STATIC_PAGES: tuple[str, ...] = (
|
||||
"/",
|
||||
"/catalog",
|
||||
"/marketplace",
|
||||
"/marketplace/pricing",
|
||||
)
|
||||
|
||||
|
||||
def _origin(settings: Settings) -> str | None:
|
||||
raw = (settings.public_base_url or "").strip().rstrip("/")
|
||||
if not raw:
|
||||
return None
|
||||
if not raw.startswith(("http://", "https://")):
|
||||
return None # malformed origin — never emit a bad absolute URL
|
||||
return raw
|
||||
|
||||
|
||||
@router.get("/sitemap.xml")
|
||||
async def sitemap(
|
||||
store=Depends(get_marketplace_store),
|
||||
settings: Settings = Depends(get_settings),
|
||||
) -> Response:
|
||||
"""Published postings + the static page set, as absolute URLs from
|
||||
AI_PUBLIC_BASE_URL. Unset origin → the honest empty set (G-105)."""
|
||||
origin = _origin(settings)
|
||||
if origin is None:
|
||||
# G-105: fail honest — never relative/malformed URLs in a
|
||||
# sitemap (spec requires absolute).
|
||||
return Response(
|
||||
content="<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
|
||||
"<!-- sitemap disabled: AI_PUBLIC_BASE_URL is unset — "
|
||||
"set the deployed origin to serve this sitemap -->\n"
|
||||
"<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n"
|
||||
"</urlset>\n",
|
||||
media_type="application/xml",
|
||||
)
|
||||
urls: list[str] = []
|
||||
for page in STATIC_PAGES:
|
||||
urls.append(f"{origin}{page}")
|
||||
# Runtime postings — every published one resolves via the G-101
|
||||
# catch-all shells (trailingSlash: true → /marketplace/jobs/{id}/).
|
||||
# Pilot cap (A-403, ≤10⁴ postings): a single sitemap page holds
|
||||
# ≤50,000 URLs; beyond 5000 postings the tail is dropped — the
|
||||
# honest bound recorded in the module docstring (no pagination in
|
||||
# v0.6; a sitemap index lands with the 3M-corpus adapter).
|
||||
postings, _total = store.list_postings(limit=5000, offset=0)
|
||||
for posting in postings:
|
||||
urls.append(f"{origin}/marketplace/jobs/{posting.id}/")
|
||||
body = ["<?xml version=\"1.0\" encoding=\"UTF-8\"?>"]
|
||||
body.append(
|
||||
'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'
|
||||
)
|
||||
for url in urls:
|
||||
# XML-escape the loc text — the origin is founder-set env, but
|
||||
# defense-in-depth: metacharacters in it must never break out
|
||||
# of the <loc> element (verified: raw <script> would otherwise
|
||||
# inject into the response body).
|
||||
body.append("<url>")
|
||||
body.append(f"<loc>{_xml_escape(url)}</loc>")
|
||||
body.append("</url>")
|
||||
body.append("</urlset>")
|
||||
return Response(content="\n".join(body) + "\n", media_type="application/xml")
|
||||
|
||||
|
||||
@router.get("/robots.txt")
|
||||
async def robots(settings: Settings = Depends(get_settings)) -> Response:
|
||||
"""Crawl policy: allow all; the Sitemap directive is ABSOLUTE
|
||||
(spec) — omitted entirely when the origin is unset (G-105)."""
|
||||
lines = ["User-agent: *", "Allow: /"]
|
||||
origin = _origin(settings)
|
||||
if origin is not None:
|
||||
# The origin is founder-set env, but defense-in-depth: strip
|
||||
# control characters (newline smuggling could forge extra
|
||||
# robots directives — a newline in the origin once appended
|
||||
# "Disallow: /admin" as a directive line).
|
||||
safe = "".join(c for c in origin if ord(c) >= 32)
|
||||
lines.append(f"Sitemap: {safe}/sitemap.xml")
|
||||
return Response(content="\n".join(lines) + "\n", media_type="text/plain")
|
||||
@@ -0,0 +1,58 @@
|
||||
"""Billing engine package (REQ-9-001, D-075..D-084, v0.9 Payment Engine).
|
||||
|
||||
The 7th domain module inside apps/ai-service (no new apps, no new ports —
|
||||
the D-031 boundary): pydantic contracts + the provider-agnostic
|
||||
`PaymentProvider` protocol (`base.py`), the shared HMAC webhook
|
||||
verification core (`webhooks.py`, D-077), the deterministic mock provider
|
||||
(`mock.py`, D-075 default), and the settings-driven factory
|
||||
(`factory.py`). The D-027 store family's seventh SQLite store
|
||||
(`store.py`), the seeded catalog (`catalog.py`), and the real Stripe
|
||||
provider (`stripe.py`) land with their owning phases.
|
||||
|
||||
Boundary (D-031 family discipline): `billing/` never imports `agents/`
|
||||
or `api/`; this package imports stdlib + pydantic + `config` only.
|
||||
"""
|
||||
|
||||
from .base import (
|
||||
CANONICAL_EVENT_NAMES,
|
||||
CanonicalBillingEvent,
|
||||
CanonicalEventName,
|
||||
CheckoutMode,
|
||||
CheckoutSession,
|
||||
CheckoutSessionSpec,
|
||||
CheckoutStatus,
|
||||
Package,
|
||||
PaymentProvider,
|
||||
PaymentStatus,
|
||||
Plan,
|
||||
PlanInterval,
|
||||
SubscriptionRef,
|
||||
SubscriptionStatus,
|
||||
UnknownPaymentProviderError,
|
||||
VerifiedEvent,
|
||||
WebhookSignatureError,
|
||||
)
|
||||
from .factory import payment_provider_from_settings
|
||||
from .mock import MockPaymentProvider
|
||||
|
||||
__all__ = [
|
||||
"CANONICAL_EVENT_NAMES",
|
||||
"CanonicalBillingEvent",
|
||||
"CanonicalEventName",
|
||||
"CheckoutMode",
|
||||
"CheckoutSession",
|
||||
"CheckoutSessionSpec",
|
||||
"CheckoutStatus",
|
||||
"MockPaymentProvider",
|
||||
"Package",
|
||||
"PaymentProvider",
|
||||
"PaymentStatus",
|
||||
"Plan",
|
||||
"PlanInterval",
|
||||
"SubscriptionRef",
|
||||
"SubscriptionStatus",
|
||||
"UnknownPaymentProviderError",
|
||||
"VerifiedEvent",
|
||||
"WebhookSignatureError",
|
||||
"payment_provider_from_settings",
|
||||
]
|
||||
@@ -0,0 +1,282 @@
|
||||
"""Billing pydantic contracts + PaymentProvider protocol (REQ-9-001).
|
||||
|
||||
The wire + provider shapes for the payment engine. `Package`/`Plan` are
|
||||
the catalog item shapes (D-078: seeded DB rows; P2 seeds them); the
|
||||
`CheckoutSession*` pair is the provider session seam (R-33..R-36);
|
||||
`CanonicalBillingEvent` is OUR event vocabulary — normalized at the
|
||||
provider boundary, never taken raw from a vendor (D-083, R-43).
|
||||
|
||||
Money (D-081): integer cents end-to-end — `int` with `ge=0`, no floats
|
||||
anywhere in billing, currency `usd` fixed. Stripe itself is cents-native
|
||||
(R-48: `unit_amount: 1000` = $10.00).
|
||||
|
||||
Id honesty (the identity-mock unique-mint lesson, A-305): every id in
|
||||
this module is an opaque handle minted UNIQUELY per creation call —
|
||||
never derived from user input or a deterministic hash of it.
|
||||
|
||||
Boundary (D-031 family): `billing/` never imports `agents/` or `api/`;
|
||||
stdlib + pydantic + config only.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any, Literal, Protocol, runtime_checkable
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
#: One-time posting packages vs recurring talent-access plans: one shape
|
||||
#: family, one table family (D-078/D-080 — a one-time purchase is NOT a
|
||||
#: degenerate subscription).
|
||||
PlanInterval = Literal["month", "year"]
|
||||
|
||||
#: Stripe-compatible checkout modes (R-34): payment = one-time packages,
|
||||
#: subscription = recurring plans. `setup` exists on the wire enum but no
|
||||
#: catalog item maps to it in v0.9.
|
||||
CheckoutMode = Literal["payment", "setup", "subscription"]
|
||||
|
||||
#: Session status vocabulary (R-36): open (awaiting payment) → complete
|
||||
#: (checkout finished) | expired (window elapsed). The GRANT predicate is
|
||||
#: `status == "complete" AND payment_status == "paid"` — never status
|
||||
#: alone (R-37: async methods can leave complete with payment still
|
||||
#: processing).
|
||||
CheckoutStatus = Literal["open", "complete", "expired"]
|
||||
|
||||
#: Payment status vocabulary (R-36). `no_payment_required` exists on the
|
||||
#: wire enum; v0.9 grants only on `paid`.
|
||||
PaymentStatus = Literal["paid", "unpaid", "no_payment_required"]
|
||||
|
||||
#: Subscription lifecycle states (D-083). G-305: `upgraded` is NOT a
|
||||
#: status — upgrade is a plan_id transition WITHIN `active`, recorded as
|
||||
#: a billing_event with provenance. `expired` here is the terminal past-
|
||||
#: due-grace outcome; the store owns the transition matrix (P5).
|
||||
SubscriptionStatus = Literal[
|
||||
"trialing", "active", "past_due", "cancelled", "expired"
|
||||
]
|
||||
|
||||
#: OUR canonical event names (D-083, R-43: Stripe has no
|
||||
#: `subscription.renewed`/`checkout.completed` — the provider boundary
|
||||
#: maps vendor names onto these; provider event ids are stored + deduped
|
||||
#: VERBATIM so dedupe stays truthful).
|
||||
CanonicalEventName = Literal[
|
||||
"checkout.completed",
|
||||
"invoice.paid",
|
||||
"invoice.payment_failed",
|
||||
"subscription.cancelled",
|
||||
"subscription.renewed",
|
||||
]
|
||||
|
||||
#: Tuple mirror of the Literal (docs + tests import this; keeps the enum
|
||||
#: and any exhaustive switch in one place).
|
||||
CANONICAL_EVENT_NAMES: tuple[CanonicalEventName, ...] = (
|
||||
"checkout.completed",
|
||||
"invoice.paid",
|
||||
"invoice.payment_failed",
|
||||
"subscription.cancelled",
|
||||
"subscription.renewed",
|
||||
)
|
||||
|
||||
|
||||
class WebhookSignatureError(ValueError):
|
||||
"""Webhook signature verification failed (D-077).
|
||||
|
||||
Raised with a precise reason (missing header / no v1 schemes / stale
|
||||
timestamp / signature mismatch). The webhook route maps this to 401 —
|
||||
a payment surface never processes an unverifiable event.
|
||||
"""
|
||||
|
||||
|
||||
class UnknownPaymentProviderError(ValueError):
|
||||
"""Raised for a provider name outside the contract, or a real
|
||||
provider selected without its required configuration (R-53 — the
|
||||
voice/embedding factory pattern).
|
||||
|
||||
main.py's lifespan CATCHES this and falls back to mock with a loud
|
||||
G-11 log; direct callers (tests) see the actionable raise.
|
||||
"""
|
||||
|
||||
|
||||
class Package(BaseModel):
|
||||
"""A one-time posting package catalog row (D-078/D-080).
|
||||
|
||||
`posts_limit` counts posting creations (consumed one per
|
||||
create_posting, newest-non-expired-first — D-080); `duration_days`
|
||||
bounds the purchase window from the buy time. `features` is the
|
||||
pricing-page copy list (P2 pins the wire shape both sides).
|
||||
"""
|
||||
|
||||
model_config = ConfigDict(frozen=True)
|
||||
|
||||
id: str = Field(min_length=1)
|
||||
name: str = Field(min_length=1)
|
||||
#: D-081: integer cents, ge=0 — currency usd fixed; never a float.
|
||||
price_cents: int = Field(ge=0)
|
||||
posts_limit: int = Field(ge=1)
|
||||
duration_days: int = Field(ge=1)
|
||||
features: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
class Plan(BaseModel):
|
||||
"""A recurring talent-access plan catalog row (D-078/D-080).
|
||||
|
||||
`interval` distinguishes the billing cadence; entitlement derives
|
||||
from the subscription's `expires_at` extension on each renewal
|
||||
(D-083 — idempotent per event dedupe).
|
||||
"""
|
||||
|
||||
model_config = ConfigDict(frozen=True)
|
||||
|
||||
id: str = Field(min_length=1)
|
||||
name: str = Field(min_length=1)
|
||||
#: D-081: integer cents, ge=0 — currency usd fixed; never a float.
|
||||
price_cents: int = Field(ge=0)
|
||||
interval: PlanInterval
|
||||
features: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
class CheckoutSessionSpec(BaseModel):
|
||||
"""What the operator asks a provider to create (R-33..R-35).
|
||||
|
||||
The checkout route resolves `item_id` against the catalog and
|
||||
carries the SNAPSHOT forward (D-078: `price_cents` + `item_name`
|
||||
copied at buy time — catalog edits never rewrite purchase
|
||||
history; the provider turns them into `line_items[0][price_data]`,
|
||||
R-35). `client_reference_id` is our reconciliation key (R-34 — the
|
||||
local checkout_sessions row id). `metadata` rides the session both
|
||||
directions (D-076: operator_ref + employer_id provenance). G-310:
|
||||
`success_url`/`cancel_url` default from `public_base_url` — a
|
||||
hosted checkout cannot be created without them (R-34).
|
||||
"""
|
||||
|
||||
model_config = ConfigDict(frozen=True)
|
||||
|
||||
mode: CheckoutMode
|
||||
item_id: str = Field(min_length=1)
|
||||
#: D-078 snapshot: the catalog price at buy time (D-081 cents).
|
||||
price_cents: int = Field(ge=0)
|
||||
#: D-078 snapshot: the catalog name at buy time.
|
||||
item_name: str = Field(min_length=1)
|
||||
#: Recurring cadence for plans ("month"/"year"); empty for packages.
|
||||
interval: str = ""
|
||||
success_url: str = ""
|
||||
cancel_url: str = ""
|
||||
client_reference_id: str = Field(min_length=1, max_length=200)
|
||||
metadata: dict[str, str] = Field(default_factory=dict)
|
||||
|
||||
|
||||
class CheckoutSession(BaseModel):
|
||||
"""Provider session state (R-36 normalized fields).
|
||||
|
||||
`url` is present only while a session is open (hosted checkout);
|
||||
`expires_at` bounds the payment window (R-34: 30m–24h on Stripe).
|
||||
"""
|
||||
|
||||
model_config = ConfigDict(frozen=True)
|
||||
|
||||
id: str = Field(min_length=1)
|
||||
url: str = ""
|
||||
status: CheckoutStatus
|
||||
payment_status: PaymentStatus
|
||||
mode: CheckoutMode
|
||||
expires_at: datetime | None = None
|
||||
|
||||
|
||||
class SubscriptionRef(BaseModel):
|
||||
"""A provider subscription handle (R-41/R-42 normalized states).
|
||||
|
||||
The store owns the lifecycle rows; this is what provider calls
|
||||
(cancel/update) and webhook payloads exchange.
|
||||
"""
|
||||
|
||||
model_config = ConfigDict(frozen=True)
|
||||
|
||||
id: str = Field(min_length=1)
|
||||
status: SubscriptionStatus
|
||||
|
||||
|
||||
class CanonicalBillingEvent(BaseModel):
|
||||
"""A provider event normalized onto OUR vocabulary (D-083, R-43).
|
||||
|
||||
`payload` is UNTRUSTED (G-302): webhook processing treats it as ID
|
||||
references only — session/subscription state resolves from LOCAL
|
||||
rows; purchase price/name come from the stored snapshot (D-078),
|
||||
never from the event body.
|
||||
"""
|
||||
|
||||
model_config = ConfigDict(frozen=True)
|
||||
|
||||
name: CanonicalEventName
|
||||
payload: dict[str, Any] = Field(default_factory=dict)
|
||||
|
||||
|
||||
class VerifiedEvent(BaseModel):
|
||||
"""What verify_webhook returns: the authenticated event.
|
||||
|
||||
Verification authenticates the TRANSPORT (HMAC over the raw body);
|
||||
`event` is the parsed body AFTER the signature gate. Providers that
|
||||
need raw-body parsing keep it inside their own verify_webhook.
|
||||
"""
|
||||
|
||||
model_config = ConfigDict(frozen=True)
|
||||
|
||||
event: CanonicalBillingEvent
|
||||
#: Provider event id, stored + deduped VERBATIM (R-43/D-083 — never
|
||||
#: normalized; the UniqueConstraint is on this exact string).
|
||||
provider_event_id: str = ""
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class PaymentProvider(Protocol):
|
||||
"""The payment port (D-075): checkout + subscriptions + webhooks.
|
||||
|
||||
Two implementations ship in-milestone: deterministic mock (default —
|
||||
tests never call a real provider) and Stripe-compatible REST (P3,
|
||||
exercised ONLY through httpx.MockTransport byte-contract tests).
|
||||
Never imports agents/api; selected by `factory.py` from Settings.
|
||||
"""
|
||||
|
||||
async def create_checkout_session(
|
||||
self, spec: CheckoutSessionSpec
|
||||
) -> CheckoutSession:
|
||||
"""Create a provider checkout session for a catalog item."""
|
||||
...
|
||||
|
||||
async def retrieve_session(self, session_id: str) -> CheckoutSession | None:
|
||||
"""Fetch session state; None when the provider does not know the id."""
|
||||
...
|
||||
|
||||
async def cancel_subscription(
|
||||
self, subscription_id: str, *, at_period_end: bool = False
|
||||
) -> SubscriptionRef | None:
|
||||
"""Cancel a subscription (R-46: immediate DELETE or deferred
|
||||
cancel_at_period_end); None when unknown to the provider."""
|
||||
...
|
||||
|
||||
async def update_subscription(
|
||||
self, subscription_id: str, new_price_cents: int
|
||||
) -> SubscriptionRef | None:
|
||||
"""Move a subscription to a new price (R-47: the provider resolves
|
||||
the subscription_item id inside — items[0][id] must be in the
|
||||
request or the new price is ADDED alongside the old → dual
|
||||
charge)."""
|
||||
...
|
||||
|
||||
def verify_webhook(
|
||||
self,
|
||||
raw_body: bytes,
|
||||
signature_header: str,
|
||||
*,
|
||||
now: float | None = None,
|
||||
) -> VerifiedEvent:
|
||||
"""Authenticate + parse a webhook delivery (D-077).
|
||||
|
||||
`raw_body` must be the exact un-parsed bytes (risk-1); raises
|
||||
`WebhookSignatureError` on any verification failure — the route
|
||||
maps that to 401, never processes further.
|
||||
"""
|
||||
...
|
||||
|
||||
def normalize_event(self, provider_event: dict[str, Any]) -> CanonicalBillingEvent:
|
||||
"""Map a provider-native event payload onto our canonical names
|
||||
(R-43). Mock speaks canonical names directly → passthrough."""
|
||||
...
|
||||
@@ -0,0 +1,105 @@
|
||||
"""Seeded billing catalog — the one source of truth for pricing (D-078).
|
||||
|
||||
The catalog mirrors the pricing page's tier structure (REQ-017 /
|
||||
REQ-9-002): prices + names + feature copy live HERE and flow to the
|
||||
page via `/v1/billing/catalog` — tier copy is data-driven, never
|
||||
hardcoded on both sides (D-079's no-drift rule). Seeding is idempotent
|
||||
(`SQLiteBillingStore.seed_catalog` upserts by id), so the app lifespan
|
||||
can seed on every boot.
|
||||
|
||||
Enterprise tiers: the pricing page models them as "Custom" — the pilot
|
||||
catalog keeps that honesty by seeding them as price_cents=0 contact
|
||||
tiers (checkout never applies; an operator grants enterprise manually
|
||||
per D-080's unlimited path). The features copy records the
|
||||
"Contact Sales" semantics verbatim from the page.
|
||||
|
||||
Money (D-081): integer cents — 4900 = $49.00; currency `usd` fixed.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from .base import Package, Plan
|
||||
from .store import BillingStore
|
||||
|
||||
SEED_PACKAGES: list[Package] = [
|
||||
Package(
|
||||
id="pkg-single",
|
||||
name="Single Post",
|
||||
price_cents=4900,
|
||||
posts_limit=1,
|
||||
duration_days=30,
|
||||
features=[
|
||||
"1 job posting",
|
||||
"30 days live",
|
||||
"Basic analytics",
|
||||
"Standard placement",
|
||||
],
|
||||
),
|
||||
Package(
|
||||
id="pkg-bundle",
|
||||
name="Bundle",
|
||||
price_cents=39900,
|
||||
posts_limit=10,
|
||||
duration_days=90,
|
||||
features=[
|
||||
"10 job postings",
|
||||
"90 days each",
|
||||
"Advanced analytics",
|
||||
"Priority placement",
|
||||
],
|
||||
),
|
||||
Package(
|
||||
id="pkg-enterprise",
|
||||
name="Enterprise",
|
||||
price_cents=0,
|
||||
posts_limit=1000,
|
||||
duration_days=365,
|
||||
features=[
|
||||
"Unlimited postings",
|
||||
"Dedicated account manager",
|
||||
"API access",
|
||||
"Custom branding",
|
||||
"Custom pricing — contact sales (operator-granted at pilot)",
|
||||
],
|
||||
),
|
||||
]
|
||||
|
||||
SEED_PLANS: list[Plan] = [
|
||||
Plan(
|
||||
id="plan-starter",
|
||||
name="Starter",
|
||||
price_cents=9900,
|
||||
interval="month",
|
||||
features=["Browse talent database", "10 candidate views/mo", "Basic filters"],
|
||||
),
|
||||
Plan(
|
||||
id="plan-pro",
|
||||
name="Pro",
|
||||
price_cents=29900,
|
||||
interval="month",
|
||||
features=[
|
||||
"Unlimited views",
|
||||
"AI matching",
|
||||
"Advanced filters",
|
||||
"Saved searches",
|
||||
],
|
||||
),
|
||||
Plan(
|
||||
id="plan-enterprise",
|
||||
name="Enterprise",
|
||||
price_cents=0,
|
||||
interval="year",
|
||||
features=[
|
||||
"Everything in Pro",
|
||||
"API access",
|
||||
"Bulk export",
|
||||
"Dedicated CSM",
|
||||
"Custom pricing — contact sales (operator-granted at pilot)",
|
||||
],
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
def seed_billing_catalog(store: BillingStore) -> None:
|
||||
"""Idempotent catalog seeding (D-078) — safe on every boot."""
|
||||
store.seed_catalog(SEED_PACKAGES, SEED_PLANS)
|
||||
@@ -0,0 +1,71 @@
|
||||
"""Payment provider factory (D-075, R-53, REQ-9-001).
|
||||
|
||||
`AI_PAYMENT_PROVIDER = mock | stripe` (default: mock — the no-key path
|
||||
is first-class; tests never call a real provider). Mirrors the
|
||||
voice/embedding factory pattern: the factory raises
|
||||
`UnknownPaymentProviderError` with an actionable message for direct
|
||||
callers (tests), while the lifespan in main.py CATCHES it and falls
|
||||
back to mock with a loud log — a typo'd env must never crash the
|
||||
unattended boot (G-11).
|
||||
|
||||
P3: `stripe` is REAL (billing/stripe.py) — but needs its API key,
|
||||
webhook secret, AND `public_base_url` (G-310: hosted checkout cannot
|
||||
build success/cancel URLs without it); a missing piece raises the
|
||||
actionable error the lifespan catches → G-11 mock fallback. The
|
||||
http_client rides in from main.py's shared pool (R-33).
|
||||
|
||||
Webhook secret (D-077): the settings default is the empty string —
|
||||
UNSET → the factory substitutes a per-boot random secret (the
|
||||
telemetry_ingest_secret pattern). Restart invalidates it, so stale
|
||||
signed deliveries fail: webhooks fail closed when unconfigured, which
|
||||
is correct for a payment surface.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import secrets
|
||||
|
||||
import httpx
|
||||
|
||||
from ..config import Settings
|
||||
from .base import PaymentProvider, UnknownPaymentProviderError
|
||||
from .mock import MockPaymentProvider
|
||||
|
||||
|
||||
def resolve_webhook_secret(settings: Settings) -> str:
|
||||
"""Configured `AI_WEBHOOK_SECRET` verbatim; unset → per-boot random
|
||||
(fail-closed webhooks, D-077 — the telemetry_ingest_secret shape)."""
|
||||
if settings.webhook_secret:
|
||||
return settings.webhook_secret
|
||||
return secrets.token_urlsafe(32)
|
||||
|
||||
|
||||
def payment_provider_from_settings(
|
||||
settings: Settings, http_client: httpx.AsyncClient | None = None
|
||||
) -> PaymentProvider:
|
||||
"""Select the payment provider by settings (env `AI_PAYMENT_PROVIDER`).
|
||||
|
||||
The selected provider gets the webhook secret resolved here
|
||||
(D-077). Stripe needs the shared httpx pool — main.py passes its
|
||||
app.state client; direct test callers construct their own.
|
||||
"""
|
||||
name = (settings.payment_provider or "mock").strip().lower()
|
||||
webhook_secret = resolve_webhook_secret(settings)
|
||||
if name == "mock":
|
||||
return MockPaymentProvider(webhook_secret=webhook_secret)
|
||||
if name == "stripe":
|
||||
# R-53/G-310: config errors (key/secret/base_url) surface from
|
||||
# the stripe factory's own gate — the operator-facing ones;
|
||||
# the httpx pool is a caller concern checked after config.
|
||||
from .stripe import stripe_provider_from_settings, validate_stripe_config
|
||||
|
||||
validate_stripe_config(settings)
|
||||
if http_client is None:
|
||||
raise UnknownPaymentProviderError(
|
||||
"stripe provider needs the shared httpx pool — "
|
||||
"pass http_client (main.py does; tests construct one)"
|
||||
)
|
||||
return stripe_provider_from_settings(settings, http_client)
|
||||
raise UnknownPaymentProviderError(
|
||||
f"unknown AI_PAYMENT_PROVIDER {name!r}: use 'mock' or 'stripe'"
|
||||
)
|
||||
@@ -0,0 +1,241 @@
|
||||
"""Deterministic mock payment provider (D-075, REQ-9-001).
|
||||
|
||||
Stripe-shaped without any network: sessions (`cs_mock_...` ids), the
|
||||
same HMAC webhook scheme (via webhooks.mint/verify — byte-identical to
|
||||
the real provider path), and canonical event names spoken directly
|
||||
(normalize_event is a passthrough — R-43's boundary maps VENDOR names;
|
||||
the mock has none to map). Tests never call a real provider; the
|
||||
mock-complete path (D-082, P3) mints a signed event through the REAL
|
||||
webhook processing via `mint_event`.
|
||||
|
||||
Id honesty (the identity-mock unique-mint lesson, verified there):
|
||||
session ids are minted UNIQUELY per create call — a monotonic counter
|
||||
plus per-process seed from `secrets`. A deterministic id derived from
|
||||
the spec would collide on any retry/re-entry of the same purchase
|
||||
request and the store's per-session idempotency (G-303) would silently
|
||||
conflate distinct logical checkouts. Uniqueness per call is the
|
||||
contract; determinism of VERDICTS (what tests pin) is preserved — the
|
||||
session lifecycle is scriptable, not the ids.
|
||||
|
||||
Session lifecycle: create → status open / payment unpaid; the operator
|
||||
completes out-of-band payment via `confirm_completion` (the D-076
|
||||
pilot flow — P3's admin-gated mock-complete route calls this) →
|
||||
status complete / payment_status paid (the R-37 grant predicate).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import itertools
|
||||
import json
|
||||
import secrets
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
from . import webhooks
|
||||
from .base import (
|
||||
CanonicalBillingEvent,
|
||||
CheckoutSession,
|
||||
CheckoutSessionSpec,
|
||||
SubscriptionRef,
|
||||
VerifiedEvent,
|
||||
)
|
||||
|
||||
#: Session payment window (R-34's shape; Stripe allows 30m–24h — the
|
||||
#: mock keeps a roomy 24h default so operator-mediated completion is
|
||||
#: never raced in the pilot).
|
||||
_SESSION_TTL = timedelta(hours=24)
|
||||
|
||||
#: Event-id prefix — provider event ids are stored + deduped VERBATIM
|
||||
#: (R-43/D-083); the mock mints them uniquely like session ids.
|
||||
_EVENT_ID_PREFIX = "evt_mock_"
|
||||
|
||||
|
||||
class MockPaymentProvider:
|
||||
"""In-memory, deterministic, zero-network PaymentProvider.
|
||||
|
||||
Scriptable sessions + real-scheme webhook minting — the full
|
||||
checkout→webhook loop is provable without any vendor.
|
||||
"""
|
||||
|
||||
def __init__(self, webhook_secret: str = "") -> None:
|
||||
# Per-process nonce: ids are opaque handles, never derived from
|
||||
# user input — counter + nonce keeps ids unique within and
|
||||
# across provider instances on one box.
|
||||
self._nonce = secrets.randbits(32)
|
||||
self._session_counter = itertools.count()
|
||||
self._event_counter = itertools.count()
|
||||
# Sessions by id: the provider's view of checkout state.
|
||||
self._sessions: dict[str, CheckoutSession] = {}
|
||||
# Subscriptions by id: created on subscription-mode completion
|
||||
# (P5 drives the lifecycle; the mock keeps the ref shape honest).
|
||||
self._subscriptions: dict[str, SubscriptionRef] = {}
|
||||
self._webhook_secret = webhook_secret or secrets.token_urlsafe(32)
|
||||
|
||||
# -- ids -----------------------------------------------------------------
|
||||
|
||||
def _mint_session_id(self) -> str:
|
||||
# Stripe-shaped cs_ prefix + mock marker (R-36's id shape; the
|
||||
# mock marker keeps logs/test failures self-explanatory).
|
||||
return (
|
||||
f"cs_mock_{self._nonce:08x}{next(self._session_counter):08x}"
|
||||
)
|
||||
|
||||
def _mint_event_id(self) -> str:
|
||||
return (
|
||||
f"{_EVENT_ID_PREFIX}{self._nonce:08x}{next(self._event_counter):08x}"
|
||||
)
|
||||
|
||||
# -- checkout ------------------------------------------------------------
|
||||
|
||||
async def create_checkout_session(
|
||||
self, spec: CheckoutSessionSpec
|
||||
) -> CheckoutSession:
|
||||
"""Create a session (status open, payment unpaid — R-36)."""
|
||||
session_id = self._mint_session_id()
|
||||
session = CheckoutSession(
|
||||
id=session_id,
|
||||
# Hosted-checkout stand-in: the mock has no hosted page; the
|
||||
# url is a stable pseudo-hosted pointer (never fetched).
|
||||
url=f"https://mock.local/checkout/{session_id}",
|
||||
status="open",
|
||||
payment_status="unpaid",
|
||||
mode=spec.mode,
|
||||
expires_at=datetime.now(UTC) + _SESSION_TTL,
|
||||
)
|
||||
self._sessions[session.id] = session
|
||||
return session
|
||||
|
||||
async def retrieve_session(self, session_id: str) -> CheckoutSession | None:
|
||||
return self._sessions.get(session_id)
|
||||
|
||||
async def confirm_completion(self, session_id: str) -> CheckoutSession:
|
||||
"""Flip a session to complete/paid (the R-37 grant predicate).
|
||||
|
||||
The out-of-band payment step of the pilot flow (D-076): P3's
|
||||
admin-gated mock-complete route calls this, then mints the
|
||||
signed webhook event through the real processing path. Unknown
|
||||
or already-complete sessions raise ValueError (fail loud, not
|
||||
idempotent-silent: the ROUTE owns idempotency via event dedupe).
|
||||
"""
|
||||
session = self._sessions.get(session_id)
|
||||
if session is None:
|
||||
raise ValueError(f"unknown checkout session {session_id!r}")
|
||||
if session.status != "open":
|
||||
raise ValueError(
|
||||
f"session {session_id!r} is {session.status!r}, not open"
|
||||
)
|
||||
completed = session.model_copy(
|
||||
update={"status": "complete", "payment_status": "paid"}
|
||||
)
|
||||
self._sessions[session_id] = completed
|
||||
if completed.mode == "subscription":
|
||||
# Subscription-mode completion creates the provider-side
|
||||
# subscription ref (R-36: `subscription` present in
|
||||
# subscription mode only).
|
||||
self._subscriptions.setdefault(
|
||||
f"sub_mock_{session_id.removeprefix('cs_')}",
|
||||
SubscriptionRef(
|
||||
id=f"sub_mock_{session_id.removeprefix('cs_')}",
|
||||
status="active",
|
||||
),
|
||||
)
|
||||
return completed
|
||||
|
||||
# -- subscriptions ---------------------------------------------------------
|
||||
|
||||
async def cancel_subscription(
|
||||
self, subscription_id: str, *, at_period_end: bool = False
|
||||
) -> SubscriptionRef | None:
|
||||
subscription = self._subscriptions.get(subscription_id)
|
||||
if subscription is None:
|
||||
return None
|
||||
# R-46 shape: immediate → cancelled now; deferred → stays active
|
||||
# until period end (the P5 webhook drives the final state).
|
||||
if at_period_end:
|
||||
return subscription
|
||||
cancelled = subscription.model_copy(update={"status": "cancelled"})
|
||||
self._subscriptions[subscription_id] = cancelled
|
||||
return cancelled
|
||||
|
||||
async def update_subscription(
|
||||
self, subscription_id: str, new_price_cents: int
|
||||
) -> SubscriptionRef | None:
|
||||
subscription = self._subscriptions.get(subscription_id)
|
||||
if subscription is None:
|
||||
return None
|
||||
# R-47 note: the real provider resolves items[0][id] inside; the
|
||||
# mock has no line items to dual-charge — price is recorded by
|
||||
# the store's plan snapshot (D-078), so this is a state no-op
|
||||
# that keeps the protocol shape honest.
|
||||
return subscription
|
||||
|
||||
# -- webhooks (D-077 scheme, shared core) -----------------------------------
|
||||
|
||||
def verify_webhook(
|
||||
self,
|
||||
raw_body: bytes,
|
||||
signature_header: str,
|
||||
*,
|
||||
now: float | None = None,
|
||||
) -> VerifiedEvent:
|
||||
"""Authenticate + parse a mock delivery via the shared core."""
|
||||
webhooks.verify(
|
||||
raw_body, signature_header, self._webhook_secret, now=now
|
||||
)
|
||||
body = _parse_json_body(raw_body)
|
||||
event = self.normalize_event(body)
|
||||
# Provider event id: top-level on the body, kept VERBATIM (the
|
||||
# R-43 rule — normalize the NAME, never the id).
|
||||
provider_event_id = str(body.get("id", ""))
|
||||
return VerifiedEvent(
|
||||
event=event, provider_event_id=provider_event_id
|
||||
)
|
||||
|
||||
def mint_event(
|
||||
self, name: str, payload: dict[str, Any]
|
||||
) -> tuple[bytes, str, str]:
|
||||
"""Mint a signed webhook delivery for tests + the complete path.
|
||||
|
||||
Returns `(raw_body, signature_header, provider_event_id)`. The
|
||||
body is the canonical event JSON — the exact bytes a provider
|
||||
would POST and the webhook route would read via
|
||||
`await request.body()`. Round-trip green through
|
||||
verify_webhook by construction (mint/verify share the scheme).
|
||||
"""
|
||||
provider_event_id = self._mint_event_id()
|
||||
body = json.dumps(
|
||||
{
|
||||
"id": provider_event_id,
|
||||
"name": name,
|
||||
"payload": payload,
|
||||
}
|
||||
).encode()
|
||||
header = webhooks.mint(self._webhook_secret, body)
|
||||
return body, header, provider_event_id
|
||||
|
||||
def normalize_event(
|
||||
self, provider_event: dict[str, Any]
|
||||
) -> CanonicalBillingEvent:
|
||||
"""Passthrough (R-43): the mock speaks canonical names directly."""
|
||||
name = str(provider_event.get("name", ""))
|
||||
if name not in (
|
||||
"checkout.completed",
|
||||
"invoice.paid",
|
||||
"invoice.payment_failed",
|
||||
"subscription.cancelled",
|
||||
"subscription.renewed",
|
||||
):
|
||||
raise ValueError(f"unknown event name {name!r}")
|
||||
payload = provider_event.get("payload")
|
||||
return CanonicalBillingEvent(
|
||||
name=name, # type: ignore[arg-type] # validated in-contract above
|
||||
payload=payload if isinstance(payload, dict) else {},
|
||||
)
|
||||
|
||||
|
||||
def _parse_json_body(raw_body: bytes) -> dict[str, Any]:
|
||||
"""Parse the event JSON body (post-verification, risk-1 safe)."""
|
||||
decoded = json.loads(raw_body.decode("utf-8"))
|
||||
if not isinstance(decoded, dict):
|
||||
raise ValueError("event body is not a JSON object")
|
||||
return decoded
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,343 @@
|
||||
"""StripePaymentProvider — Stripe-compatible REST via the shared httpx
|
||||
pool (REQ-9-003, D-75/R-33..R-50).
|
||||
|
||||
Form-encoded bodies with bracket nesting (R-33: `line_items[0]
|
||||
[price_data][currency]=usd` — NOT JSON), HTTP Basic auth, an
|
||||
Idempotency-Key per logical operation (R-49: a double-submit
|
||||
otherwise creates two sessions), and the webhook signature scheme
|
||||
shared with the mock (webhooks.py — D-077 is byte-for-byte Stripe's
|
||||
`t=...,v1=...` HMAC-SHA256 over `{t}.{raw_body}`).
|
||||
|
||||
Exercised ONLY through httpx.MockTransport byte-contract tests
|
||||
(D-075) — tests never call the cloud. Event normalization maps
|
||||
vendor names onto OUR canonical vocabulary (R-43); provider event ids
|
||||
are stored + deduped VERBATIM.
|
||||
|
||||
G-310: `success_url`/`cancel_url` default from `public_base_url` —
|
||||
without them a hosted checkout session cannot be created (R-34:
|
||||
success_url is required).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import json
|
||||
import uuid
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
from ..config import Settings
|
||||
from .base import (
|
||||
CanonicalBillingEvent,
|
||||
CanonicalEventName,
|
||||
CheckoutSession,
|
||||
CheckoutSessionSpec,
|
||||
SubscriptionRef,
|
||||
SubscriptionStatus,
|
||||
UnknownPaymentProviderError,
|
||||
VerifiedEvent,
|
||||
WebhookSignatureError,
|
||||
)
|
||||
from .webhooks import verify as verify_webhook_signature
|
||||
|
||||
#: R-43: vendor event type → our canonical name. `subscription.renewed`
|
||||
#: has no vendor equivalent — a renewal IS an invoice.paid on a
|
||||
#: recurring subscription; the corroborating `customer.subscription.
|
||||
#: updated` maps alongside it (recorded, not conflated).
|
||||
_EVENT_NAME_MAP: dict[str, CanonicalEventName] = {
|
||||
"checkout.session.completed": "checkout.completed",
|
||||
"invoice.paid": "invoice.paid",
|
||||
"invoice.payment_succeeded": "invoice.paid",
|
||||
"invoice.payment_failed": "invoice.payment_failed",
|
||||
"customer.subscription.deleted": "subscription.cancelled",
|
||||
"customer.subscription.updated": "subscription.renewed",
|
||||
}
|
||||
|
||||
|
||||
#: R-42: vendor status spellings → OUR enum (Stripe writes `canceled`
|
||||
#: with one L; our vocabulary is `cancelled`).
|
||||
_STATUS_MAP: dict[str, SubscriptionStatus] = {
|
||||
"trialing": "trialing",
|
||||
"incomplete": "trialing",
|
||||
"active": "active",
|
||||
"past_due": "past_due",
|
||||
"canceled": "cancelled",
|
||||
"unpaid": "expired",
|
||||
"incomplete_expired": "expired",
|
||||
}
|
||||
|
||||
|
||||
def _normalize_status(raw: Any, default: SubscriptionStatus) -> SubscriptionStatus:
|
||||
return _STATUS_MAP.get(str(raw), default)
|
||||
|
||||
|
||||
class StripePaymentProvider:
|
||||
"""Stripe-compatible REST implementation of PaymentProvider."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
http_client: httpx.AsyncClient,
|
||||
api_key: str,
|
||||
webhook_secret: str,
|
||||
base_url: str = "https://api.stripe.com",
|
||||
) -> None:
|
||||
self._http = http_client
|
||||
self._api_key = api_key
|
||||
self._webhook_secret = webhook_secret
|
||||
self._base_url = base_url.rstrip("/")
|
||||
|
||||
# -- helpers ------------------------------------------------------------
|
||||
|
||||
def _auth_headers(self) -> dict[str, str]:
|
||||
# R-33: HTTP Basic with the secret key as the username and an
|
||||
# empty password (`-u sk_...:`).
|
||||
basic = base64.b64encode(f"{self._api_key}:".encode()).decode()
|
||||
return {"Authorization": f"Basic {basic}"}
|
||||
|
||||
def _raise_for_status(self, response: httpx.Response) -> None:
|
||||
if response.status_code >= 400:
|
||||
# A-305: sanitize — the api key must never appear in any
|
||||
# raised exception (the embedding-test precedent).
|
||||
detail = response.text
|
||||
if self._api_key and self._api_key in detail:
|
||||
detail = detail.replace(self._api_key, "[redacted]")
|
||||
raise httpx.HTTPStatusError(
|
||||
f"stripe {response.status_code}: {detail}",
|
||||
request=response.request,
|
||||
response=response,
|
||||
)
|
||||
|
||||
async def _form_post(self, path: str, data: dict[str, Any]) -> dict[str, Any]:
|
||||
headers = self._auth_headers()
|
||||
# R-49: an idempotency key per logical POST — a network retry of
|
||||
# session creation must not mint two sessions.
|
||||
headers["Idempotency-Key"] = str(uuid.uuid4())
|
||||
response = await self._http.post(
|
||||
f"{self._base_url}{path}",
|
||||
data=data,
|
||||
headers=headers,
|
||||
)
|
||||
self._raise_for_status(response)
|
||||
return response.json()
|
||||
|
||||
# -- checkout sessions (R-33..R-37) ---------------------------------------
|
||||
|
||||
async def create_checkout_session(
|
||||
self, spec: CheckoutSessionSpec
|
||||
) -> CheckoutSession:
|
||||
# R-33/R-35: form-encoded with bracket nesting. One-time vs
|
||||
# recurring differs only by price_data[recurring][interval]
|
||||
# (R-35) — the snapshot price rides the wire (D-078/D-081).
|
||||
data: dict[str, Any] = {
|
||||
"mode": spec.mode,
|
||||
"client_reference_id": spec.client_reference_id,
|
||||
"line_items[0][quantity]": "1",
|
||||
"line_items[0][price_data][currency]": "usd",
|
||||
"line_items[0][price_data][unit_amount]": str(spec.price_cents),
|
||||
"line_items[0][price_data][product_data][name]": spec.item_name,
|
||||
}
|
||||
if spec.interval:
|
||||
data["line_items[0][price_data][recurring][interval]"] = spec.interval
|
||||
for key, value in spec.metadata.items():
|
||||
data[f"metadata[{key}]"] = value
|
||||
# G-310: hosted checkout requires success_url (R-34) — the
|
||||
# checkout route defaults these from public_base_url.
|
||||
data["success_url"] = spec.success_url
|
||||
data["cancel_url"] = spec.cancel_url
|
||||
body = await self._form_post("/v1/checkout/sessions", data)
|
||||
return self._session_from_api(body)
|
||||
|
||||
async def retrieve_session(self, session_id: str) -> CheckoutSession | None:
|
||||
try:
|
||||
body = await self._get(f"/v1/checkout/sessions/{session_id}")
|
||||
except httpx.HTTPStatusError as exc:
|
||||
if exc.response.status_code == 404:
|
||||
return None
|
||||
raise
|
||||
return self._session_from_api(body)
|
||||
|
||||
async def _get(self, path: str) -> dict[str, Any]:
|
||||
response = await self._http.get(
|
||||
f"{self._base_url}{path}",
|
||||
headers=self._auth_headers(),
|
||||
)
|
||||
self._raise_for_status(response)
|
||||
return response.json()
|
||||
|
||||
@staticmethod
|
||||
def _session_from_api(body: dict[str, Any]) -> CheckoutSession:
|
||||
# Final-review fix: coerce + default every enum-adjacent value —
|
||||
# a vendor body with an unexpected status spelling (or a missing
|
||||
# one) must not crash the route with a pydantic ValidationError
|
||||
# (the G-306 never-500 discipline).
|
||||
status = str(body.get("status", "open"))
|
||||
if status not in ("open", "complete", "expired"):
|
||||
status = "open"
|
||||
payment_status = str(body.get("payment_status", "unpaid"))
|
||||
if payment_status not in ("paid", "unpaid", "no_payment_required"):
|
||||
payment_status = "unpaid"
|
||||
mode = str(body.get("mode", "payment"))
|
||||
if mode not in ("payment", "setup", "subscription"):
|
||||
mode = "payment"
|
||||
return CheckoutSession(
|
||||
id=str(body.get("id", "")),
|
||||
url=str(body.get("url") or ""),
|
||||
status=status, # type: ignore[arg-type]
|
||||
payment_status=payment_status, # type: ignore[arg-type]
|
||||
mode=mode, # type: ignore[arg-type]
|
||||
expires_at=None,
|
||||
)
|
||||
|
||||
# -- subscriptions (R-46/R-47) --------------------------------------------
|
||||
|
||||
async def cancel_subscription(
|
||||
self, subscription_id: str, *, at_period_end: bool = False
|
||||
) -> SubscriptionRef | None:
|
||||
try:
|
||||
if at_period_end:
|
||||
body = await self._form_post(
|
||||
f"/v1/subscriptions/{subscription_id}",
|
||||
{"cancel_at_period_end": "true"},
|
||||
)
|
||||
else:
|
||||
response = await self._http.delete(
|
||||
f"{self._base_url}/v1/subscriptions/{subscription_id}",
|
||||
headers=self._auth_headers(),
|
||||
)
|
||||
self._raise_for_status(response)
|
||||
body = response.json()
|
||||
except httpx.HTTPStatusError as exc:
|
||||
if exc.response.status_code == 404:
|
||||
return None
|
||||
raise
|
||||
return SubscriptionRef(
|
||||
id=str(body.get("id", subscription_id)),
|
||||
status=_normalize_status(body.get("status", "cancelled"), "cancelled"),
|
||||
)
|
||||
|
||||
async def update_subscription(
|
||||
self, subscription_id: str, new_price_cents: int
|
||||
) -> SubscriptionRef | None:
|
||||
"""R-47: the provider resolves the subscription_item id INSIDE —
|
||||
`items[0][id]` must ride the update or the new price is ADDED
|
||||
alongside the old (dual-charge bug, pinned by byte-contract)."""
|
||||
try:
|
||||
current = await self._get(f"/v1/subscriptions/{subscription_id}")
|
||||
items = current.get("items", {}).get("data", [])
|
||||
if not items:
|
||||
return None
|
||||
item_id = str(items[0]["id"])
|
||||
body = await self._form_post(
|
||||
f"/v1/subscriptions/{subscription_id}",
|
||||
{
|
||||
"items[0][id]": item_id,
|
||||
"items[0][price_data][currency]": "usd",
|
||||
"items[0][price_data][unit_amount]": str(new_price_cents),
|
||||
"items[0][price_data][product_data][name]": "nextcraft plan",
|
||||
"items[0][price_data][recurring][interval]": "month",
|
||||
},
|
||||
)
|
||||
except httpx.HTTPStatusError as exc:
|
||||
if exc.response.status_code == 404:
|
||||
return None
|
||||
raise
|
||||
return SubscriptionRef(
|
||||
id=str(body.get("id", subscription_id)),
|
||||
status=_normalize_status(body.get("status", "active"), "active"),
|
||||
)
|
||||
|
||||
# -- webhooks (D-077 — the shared scheme) ---------------------------------
|
||||
|
||||
def verify_webhook(
|
||||
self,
|
||||
raw_body: bytes,
|
||||
signature_header: str,
|
||||
*,
|
||||
now: float | None = None,
|
||||
) -> VerifiedEvent:
|
||||
verify_webhook_signature(
|
||||
raw_body,
|
||||
signature_header,
|
||||
self._webhook_secret,
|
||||
now=now,
|
||||
)
|
||||
payload = _parse_event_payload(raw_body)
|
||||
return VerifiedEvent(
|
||||
event=self.normalize_event(payload),
|
||||
provider_event_id=str(payload.get("id", "")),
|
||||
)
|
||||
|
||||
def normalize_event(
|
||||
self, provider_event: dict[str, Any]
|
||||
) -> CanonicalBillingEvent:
|
||||
"""R-43: map the vendor event onto OUR canonical vocabulary —
|
||||
BOTH the name and the payload keys. Final-review fix: the
|
||||
vendor object's key spellings (`id`, `subscription`) never
|
||||
become the canonical keys (`session_id`, `subscription_id`)
|
||||
the processing route reads, so under real Stripe every
|
||||
checkout/renewal resolved no local row and landed unmatched
|
||||
with NO entitlement — the mock speaks canonical keys directly
|
||||
and hid the desync."""
|
||||
vendor_type = str(provider_event.get("type", ""))
|
||||
mapped = _EVENT_NAME_MAP.get(vendor_type)
|
||||
if mapped is None:
|
||||
raise UnknownPaymentProviderError(
|
||||
f"unmapped provider event type {vendor_type!r}"
|
||||
)
|
||||
payload = dict(provider_event.get("data", {}).get("object", {}))
|
||||
canonical: dict[str, Any] = dict(payload)
|
||||
if vendor_type == "checkout.session.completed":
|
||||
canonical["session_id"] = str(payload.get("id", ""))
|
||||
else:
|
||||
# invoice.* + customer.subscription.*: Stripe carries the
|
||||
# subscription ref at data.object.subscription (and, on
|
||||
# subscription objects, at data.object.id).
|
||||
subscription_ref = payload.get("subscription") or payload.get("id")
|
||||
canonical["subscription_id"] = str(subscription_ref or "")
|
||||
return CanonicalBillingEvent(name=mapped, payload=canonical)
|
||||
|
||||
|
||||
def _parse_event_payload(raw_body: bytes) -> dict[str, Any]:
|
||||
try:
|
||||
parsed = json.loads(raw_body.decode("utf-8"))
|
||||
except (UnicodeDecodeError, ValueError) as exc:
|
||||
raise WebhookSignatureError(f"event body is not JSON: {exc}") from exc
|
||||
if not isinstance(parsed, dict):
|
||||
raise WebhookSignatureError("event body is not a JSON object")
|
||||
return parsed
|
||||
|
||||
|
||||
def validate_stripe_config(settings: Settings) -> None:
|
||||
"""R-53/G-310: the actionable config gate — main.py's lifespan
|
||||
catches and falls back to mock with the loud G-11 log."""
|
||||
api_key = settings.payment_api_key.get_secret_value()
|
||||
if not api_key:
|
||||
raise UnknownPaymentProviderError(
|
||||
"AI_PAYMENT_PROVIDER=stripe requires AI_PAYMENT_API_KEY "
|
||||
"(env-only, D-014) — set it or drop back to the mock default"
|
||||
)
|
||||
if not settings.webhook_secret:
|
||||
raise UnknownPaymentProviderError(
|
||||
"AI_PAYMENT_PROVIDER=stripe requires AI_WEBHOOK_SECRET — "
|
||||
"webhooks fail closed without it (D-077)"
|
||||
)
|
||||
if not settings.public_base_url:
|
||||
raise UnknownPaymentProviderError(
|
||||
"AI_PAYMENT_PROVIDER=stripe requires AI_PUBLIC_BASE_URL — "
|
||||
"hosted checkout cannot build success/cancel URLs without it (G-310)"
|
||||
)
|
||||
|
||||
|
||||
def stripe_provider_from_settings(
|
||||
settings: Settings, http_client: httpx.AsyncClient
|
||||
) -> StripePaymentProvider:
|
||||
"""Factory wiring (R-53): validates config, then constructs the
|
||||
provider over the shared httpx pool."""
|
||||
validate_stripe_config(settings)
|
||||
return StripePaymentProvider(
|
||||
http_client=http_client,
|
||||
api_key=settings.payment_api_key.get_secret_value(),
|
||||
webhook_secret=settings.webhook_secret,
|
||||
)
|
||||
@@ -0,0 +1,142 @@
|
||||
"""Webhook signature verification core (D-077, R-38..R-40).
|
||||
|
||||
Byte-for-byte Stripe's scheme shape, shared by every provider so the
|
||||
mock and the real Stripe path verify identically (the byte-contract
|
||||
lesson): header `Stripe-Signature: t=<unix_seconds>,v1=<hex>` on one
|
||||
line; signed payload `"{timestamp}.{raw_body}"`; HMAC-SHA256 with the
|
||||
endpoint secret; constant-time comparison; ±300 s replay window.
|
||||
|
||||
Security properties (each pinned by tests/billing/test_webhooks.py):
|
||||
- raw body: verification needs the exact UN-PARSED bytes (risk-1) — the
|
||||
caller passes `raw_body: bytes`, never a pre-parsed model;
|
||||
- multiple `v1` values (secret rolls — R-38): verify iterates ALL v1
|
||||
candidates, any match wins (R-53 risk-5);
|
||||
- non-`v1` schemes (`v0` on Stripe test events, unknown future ones):
|
||||
ignored entirely — a v0-only header has no v1 to check and fails
|
||||
(downgrade protection);
|
||||
- replay window (R-40, Stripe default 300 s): the timestamp bounds how
|
||||
long a captured delivery can be replayed; `now` is injectable so
|
||||
tests are deterministic without sleeps (risk-4);
|
||||
- fail closed (D-077): every failure raises `WebhookSignatureError`
|
||||
with a precise reason — a payment surface never processes an
|
||||
unverifiable event.
|
||||
|
||||
`mint` exists for tests + the mock provider: it produces exactly what a
|
||||
signed provider delivery looks like, so the mock-complete path (D-082)
|
||||
can post through the REAL webhook processing.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import hmac
|
||||
import time
|
||||
|
||||
from .base import WebhookSignatureError
|
||||
|
||||
#: Replay tolerance in seconds (R-40: Stripe's official default; "don't
|
||||
#: use a tolerance of 0" — clock skew between provider and box is real).
|
||||
DEFAULT_TOLERANCE_S: float = 300.0
|
||||
|
||||
|
||||
def _parse_header(header: str) -> tuple[int | None, list[str]]:
|
||||
"""Parse `t=...,v1=...,v1=...` into (timestamp, v1 candidates).
|
||||
|
||||
Elements are comma-separated `key=value` pairs (R-38). Unknown
|
||||
schemes (v0, anything else) are ignored: only `v1` is ever checked.
|
||||
Returns timestamp None when the header carries no valid `t` pair.
|
||||
"""
|
||||
timestamp: int | None = None
|
||||
v1_candidates: list[str] = []
|
||||
for element in header.split(","):
|
||||
key, sep, value = element.strip().partition("=")
|
||||
if not sep:
|
||||
continue
|
||||
if key == "t":
|
||||
try:
|
||||
timestamp = int(value)
|
||||
except ValueError:
|
||||
# Malformed t → treat as absent; verify() fails on the
|
||||
# stale/missing-timestamp branch (fail closed).
|
||||
continue
|
||||
elif key == "v1":
|
||||
v1_candidates.append(value)
|
||||
return timestamp, v1_candidates
|
||||
|
||||
|
||||
def _compute_signature(
|
||||
secret: str, timestamp: int, raw_body: bytes
|
||||
) -> str:
|
||||
"""HMAC-SHA256 over `"{timestamp}.{raw_body}"` (R-39).
|
||||
|
||||
The timestamp is attacker-immutable in transit: changing `t` without
|
||||
the secret invalidates every v1 in the header.
|
||||
"""
|
||||
signed_payload = f"{timestamp}.".encode() + raw_body
|
||||
return hmac.new(
|
||||
secret.encode("utf-8"), signed_payload, hashlib.sha256
|
||||
).hexdigest()
|
||||
|
||||
|
||||
def mint(
|
||||
secret: str,
|
||||
raw_body: bytes,
|
||||
now: float | None = None,
|
||||
) -> str:
|
||||
"""Mint a `Stripe-Signature` header for `raw_body` (D-077 scheme).
|
||||
|
||||
Test + mock-provider helper (the mint half of the telemetry
|
||||
tokens.py precedent). `now` defaults to the wall clock; inject for
|
||||
determinism. Produces exactly one `t` + one `v1` pair — what a
|
||||
provider delivery carries.
|
||||
"""
|
||||
timestamp = int(now if now is not None else time.time())
|
||||
signature = _compute_signature(secret, timestamp, raw_body)
|
||||
return f"t={timestamp},v1={signature}"
|
||||
|
||||
|
||||
def verify(
|
||||
raw_body: bytes,
|
||||
header: str | None,
|
||||
secret: str,
|
||||
*,
|
||||
now: float | None = None,
|
||||
tolerance_s: float = DEFAULT_TOLERANCE_S,
|
||||
) -> tuple[int, list[str]]:
|
||||
"""Verify a `Stripe-Signature` header against the raw body.
|
||||
|
||||
Returns `(timestamp, v1_candidates)` on success — the parsed header
|
||||
the caller may want for replay bookkeeping. Raises
|
||||
`WebhookSignatureError` with a precise reason otherwise:
|
||||
|
||||
- missing/empty header → "missing Stripe-Signature header";
|
||||
- no `v1` schemes present → "no v1 signature schemes in header"
|
||||
(a v0-only header lands here — non-v1 schemes are ignored);
|
||||
- timestamp absent or outside ±tolerance_s of now → "stale
|
||||
timestamp" (replay window, R-40);
|
||||
- no v1 candidate matches → "signature mismatch" (constant-time
|
||||
compare per candidate — any match wins across secret rolls).
|
||||
"""
|
||||
if not header:
|
||||
raise WebhookSignatureError("missing Stripe-Signature header")
|
||||
timestamp, v1_candidates = _parse_header(header)
|
||||
if not v1_candidates:
|
||||
raise WebhookSignatureError(
|
||||
f"no v1 signature schemes in header {header!r} "
|
||||
"(non-v1 schemes are ignored)"
|
||||
)
|
||||
if timestamp is None:
|
||||
raise WebhookSignatureError(
|
||||
f"missing or malformed timestamp in header {header!r}"
|
||||
)
|
||||
current = now if now is not None else time.time()
|
||||
if abs(current - timestamp) > tolerance_s:
|
||||
raise WebhookSignatureError(
|
||||
f"stale timestamp {timestamp}: outside the "
|
||||
f"{tolerance_s:g}s replay window at {current:g}"
|
||||
)
|
||||
for candidate in v1_candidates:
|
||||
expected = _compute_signature(secret, timestamp, raw_body)
|
||||
if hmac.compare_digest(expected, candidate):
|
||||
return timestamp, v1_candidates
|
||||
raise WebhookSignatureError("signature mismatch: no v1 candidate matches")
|
||||
@@ -164,6 +164,16 @@ class Settings(BaseSettings):
|
||||
# (a loud boot warning names the fix, G-11).
|
||||
admin_token: SecretStr = SecretStr("")
|
||||
|
||||
# v0.10 employer auth (REQ-10-001, D-088): both throttle knobs —
|
||||
# plain ints, the identity_submits_per_min shape (R-60d). Keyed by
|
||||
# SUBMITTED EMAIL, never client IP (R-63); in-memory, per-process.
|
||||
# (a) Failed logins per email per rolling 900 s window → 429 with
|
||||
# the honest "wait" detail; a successful login clears it.
|
||||
# (b) Well-formed login+register attempts per rolling 60 s window
|
||||
# across all emails → 429 (G-314: failed passwords count).
|
||||
employer_login_failures_per_window: int = 5
|
||||
employer_auth_attempts_per_min: int = 30
|
||||
|
||||
# v0.6 P5 placeholder (D-056): the deployed origin for sitemap.xml /
|
||||
# robots.txt absolute URLs (consumed by the SEO phase; documented
|
||||
# now so operators see it beside the admin token).
|
||||
@@ -213,3 +223,24 @@ class Settings(BaseSettings):
|
||||
# A-302/D-041: upload guard before the provider call (webm/opus is
|
||||
# ~0.5-1MB/min, so 10MB tolerates very long answers).
|
||||
voice_max_audio_mb: int = 10
|
||||
|
||||
# v0.9 Payment Engine (REQ-9-001, D-075, R-53): payment provider
|
||||
# selection — 'mock' (default: deterministic, zero-network; tests
|
||||
# NEVER call a real payment API) or 'stripe' (real Stripe-compatible
|
||||
# REST, P3). A typo'd name raises at the factory; main.py's lifespan
|
||||
# catches it and falls back to mock with a loud log (G-11 — the
|
||||
# voice/embedding factory pattern).
|
||||
payment_provider: str = "mock"
|
||||
|
||||
# Real payment API key (Stripe sk_... class) — 'stripe' requires
|
||||
# this; 'mock' ignores it. Keys env-only (D-014), never committed,
|
||||
# never logged (SecretStr mirrors the admin token; tests use fixed
|
||||
# test secrets, never real ones).
|
||||
payment_api_key: SecretStr = SecretStr("")
|
||||
|
||||
# Webhook HMAC secret (D-077, the telemetry_ingest_secret pattern):
|
||||
# UNSET (empty default) → the factory substitutes a PER-BOOT RANDOM
|
||||
# secret — restart invalidates stale signed deliveries, so webhooks
|
||||
# FAIL CLOSED when unconfigured (401, never process unverifiable —
|
||||
# correct for a payment surface). Set for multi-process deploys.
|
||||
webhook_secret: str = ""
|
||||
|
||||
@@ -5,9 +5,11 @@ grounding (Task 6-1-04): no production code path imports this module. Retained a
|
||||
calibration history.
|
||||
|
||||
|
||||
Counterpart: packages/mock-data/ai-scenarios.ts (artifact IDs string-identical,
|
||||
D-021). Real process-trace grading is a v0.3+ engine (assessment engine);
|
||||
these pre-baked submissions stand in for artifact + defense evaluation.
|
||||
Historical note: artifact IDs were once string-synced with a TS counterpart
|
||||
(packages/mock-data/ai-scenarios.ts, D-021) — that module was deleted in
|
||||
v0.7 P4 (dead export); this corpus is the single source. Real process-trace
|
||||
grading is a v0.3+ engine (assessment engine); these pre-baked submissions
|
||||
stand in for artifact + defense evaluation.
|
||||
"""
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
@@ -5,9 +5,11 @@ no production code path imports this module. Retained as Phase-3 calibration his
|
||||
(corpus/trace_fixtures.py references it from TESTS only).
|
||||
|
||||
|
||||
Counterpart: packages/mock-data/ai-scenarios.ts (scenario IDs string-identical,
|
||||
D-021). Real sandbox telemetry is a v0.3+ engine (sandbox fabric); these
|
||||
scripted event streams stand in for the build-session process trace.
|
||||
Historical note: scenario IDs were once string-synced with a TS counterpart
|
||||
(packages/mock-data/ai-scenarios.ts, D-021) — that module was deleted in
|
||||
v0.7 P4 (dead export); this corpus is the single source. Real sandbox
|
||||
telemetry is a v0.3+ engine (sandbox fabric); these scripted event streams
|
||||
stand in for the build-session process trace.
|
||||
"""
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
"""Employer B2B auth module (REQ-10-001, D-086..D-097, v0.10).
|
||||
|
||||
The 8th domain module inside apps/ai-service (no new apps, no new ports,
|
||||
no new dependencies — the D-031 boundary): pydantic contracts
|
||||
(`base.py`), the D-027 store family's eighth SQLite store
|
||||
(`store.py`, R-57/D-095), and the stdlib scrypt KDF (`passwords.py`,
|
||||
D-086/R-55). Claim evidence (`claim_evidence.py`) and the auth routes
|
||||
(`api/employers.py` via DI) land with their owning phases. No
|
||||
`service.py` anywhere (R-57) — routes compose the store via api/ DI.
|
||||
|
||||
G-315: email fields are plain `str` with stdlib-only validation —
|
||||
pydantic `EmailStr` is BANNED (email-validator would be the first new
|
||||
dependency, breaking R-66/D-086).
|
||||
|
||||
D-097: employer accounts are UNVERIFIED — no learner gate
|
||||
(require_verified_age/allowlist) is ever composed on an employer route.
|
||||
|
||||
Boundary (D-031 family discipline): `employers/` never imports `agents/`
|
||||
or `api/`; this package imports stdlib + pydantic + `config` only.
|
||||
"""
|
||||
|
||||
from .base import (
|
||||
CLAIM_STATUSES,
|
||||
OWN_POSTING_STATUSES,
|
||||
ClaimEmployerRequest,
|
||||
ClaimStatus,
|
||||
EmployerAccount,
|
||||
EmployerClaim,
|
||||
EmployerMe,
|
||||
EmployerPostingCreate,
|
||||
EmployerPostingEdit,
|
||||
EmployerPostingWriteResponse,
|
||||
LoginEmployerRequest,
|
||||
OwnPostingsFacets,
|
||||
OwnPostingsResponse,
|
||||
OwnPostingSummary,
|
||||
RegisterEmployerRequest,
|
||||
TokenResponse,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"CLAIM_STATUSES",
|
||||
"ClaimEmployerRequest",
|
||||
"ClaimStatus",
|
||||
"EmployerAccount",
|
||||
"EmployerClaim",
|
||||
"EmployerMe",
|
||||
"EmployerPostingCreate",
|
||||
"EmployerPostingEdit",
|
||||
"EmployerPostingWriteResponse",
|
||||
"LoginEmployerRequest",
|
||||
"OWN_POSTING_STATUSES",
|
||||
"OwnPostingSummary",
|
||||
"OwnPostingsFacets",
|
||||
"OwnPostingsResponse",
|
||||
"RegisterEmployerRequest",
|
||||
"TokenResponse",
|
||||
]
|
||||
@@ -0,0 +1,343 @@
|
||||
"""Employer auth pydantic contracts (REQ-10-001, D-086..D-097).
|
||||
|
||||
The wire + domain shapes for the employer module. `EmployerAccount` /
|
||||
`EmployerClaim` are the domain rows served over the wire; the request
|
||||
pair carries G-315 email discipline + D-086 password min length;
|
||||
`TokenResponse` / `EmployerMe` are the auth route responses.
|
||||
|
||||
G-315: email fields are plain `str` with stdlib-only validation —
|
||||
non-empty, exactly one "@", non-empty domain, stripped + lowercased on
|
||||
normalize. pydantic `EmailStr` is BANNED (email-validator is not in the
|
||||
venv and adding it would be the first new dependency, breaking
|
||||
R-66/D-086).
|
||||
|
||||
D-097: `EmployerAccount.email_verified` is `Literal[False]` — the
|
||||
account is UNVERIFIED, displayed as such; never presented as verified.
|
||||
|
||||
Id honesty (A-305, the family rule): every id in this module is an
|
||||
opaque handle minted UNIQUELY per creation call — never derived from
|
||||
user input or a deterministic hash of it.
|
||||
|
||||
P3 (REQ-10-003, G-319): `OwnPostingSummary` REUSES the PostingSummary
|
||||
wire shape by subclassing marketplace.base.Posting (the PostingSummary
|
||||
serialization contract — never duplicated) + `applicant_count`. The PII
|
||||
boundary is binding: applicant COUNTS are the only applications-derived
|
||||
datum — learner identifiers never ride any employer-facing response.
|
||||
|
||||
Boundary (D-031 family): `employers/` never imports `agents/` or `api/`;
|
||||
stdlib + pydantic + the marketplace WIRE contracts (G-319's PostingSummary
|
||||
reuse — a pure-pydantic module, never a store/engine import) only.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any, Literal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
||||
|
||||
from ..marketplace.base import Posting
|
||||
|
||||
#: Claim lifecycle states (D-089): every claim starts pending; an
|
||||
#: operator approve/reject decides it. Approved activates ownership
|
||||
#: (one account : one entity); rejection frees the entity for a new
|
||||
#: claim. Deferred to P2's claim routes — the shape lands now.
|
||||
ClaimStatus = Literal["pending", "approved", "rejected"]
|
||||
|
||||
#: Tuple mirror of the Literal (docs + tests import this; keeps the enum
|
||||
#: and any exhaustive switch in one place).
|
||||
CLAIM_STATUSES: tuple[ClaimStatus, ...] = (
|
||||
"pending",
|
||||
"approved",
|
||||
"rejected",
|
||||
)
|
||||
|
||||
#: G-315: password minimum length (D-086 honest validation floor).
|
||||
PASSWORD_MIN_LENGTH = 8
|
||||
|
||||
|
||||
def validate_email(value: str) -> str:
|
||||
"""G-315: stdlib-only email validation + normalization.
|
||||
|
||||
Non-empty (after strip), exactly one "@", non-empty local part and
|
||||
non-empty domain — normalized to stripped + lowercased. Deliberately
|
||||
NOT RFC-5322: the honest floor for an unverified pilot signup is
|
||||
structural (exactly one "@", a domain after it), never a regex
|
||||
masquerade. pydantic `EmailStr` is BANNED (it would require
|
||||
email-validator — the first new dependency, breaking R-66/D-086).
|
||||
"""
|
||||
normalized = value.strip().lower()
|
||||
if not normalized:
|
||||
raise ValueError("email must be non-empty")
|
||||
if normalized.count("@") != 1:
|
||||
raise ValueError('email must contain exactly one "@"')
|
||||
local, _, domain = normalized.partition("@")
|
||||
if not local:
|
||||
raise ValueError("email local part must be non-empty")
|
||||
if not domain:
|
||||
raise ValueError("email domain must be non-empty")
|
||||
return normalized
|
||||
|
||||
|
||||
class EmployerAccount(BaseModel):
|
||||
"""An employer-side login account (D-087).
|
||||
|
||||
`employer_id` is nullable-until-claim-approval (the UNIQUE
|
||||
one-account-one-entity constraint activates on approve, P2). The
|
||||
account is UNVERIFIED (D-097): `email_verified` is `Literal[False]`
|
||||
— no email verification exists in v0.10, so the field can never
|
||||
carry `True`, and no learner gate is ever composed on an employer
|
||||
route.
|
||||
"""
|
||||
|
||||
model_config = ConfigDict(frozen=True)
|
||||
|
||||
id: str = Field(min_length=1)
|
||||
#: G-315: plain str, stdlib-validated + normalized.
|
||||
email: str = Field(min_length=3)
|
||||
#: None until a claim is approved (P2).
|
||||
employer_id: str | None = None
|
||||
created_at: datetime
|
||||
#: D-097: UNVERIFIED — displayed as such, never as verified.
|
||||
email_verified: Literal[False] = False
|
||||
|
||||
|
||||
class EmployerClaim(BaseModel):
|
||||
"""An account's claim on an EmployerRow entity (D-089).
|
||||
|
||||
Advisory evidence is computed at claim time (P2's claim_evidence.py)
|
||||
and stored as provenance JSON; the operator decision activates
|
||||
ownership. Auto-approval is deferred (D-089: without email
|
||||
verification the match is forgeable).
|
||||
"""
|
||||
|
||||
model_config = ConfigDict(frozen=True)
|
||||
|
||||
id: str = Field(min_length=1)
|
||||
account_id: str = Field(min_length=1)
|
||||
employer_id: str = Field(min_length=1)
|
||||
status: ClaimStatus
|
||||
evidence: dict[str, Any] = Field(default_factory=dict)
|
||||
created_at: datetime
|
||||
#: Operator provenance (decided_by/decided_at) — None while pending.
|
||||
decided_by: str | None = None
|
||||
decided_at: datetime | None = None
|
||||
|
||||
|
||||
class RegisterEmployerRequest(BaseModel):
|
||||
"""POST /v1/employers/auth/register body (Task 1-2-01).
|
||||
|
||||
Honest validation (G-315 + D-086): stdlib email normalization; the
|
||||
password carries a min-length-8 floor. Neither field is ever
|
||||
echoed back by a 422 (the pii_fields scrub lands with the routes).
|
||||
"""
|
||||
|
||||
email: str = Field(min_length=3)
|
||||
password: str = Field(min_length=PASSWORD_MIN_LENGTH)
|
||||
|
||||
@field_validator("email")
|
||||
@classmethod
|
||||
def _validate_email(cls, value: str) -> str:
|
||||
return validate_email(value)
|
||||
|
||||
|
||||
class LoginEmployerRequest(RegisterEmployerRequest):
|
||||
"""POST /v1/employers/auth/login body — same honest validation
|
||||
(G-315 email + password floor); subclass so both routes share the
|
||||
contract and drift is structurally impossible."""
|
||||
|
||||
|
||||
class ClaimEmployerRequest(BaseModel):
|
||||
"""POST /v1/employers/claims body (Task 2-1-03, D-089): the
|
||||
marketplace EmployerRow id being claimed. The entity's existence
|
||||
is checked against the marketplace store at the route (404
|
||||
unknown); evidence is computed from the session account's email +
|
||||
the entity's website AT CLAIM TIME (R-65)."""
|
||||
|
||||
employer_id: str = Field(min_length=1)
|
||||
|
||||
|
||||
class TokenResponse(BaseModel):
|
||||
"""Login/register session response (D-087): the bearer token (raw,
|
||||
exactly once on this response — only sha256(token) is stored) and
|
||||
its expiry (login + SESSION_TTL_DAYS, evaluated lazily at read)."""
|
||||
|
||||
model_config = ConfigDict(frozen=True)
|
||||
|
||||
token: str = Field(min_length=1)
|
||||
expires_at: datetime
|
||||
|
||||
|
||||
class EmployerMe(BaseModel):
|
||||
"""GET /v1/employers/auth/me response (Task 1-2-01): the account
|
||||
(unverified email displayed as such, D-097) + the claimed entity +
|
||||
the claim state — None until a claim exists (P2)."""
|
||||
|
||||
model_config = ConfigDict(frozen=True)
|
||||
|
||||
account: EmployerAccount
|
||||
#: None until a claim is approved (P2's decide_claim sets it).
|
||||
claimed_employer_id: str | None = None
|
||||
#: None until a claim is filed; the claim state (pending/approved/
|
||||
#: rejected) once one exists (P2).
|
||||
claim: EmployerClaim | None = None
|
||||
|
||||
|
||||
#: Own-postings status facets (D-092/G-319): the posting lifecycle set
|
||||
#: (marketplace.base.PostingStatus) — every facet key is one of these.
|
||||
OWN_POSTING_STATUSES: tuple[str, ...] = ("draft", "published", "closed")
|
||||
|
||||
|
||||
class OwnPostingSummary(Posting):
|
||||
"""G-319: the employer-facing posting summary (Task 3-1-01) —
|
||||
the PostingSummary wire shape REUSED (subclass of marketplace.base.
|
||||
Posting — one serialization contract, never duplicated) + the
|
||||
per-posting applicant COUNT (the D-092 overview data source, read
|
||||
through the batched count_applications_by_posting — never a
|
||||
per-posting N+1).
|
||||
|
||||
PII boundary (binding): applicant_count is the ONLY applications-
|
||||
derived datum on this contract — learner identifiers never ride
|
||||
any /v1/employers/* response."""
|
||||
|
||||
model_config = ConfigDict(frozen=True)
|
||||
|
||||
applicant_count: int = 0
|
||||
|
||||
|
||||
class OwnPostingsFacets(BaseModel):
|
||||
"""Status facet counts over the session employer's OWN postings
|
||||
(draft|published|closed — the full lifecycle, unlike the public
|
||||
board's published-only view). Every status key is ALWAYS present
|
||||
(a status with zero postings carries its honest 0)."""
|
||||
|
||||
model_config = ConfigDict(frozen=True)
|
||||
|
||||
draft: int = 0
|
||||
published: int = 0
|
||||
closed: int = 0
|
||||
|
||||
|
||||
class OwnPostingsResponse(BaseModel):
|
||||
"""GET /v1/employers/postings response (Task 3-1-01, G-319): the
|
||||
claimed employer's OWN postings (all lifecycle statuses, posted_at
|
||||
DESC then id — the list_postings order) + per-status facet counts
|
||||
+ the honest total. Unclaimed accounts never see this shape (the
|
||||
route's 403 claim-CTA precedes it)."""
|
||||
|
||||
model_config = ConfigDict(frozen=True)
|
||||
|
||||
postings: list[OwnPostingSummary] = Field(default_factory=list)
|
||||
facets: OwnPostingsFacets
|
||||
total: int = 0
|
||||
|
||||
|
||||
class EmployerPostingCreate(BaseModel):
|
||||
"""POST /v1/employers/postings body (Task 4-1-02, REQ-10-004): the
|
||||
employer-authored draft (the AdminPostingCreate shape minus
|
||||
employer_id — the entity derives from the session's CLAIM, never
|
||||
the body; G-317 stamps source="employer" at the route). Starts as
|
||||
a DRAFT; publish is an explicit call (the admin-route lifecycle
|
||||
discipline)."""
|
||||
|
||||
model_config = ConfigDict(frozen=True)
|
||||
|
||||
title: str = Field(min_length=1)
|
||||
description: str = ""
|
||||
required_competencies: list[str] = Field(default_factory=list)
|
||||
skills: list[str] = Field(default_factory=list)
|
||||
seniority: str | None = None
|
||||
category: str | None = None
|
||||
location: str = ""
|
||||
remote: bool = False
|
||||
salary_min: int | None = None
|
||||
salary_max: int | None = None
|
||||
|
||||
|
||||
class EmployerPostingEdit(BaseModel):
|
||||
"""PATCH /v1/employers/postings/{id} body (Task 4-1-02, G-318): the
|
||||
AdminPostingEdit shape — partial content edit, fields omitted stay
|
||||
put; a successful edit RE-TAGS the posting (tags are derived data,
|
||||
D-052 — the tagger overwrites). Own DRAFTS only."""
|
||||
|
||||
model_config = ConfigDict(frozen=True)
|
||||
|
||||
title: str | None = Field(default=None, min_length=1)
|
||||
description: str | None = None
|
||||
skills: list[str] | None = None
|
||||
|
||||
|
||||
class EmployerPostingWriteResponse(BaseModel):
|
||||
"""Create/edit/publish/close response (Task 4-1-02): the
|
||||
AdminPostingResponse shape (G-317's source stamp rides it —
|
||||
"employer" on every employer-authored row; seeded/admin rows keep
|
||||
their own)."""
|
||||
|
||||
model_config = ConfigDict(frozen=True)
|
||||
|
||||
id: str
|
||||
source: str
|
||||
external_id: str
|
||||
employer_id: str
|
||||
title: str
|
||||
status: str
|
||||
|
||||
|
||||
# P5 (REQ-10-005, Task 5-1-01): the checkout/entitlement contracts
|
||||
# REUSE the v0.9 billing shapes where they coincide (never duplicated —
|
||||
# CheckoutResponse here is only the wire handle; the session spec +
|
||||
# provider session live in billing/base.py as the ONE provider seam).
|
||||
|
||||
|
||||
class EmployerCheckoutCreate(BaseModel):
|
||||
"""POST /v1/employers/billing/checkout body (Task 5-1-01): which
|
||||
catalog item — the buyer derives from the session's CLAIMED entity
|
||||
(D-076's operator-mediated employer_id body field is GONE; the
|
||||
claimed entity is the only buyer the route will ever record)."""
|
||||
|
||||
item_id: str = Field(min_length=1)
|
||||
|
||||
|
||||
class EmployerCheckoutResponse(BaseModel):
|
||||
"""The created session handle + the local reconciliation id (the
|
||||
v0.9 billing_admin.CheckoutResponse shape REUSED verbatim — one
|
||||
wire contract for both checkout principals, the D-091 doctrine
|
||||
applied to the response rather than restated)."""
|
||||
|
||||
session_id: str
|
||||
provider_session_id: str
|
||||
url: str
|
||||
mode: str
|
||||
|
||||
|
||||
class EmployerEntitlementResponse(BaseModel):
|
||||
"""GET /v1/employers/billing/entitlement response (Task 5-1-01):
|
||||
the session employer's OWN entitlement summary — the v0.9
|
||||
EntitlementResponse shape (REQ-9-004) resolved for the CLAIMED
|
||||
entity only: active package (posts used/limit/expiry — lazy
|
||||
past_due grace per G-306) + subscription state. Honest states:
|
||||
purchase/subscription are None until a real grant exists; the
|
||||
shape cannot distinguish never-purchased from expired (both read
|
||||
None — the store skips expired windows lazily), so surfaces never
|
||||
assert expiry provenance from a None purchase."""
|
||||
|
||||
employer_id: str
|
||||
purchase: dict[str, Any] | None = None
|
||||
subscription: dict[str, Any] | None = None
|
||||
|
||||
|
||||
class EmployerMockCompleteRequest(BaseModel):
|
||||
"""POST /v1/employers/billing/mock/complete body (Task 5-1-02,
|
||||
D-082/G-301): the provider session id being completed. The id is
|
||||
an UNTRUSTED reference (G-302) — the route resolves it against
|
||||
the session's OWN checkout rows, never takes it on faith."""
|
||||
|
||||
provider_session_id: str = Field(min_length=1)
|
||||
|
||||
|
||||
class EmployerMockCompleteResponse(BaseModel):
|
||||
"""The completion result (the v0.9 MockCompleteResponse shape
|
||||
REUSED verbatim)."""
|
||||
|
||||
completed: bool
|
||||
payment_status: str
|
||||
@@ -0,0 +1,115 @@
|
||||
"""Advisory claim evidence — stdlib registrable-domain normalization (R-65, D-089).
|
||||
|
||||
The signal this module computes is ADVISORY and never displayed as
|
||||
verification (A-304): the operator decision activates a claim, the
|
||||
domain match merely informs it. Auto-approval is deferred (D-089) —
|
||||
without email verification the match is forgeable.
|
||||
|
||||
R-65 normalization is stdlib-only (zero-dep discipline, R-66): no PSL
|
||||
library, no tldextract. `urllib.parse.urlsplit(website).hostname`
|
||||
lowercases and strips scheme/path ("https://example.com/openai" →
|
||||
"example.com"); the email domain is taken after the last "@" and
|
||||
lowercased (never the local part — it rides nowhere in the evidence).
|
||||
|
||||
The comparison is a simple SUFFIX match: two domains match when equal
|
||||
or when one endswith "." + the other. KNOWN LIMIT (documented per the
|
||||
task, accepted for an advisory signal): a multi-label public suffix
|
||||
over-matches — "mail.co.uk" vs "co.uk" counts as a match even though
|
||||
"co.uk" is a public suffix, not a registrable domain, because a
|
||||
subdomain of a registrable domain is the intended match
|
||||
("shop.acme.com" vs "acme.com") and suffix equality cannot tell the
|
||||
two cases apart. That over-match is ACCEPTABLE HERE: the seeded
|
||||
corpus's websites are example.com placeholders (match=false
|
||||
corpus-wide at pilot, R-65) and the signal never gates anything — it
|
||||
is recorded provenance an operator reads. A PSL would be the first
|
||||
new dependency (R-66) — rejected.
|
||||
|
||||
Evidence shape per D-089: {account_email_domain, entity_website_domain,
|
||||
match} — computed AT CLAIM TIME (Task 2-1-03) and stored as provenance
|
||||
JSON on the claim row; it is a snapshot, never recomputed on read.
|
||||
|
||||
Boundary (D-031 family): stdlib + pydantic only; this module never
|
||||
imports agents/ or api/ — it is a pure function family over strings.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
|
||||
def normalize_email_domain(email: str) -> str:
|
||||
"""The email's domain after the last "@" — lowercased (never the
|
||||
local part). The last-@ split tolerates local parts containing "@"
|
||||
under a quoting convention; honest callers pass validated emails
|
||||
(G-315: exactly one "@" by the time an account exists), so an
|
||||
"@"-less string is an honest-absence case: ""."""
|
||||
if "@" not in email:
|
||||
return ""
|
||||
_, _, domain = email.rpartition("@")
|
||||
return domain.lower()
|
||||
|
||||
|
||||
def normalize_website_domain(website: str) -> str:
|
||||
"""The website's host, lowercased — scheme, path, port, and any
|
||||
userinfo stripped ("HTTPS://Example.COM/openai" → "example.com").
|
||||
urlsplit parses a SCHEME-qualified URL: a bare "example.com" has no
|
||||
netloc, so a scheme is prepended for the parse ("example.com" →
|
||||
"example.com"; "example.com:8443" likewise — the port drops with
|
||||
the netloc, evidence is registrable not origin-scoped). An
|
||||
unparseable/empty website yields "" (the honest absence the route
|
||||
records, never an exception)."""
|
||||
candidate = website.strip()
|
||||
if not candidate:
|
||||
return ""
|
||||
try:
|
||||
parts = urlsplit(candidate)
|
||||
if parts.scheme or parts.netloc:
|
||||
# Scheme-qualified ("https://…", "//host/…") — parse as-is.
|
||||
# Non-URL schemes ("mailto:…") land here with no netloc →
|
||||
# hostname None (honest absence).
|
||||
hostname = parts.hostname
|
||||
else:
|
||||
# Bare host (no scheme): urlsplit would treat it as a
|
||||
# path — prepending "//" makes it an authority-only URL.
|
||||
hostname = urlsplit(f"//{candidate}").hostname
|
||||
except ValueError:
|
||||
# e.g. an unterminated IPv6 literal — evidence stays advisory,
|
||||
# never a 500 on the claim route.
|
||||
return ""
|
||||
if hostname is None:
|
||||
return ""
|
||||
if any(char.isspace() for char in hostname):
|
||||
return "" # not a domain — honest absence, never junk
|
||||
return hostname
|
||||
|
||||
|
||||
def domains_match(account_email_domain: str, entity_website_domain: str) -> bool:
|
||||
"""Simple SUFFIX match (R-65): True when equal or when one endswith
|
||||
"." + the other. Honest absent input: either side empty → False
|
||||
(nothing claimed is nothing matched)."""
|
||||
if not account_email_domain or not entity_website_domain:
|
||||
return False
|
||||
if account_email_domain == entity_website_domain:
|
||||
return True
|
||||
if account_email_domain.endswith("." + entity_website_domain):
|
||||
return True
|
||||
if entity_website_domain.endswith("." + account_email_domain):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def compute_claim_evidence(email: str, website: str) -> dict:
|
||||
"""The D-089 evidence dict, computed at claim time:
|
||||
|
||||
{account_email_domain, entity_website_domain, match}
|
||||
|
||||
Pure function over the account email + the entity website — the
|
||||
claim route snapshots it onto the claim row as provenance JSON.
|
||||
"""
|
||||
account_email_domain = normalize_email_domain(email)
|
||||
entity_website_domain = normalize_website_domain(website)
|
||||
return {
|
||||
"account_email_domain": account_email_domain,
|
||||
"entity_website_domain": entity_website_domain,
|
||||
"match": domains_match(account_email_domain, entity_website_domain),
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
"""Stdlib scrypt password KDF (D-086, R-55, REQ-10-001).
|
||||
|
||||
`hashlib.scrypt` (stdlib, OpenSSL-backed — D-086: zero new
|
||||
dependencies) with per-password random salt and a SELF-DESCRIBING
|
||||
storage format, `scrypt$16384$8$1$<salt_b64>$<hash_b64>`: the KDF
|
||||
parameters ride the row, so params evolve without invalidating
|
||||
existing rows (verify parses them from the stored string, never from
|
||||
the module constants).
|
||||
|
||||
Cost budget (R-55 probe, this box's venv — Python 3.11.2): ~47-59 ms
|
||||
per hash at N=2^14/r=8/p=1/dklen=32, 128·N·r = 16 MiB working set.
|
||||
Register and login each perform exactly ONE derivation — inside
|
||||
D-096's "tens of ms, honest" budget. Burst risk (open-risk-1): a
|
||||
login burst stacks single-threaded derivations; BOTH throttle windows
|
||||
(Wave 1-2, D-088/G-320) run BEFORE this KDF so a 429'd or capped
|
||||
attempt never burns KDF CPU.
|
||||
|
||||
maxmem discipline (R-55): CPython's default 32 MiB admits the 16 MiB
|
||||
working set with NO argument; the pin below is exactly 33554432 for
|
||||
explicitness — never lower (1024 KiB raises ValueError: memory limit
|
||||
exceeded; the floor is ~17 MiB).
|
||||
|
||||
Tests run the REAL KDF (D-096: no fake-hash path) and assert
|
||||
accept/reject behavior only — never hash bytes.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import secrets
|
||||
|
||||
#: KDF parameters (D-086) — pinned by test (the PAST_DUE_GRACE_DAYS
|
||||
#: shape). N=2^14, r=8, p=1, dklen=32: the R-55 probe-verified
|
||||
#: cost/memory point (~50 ms/hash, 16 MiB).
|
||||
SCRYPT_N = 2**14
|
||||
SCRYPT_R = 8
|
||||
SCRYPT_P = 1
|
||||
SCRYPT_DKLEN = 32
|
||||
|
||||
#: Per-password salt length (bytes) — `secrets.token_bytes(16)`; the
|
||||
#: random salt is what makes two hashes of one password differ.
|
||||
_SALT_BYTES = 16
|
||||
|
||||
#: R-55: pinned for explicitness — the default 32 MiB admits the
|
||||
#: 16 MiB working set; NEVER pin below ~17 MiB (1024 KiB raises).
|
||||
_SCRYPT_MAXMEM = 33554432 # 32 MiB
|
||||
|
||||
#: Storage format marker — self-describing rows start with this.
|
||||
_ALGORITHM = "scrypt"
|
||||
|
||||
|
||||
def _b64e(raw: bytes) -> str:
|
||||
return base64.b64encode(raw).decode("ascii")
|
||||
|
||||
|
||||
def _b64d(encoded: str) -> bytes:
|
||||
return base64.b64decode(encoded.encode("ascii"))
|
||||
|
||||
|
||||
def _derive(
|
||||
password: str, *, salt: bytes, n: int, r: int, p: int, dklen: int
|
||||
) -> bytes:
|
||||
"""One scrypt derivation — the ONLY derivation path (register and
|
||||
verify both route through here, so their costs stay identical)."""
|
||||
return hashlib.scrypt(
|
||||
password.encode("utf-8"),
|
||||
salt=salt,
|
||||
n=n,
|
||||
r=r,
|
||||
p=p,
|
||||
dklen=dklen,
|
||||
maxmem=_SCRYPT_MAXMEM,
|
||||
)
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
"""Hash a password with a fresh random salt → the self-describing
|
||||
`scrypt$16384$8$1$<salt_b64>$<hash_b64>` string.
|
||||
|
||||
The module constants bake in at hash time; verify re-reads them
|
||||
from the stored row, so a future param bump never invalidates
|
||||
existing rows.
|
||||
"""
|
||||
salt = secrets.token_bytes(_SALT_BYTES)
|
||||
derived = _derive(
|
||||
password,
|
||||
salt=salt,
|
||||
n=SCRYPT_N,
|
||||
r=SCRYPT_R,
|
||||
p=SCRYPT_P,
|
||||
dklen=SCRYPT_DKLEN,
|
||||
)
|
||||
return "$".join(
|
||||
(
|
||||
_ALGORITHM,
|
||||
str(SCRYPT_N),
|
||||
str(SCRYPT_R),
|
||||
str(SCRYPT_P),
|
||||
_b64e(salt),
|
||||
_b64e(derived),
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def verify_password(stored: str, password: str) -> bool:
|
||||
"""Verify a candidate against a stored self-describing hash.
|
||||
|
||||
Parses the params from the stored string (never the module
|
||||
constants — a row hashed under different params still verifies),
|
||||
re-derives with the SAME pinned maxmem, compares via
|
||||
`hmac.compare_digest` (constant-time). Any malformed stored string
|
||||
is an honest False — never a raise (the auth route maps it to 401).
|
||||
"""
|
||||
parts = stored.split("$")
|
||||
if len(parts) != 6 or parts[0] != _ALGORITHM:
|
||||
return False
|
||||
try:
|
||||
n, r, p = (int(part) for part in parts[1:4])
|
||||
salt = _b64d(parts[4])
|
||||
expected = _b64d(parts[5])
|
||||
if n < 1 or r < 1 or p < 1 or not salt or not expected:
|
||||
return False
|
||||
derived = _derive(
|
||||
password, salt=salt, n=n, r=r, p=p, dklen=len(expected)
|
||||
)
|
||||
except (ValueError, TypeError):
|
||||
# Malformed stored row (bad ints, bad base64, scrypt rejection)
|
||||
# — an honest reject, never a 500 on the auth path.
|
||||
return False
|
||||
return hmac.compare_digest(derived, expected)
|
||||
@@ -0,0 +1,739 @@
|
||||
"""EmployerStore — the 8th D-027 store family (D-087/D-095, REQ-10-001).
|
||||
|
||||
Four tables on the shared `Settings().db_path` (one SQLite file with the
|
||||
seven prior stores): `employer_accounts`, `employer_sessions`,
|
||||
`employer_claims`, `employer_audit_events`. All `employer_`-prefixed —
|
||||
bare `employer` is marketplace's EmployerRow (marketplace/store.py:144).
|
||||
Mechanics mirror the probe-verified billing/store.py exactly (R-57):
|
||||
WAL / synchronous=NORMAL / busy_timeout / foreign_keys pragmas at
|
||||
connect time, `sa_type` portable columns (String/JSON for Postgres
|
||||
parity), `_validate()`/`_normalize()` hooks, Protocol + SQLite impl
|
||||
pair, surfaced IntegrityError, tz-aware → naive → tz-aware boundary
|
||||
normalization, one-time idempotent `create_schema()` (D-095 — the
|
||||
tables join an existing shared DB at next boot, zero migration).
|
||||
|
||||
Guards baked into the schema (D-087):
|
||||
- `employer_accounts.email` UNIQUE — one account per email; the
|
||||
register route's check-first 409 is the fast path, the constraint
|
||||
is the race backstop and its IntegrityError SURFACES.
|
||||
- `employer_accounts.employer_id` UNIQUE nullable — the one-account-
|
||||
one-entity constraint, activates on claim approval (P2).
|
||||
- `employer_sessions.token_hash` UNIQUE — stores ONLY
|
||||
`sha256(token)`, NEVER the raw token (D-087): a DB leak yields
|
||||
nothing usable against the Authorization header namespace.
|
||||
- G-306: session expiry is evaluated LAZILY at read time against
|
||||
`expires_at` (login + SESSION_TTL_DAYS) — an expired row reads as
|
||||
absent; no background timer, no writes on evaluation.
|
||||
- `employer_claims` landed in P1 per D-095's one-time create_all;
|
||||
its claim methods (insert_claim/decide_claim/list_claims/get_claim)
|
||||
+ the G-316 partial UNIQUE index arrive with P2 (D-089).
|
||||
|
||||
Boundary (D-027 family): `employers/` never imports `agents/`/`api/`;
|
||||
this module imports config + base only.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import sqlite3
|
||||
import uuid
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from pathlib import Path
|
||||
from typing import Any, Protocol
|
||||
|
||||
from sqlalchemy import Index, UniqueConstraint, event, text
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.types import JSON, String
|
||||
from sqlmodel import Field, Session, SQLModel, col, create_engine, select
|
||||
|
||||
from ..config import Settings
|
||||
from .base import CLAIM_STATUSES, validate_email
|
||||
|
||||
#: D-087: a login session's TTL. Module constant (not settings) —
|
||||
#: pinned by test (the PAST_DUE_GRACE_DAYS shape); evaluation is lazy
|
||||
#: at read time (G-306), never a timer.
|
||||
SESSION_TTL_DAYS = 7
|
||||
|
||||
_TABLES = (
|
||||
"employer_accounts",
|
||||
"employer_sessions",
|
||||
"employer_claims",
|
||||
"employer_audit_events",
|
||||
)
|
||||
|
||||
#: Audit event vocabulary: `auth` = the Wave 1-2 register/logout
|
||||
#: account events; `claim` = P2's claim/decide entity events; `manual`
|
||||
#: = operator action provenance (the billing kind set, employer-side).
|
||||
#: v0.11 P2: "application" joins the vocabulary (employer-driven hiring
|
||||
#: transitions append their audit row — the D-089 one-queryable lane).
|
||||
_AUDIT_EVENT_KINDS = ("auth", "claim", "manual", "application")
|
||||
|
||||
|
||||
class AccountRow(SQLModel, table=True):
|
||||
"""An employer login account row (D-087).
|
||||
|
||||
Bare Literal annotations crash sqlmodel's column inference; the
|
||||
family pattern (explicit sa_type + _validate hook) is used where
|
||||
needed. `email` is normalized via base.validate_email (G-315) at
|
||||
the store boundary — routes normalize too; the store re-derives,
|
||||
never trusts."""
|
||||
|
||||
__tablename__ = "employer_accounts"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("email", name="uq_account_email"),
|
||||
UniqueConstraint("employer_id", name="uq_account_employer"),
|
||||
)
|
||||
|
||||
id: str = Field(primary_key=True, sa_type=String)
|
||||
#: G-315: plain str, stdlib-validated + stripped/lowercased.
|
||||
email: str = Field(sa_type=String)
|
||||
#: Self-describing scrypt string (passwords.py) — never a raw hash.
|
||||
password_hash: str = Field(sa_type=String)
|
||||
#: None until a claim is APPROVED (P2) — the UNIQUE nullable
|
||||
#: one-account-one-entity constraint.
|
||||
employer_id: str | None = Field(default=None, sa_type=String)
|
||||
created_at: datetime | None = Field(default=None)
|
||||
|
||||
def _validate(self) -> None:
|
||||
if not self.id:
|
||||
raise ValueError("id must be non-empty")
|
||||
if not self.password_hash:
|
||||
raise ValueError("password_hash must be non-empty")
|
||||
if self.employer_id is not None and not self.employer_id:
|
||||
raise ValueError("employer_id must be non-empty when set")
|
||||
|
||||
def _normalize(self) -> None:
|
||||
# G-315 at the store boundary: validate + strip + lowercase
|
||||
# (raises ValueError on a dishonest email — never trusts).
|
||||
self.email = validate_email(self.email)
|
||||
self.created_at = _as_utc(self.created_at) if self.created_at else None
|
||||
|
||||
|
||||
class SessionRow(SQLModel, table=True):
|
||||
"""A hashed server-side session row (D-087).
|
||||
|
||||
`token_hash` is sha256(token) — the raw token is handed to the
|
||||
client EXACTLY ONCE on login and never persisted anywhere. The
|
||||
TTL is evaluated LAZILY at read (G-306): an expired row reads as
|
||||
absent; no timer ever rewrites or deletes it."""
|
||||
|
||||
__tablename__ = "employer_sessions"
|
||||
__table_args__ = (UniqueConstraint("token_hash", name="uq_session_token_hash"),)
|
||||
|
||||
id: str = Field(primary_key=True, sa_type=String)
|
||||
token_hash: str = Field(sa_type=String)
|
||||
account_id: str = Field(index=True, sa_type=String)
|
||||
created_at: datetime | None = Field(default=None)
|
||||
expires_at: datetime | None = Field(default=None)
|
||||
|
||||
def _validate(self) -> None:
|
||||
if not self.id:
|
||||
raise ValueError("id must be non-empty")
|
||||
if not self.token_hash:
|
||||
raise ValueError("token_hash must be non-empty")
|
||||
if not self.account_id:
|
||||
raise ValueError("account_id must be non-empty")
|
||||
|
||||
def _normalize(self) -> None:
|
||||
self.created_at = _as_utc(self.created_at) if self.created_at else None
|
||||
self.expires_at = _as_utc(self.expires_at) if self.expires_at else None
|
||||
|
||||
|
||||
class ClaimRow(SQLModel, table=True):
|
||||
"""An account's claim on a marketplace EmployerRow entity (D-089).
|
||||
|
||||
The table lands now per D-095's one-time create_all; the claim
|
||||
methods (insert_claim/decide_claim/list_claims) arrive with P2.
|
||||
`evidence` is the advisory claim-time provenance JSON
|
||||
{account_email_domain, entity_website_domain, match} (R-65). The
|
||||
decided_* pair carries operator provenance and is valid only on a
|
||||
decided row (the past_due_at pairing discipline).
|
||||
|
||||
G-316: the partial UNIQUE index uq_pending_claim_per_entity on
|
||||
employer_id WHERE status='pending' makes one-PENDING-claim-per-
|
||||
entity a STRUCTURAL guard — check-first alone is TOCTOU. The
|
||||
approved-owner arm is already structural: employer_accounts.
|
||||
employer_id UNIQUE (one account : one entity). Rejection frees
|
||||
the entity — a partial index over status='pending' never touches
|
||||
rejected rows.
|
||||
"""
|
||||
|
||||
__tablename__ = "employer_claims"
|
||||
__table_args__ = (
|
||||
Index(
|
||||
"uq_pending_claim_per_entity",
|
||||
"employer_id",
|
||||
unique=True,
|
||||
sqlite_where=text("status='pending'"),
|
||||
),
|
||||
)
|
||||
|
||||
id: str = Field(primary_key=True, sa_type=String)
|
||||
account_id: str = Field(index=True, sa_type=String)
|
||||
employer_id: str = Field(index=True, sa_type=String)
|
||||
status: str = Field(default="pending", sa_type=String)
|
||||
evidence: dict[str, Any] = Field(default_factory=dict, sa_type=JSON)
|
||||
created_at: datetime | None = Field(default=None)
|
||||
decided_by: str | None = Field(default=None, sa_type=String)
|
||||
decided_at: datetime | None = Field(default=None)
|
||||
|
||||
def _validate(self) -> None:
|
||||
if not self.id or not self.account_id or not self.employer_id:
|
||||
raise ValueError("id, account_id, and employer_id must be non-empty")
|
||||
if self.status not in CLAIM_STATUSES:
|
||||
raise ValueError(f"invalid claim status {self.status!r}")
|
||||
if self.status == "pending" and (
|
||||
self.decided_by is not None or self.decided_at is not None
|
||||
):
|
||||
raise ValueError("decided_by/decided_at are set only on a decided claim")
|
||||
if self.status in ("approved", "rejected") and self.decided_at is None:
|
||||
raise ValueError("decided_at must be set on a decided claim")
|
||||
|
||||
def _normalize(self) -> None:
|
||||
self.created_at = _as_utc(self.created_at) if self.created_at else None
|
||||
self.decided_at = _as_utc(self.decided_at) if self.decided_at else None
|
||||
|
||||
|
||||
class AuditEventRow(SQLModel, table=True):
|
||||
"""Employer-side audit trail — the BillingEventRow audit shape
|
||||
(billing/store.py:337-359): auth events (register/logout), claim
|
||||
events (P2), and operator actions with provenance."""
|
||||
|
||||
__tablename__ = "employer_audit_events"
|
||||
|
||||
id: int | None = Field(default=None, primary_key=True)
|
||||
account_id: str | None = Field(default=None, index=True, sa_type=String)
|
||||
employer_id: str | None = Field(default=None, index=True, sa_type=String)
|
||||
kind: str = Field(sa_type=String)
|
||||
name: str = Field(sa_type=String)
|
||||
detail: dict[str, Any] = Field(default_factory=dict, sa_type=JSON)
|
||||
operator: str | None = Field(default=None, sa_type=String)
|
||||
created_at: datetime | None = Field(default=None)
|
||||
|
||||
def _validate(self) -> None:
|
||||
if self.kind not in _AUDIT_EVENT_KINDS:
|
||||
raise ValueError(f"invalid audit event kind {self.kind!r}")
|
||||
if not self.name:
|
||||
raise ValueError("name must be non-empty")
|
||||
|
||||
def _normalize(self) -> None:
|
||||
self.created_at = _as_utc(self.created_at) if self.created_at else None
|
||||
|
||||
|
||||
def _as_utc(ts: datetime) -> datetime:
|
||||
"""SQLite stores naive; read paths re-label tz-aware UTC (D-027 pattern)."""
|
||||
if ts.tzinfo is None:
|
||||
return ts.replace(tzinfo=UTC)
|
||||
return ts
|
||||
|
||||
|
||||
def _hash_token(token: str) -> str:
|
||||
"""D-087: sessions store ONLY sha256(token) — never the raw token."""
|
||||
return hashlib.sha256(token.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def _constraint_error(message: str, params: dict[str, Any]) -> IntegrityError:
|
||||
"""Hand-raised IntegrityError (the guard arms of decide_claim) —
|
||||
the caller's honest 409, never a silent overwrite. The original
|
||||
exception is the raised guard itself."""
|
||||
return IntegrityError(message, params, ValueError(message))
|
||||
|
||||
|
||||
def _sqlite_connect(dbapi_connection: sqlite3.Connection, _: object) -> None:
|
||||
"""Per-connection pragmas — mirrors the other D-027 stores."""
|
||||
cursor = dbapi_connection.cursor()
|
||||
cursor.execute("PRAGMA journal_mode=WAL")
|
||||
cursor.execute("PRAGMA synchronous=NORMAL")
|
||||
cursor.execute("PRAGMA busy_timeout=5000")
|
||||
cursor.execute("PRAGMA foreign_keys=ON")
|
||||
cursor.close()
|
||||
|
||||
|
||||
class EmployerStore(Protocol):
|
||||
"""Persistence contract for employer auth (D-087/D-095)."""
|
||||
|
||||
def create_schema(self) -> None:
|
||||
"""Ensure all four tables exist (idempotent — shared DB file)."""
|
||||
...
|
||||
|
||||
def insert_account(self, *, email: str, password_hash: str) -> tuple[AccountRow, bool]:
|
||||
"""Check-first insert by email → (row, created); the EXISTING
|
||||
row rides a duplicate register (route → 409). The UNIQUE
|
||||
constraint is the race backstop — its IntegrityError SURFACES
|
||||
(never swallowed, never re-masked as created=False)."""
|
||||
...
|
||||
|
||||
def get_account_by_email(self, email: str) -> AccountRow | None:
|
||||
"""Point lookup by the normalized email (login path)."""
|
||||
...
|
||||
|
||||
def get_account(self, account_id: str) -> AccountRow | None:
|
||||
"""Point lookup by id (require_employer_session's account arm)."""
|
||||
...
|
||||
|
||||
def mint_session(
|
||||
self, *, account_id: str, token: str, now: datetime | None = None
|
||||
) -> SessionRow:
|
||||
"""Store sha256(token) with expires_at = now + SESSION_TTL_DAYS
|
||||
(D-087). The raw token is NEVER persisted; a duplicate
|
||||
token_hash surfaces as IntegrityError (the constraint is the
|
||||
only guard — a token is minted fresh per login)."""
|
||||
...
|
||||
|
||||
def get_session_by_token_hash(
|
||||
self, token_hash: str, *, now: datetime | None = None
|
||||
) -> SessionRow | None:
|
||||
"""Point lookup by sha256(token) with LAZY TTL (G-306): an
|
||||
expired row reads as ABSENT — no timer, no writes on
|
||||
evaluation; the row itself stays until revoked."""
|
||||
...
|
||||
|
||||
def revoke_session(self, token_hash: str) -> bool:
|
||||
"""DELETE the session row (logout); True when a row was
|
||||
removed, False when it was already gone."""
|
||||
...
|
||||
|
||||
def append_audit_event(
|
||||
self,
|
||||
kind: str,
|
||||
name: str,
|
||||
*,
|
||||
account_id: str | None = None,
|
||||
employer_id: str | None = None,
|
||||
operator: str | None = None,
|
||||
detail: dict[str, Any] | None = None,
|
||||
) -> AuditEventRow:
|
||||
"""Audit log append (auth/claim/manual)."""
|
||||
...
|
||||
|
||||
# -- claims (D-089, REQ-10-002) ---------------------------------------
|
||||
|
||||
def insert_claim(
|
||||
self,
|
||||
*,
|
||||
account_id: str,
|
||||
employer_id: str,
|
||||
evidence: dict[str, Any] | None = None,
|
||||
) -> tuple[ClaimRow, bool]:
|
||||
"""Check-first pending-claim insert (the insert_application
|
||||
precedent, marketplace/store.py:341-347): an existing PENDING
|
||||
claim on the entity returns (existing_row, False) — the route's
|
||||
honest 409 fast path. G-316: the partial UNIQUE index
|
||||
uq_pending_claim_per_entity backstops the check-first TOCTOU —
|
||||
a raced duplicate insert SURFACES its IntegrityError (never
|
||||
swallowed, never re-masked as created=False); the caller maps
|
||||
it to the SAME 409. Rejected/decided rows never block: rejection
|
||||
frees the entity for a new claim."""
|
||||
...
|
||||
|
||||
def decide_claim(
|
||||
self,
|
||||
claim_id: str,
|
||||
*,
|
||||
decision: str,
|
||||
operator: str,
|
||||
now: datetime | None = None,
|
||||
) -> ClaimRow | None:
|
||||
"""Operator decision on a PENDING claim (D-089): approve → set
|
||||
employer_accounts.employer_id + decided_by/decided_at + a
|
||||
`claim` audit event; reject → decided_by/decided_at + the audit
|
||||
event (the entity stays free). The one-account-one-entity arm
|
||||
is STRUCTURAL: approving when the account already holds an
|
||||
entity, or the entity is already owned, raises a hand-raised
|
||||
IntegrityError (the caller's honest 409 — never a silent
|
||||
overwrite). Unknown claim id → None (route 404s)."""
|
||||
...
|
||||
|
||||
def list_claims(self, status: str | None = None) -> list[ClaimRow]:
|
||||
"""Claims newest-first; optional status filter (pending/
|
||||
approved/rejected — the admin queue's consume-free read path)."""
|
||||
...
|
||||
|
||||
def list_accounts(self) -> list[AccountRow]:
|
||||
"""All accounts, created-oldest-first (the admin accounts list —
|
||||
consume-free read path; the queue is pilot-sized)."""
|
||||
...
|
||||
|
||||
def list_audit_events(
|
||||
self,
|
||||
*,
|
||||
account_id: str | None = None,
|
||||
employer_id: str | None = None,
|
||||
kind: str | None = None,
|
||||
name: str | None = None,
|
||||
limit: int = 100,
|
||||
) -> list[AuditEventRow]:
|
||||
"""Audit trail, newest-first (the list_billing_events shape,
|
||||
billing/store.py:1122-1145); optional account/employer/kind/name
|
||||
filters — the queryable operator trail (D-089)."""
|
||||
...
|
||||
|
||||
def get_claim(self, claim_id: str) -> ClaimRow | None:
|
||||
"""Point lookup by id (the admin review path)."""
|
||||
...
|
||||
|
||||
def get_claim_by_account(
|
||||
self, account_id: str, *, exclude_statuses: tuple[str, ...] = ()
|
||||
) -> ClaimRow | None:
|
||||
"""The account's most recent claim NOT in exclude_statuses
|
||||
(newest-first — created_at DESC then id; the /me claim-state
|
||||
read). An account with no non-excluded claim → None."""
|
||||
...
|
||||
|
||||
def close(self) -> None:
|
||||
"""Dispose the engine (app shutdown)."""
|
||||
...
|
||||
|
||||
|
||||
class SQLiteEmployerStore:
|
||||
"""SQLite implementation of EmployerStore (D-027/D-087)."""
|
||||
|
||||
def __init__(self, db_path: Path | None = None) -> None:
|
||||
self._db_path: Path = db_path if db_path is not None else Settings().db_path
|
||||
self._engine = create_engine(
|
||||
f"sqlite:///{self._db_path}",
|
||||
connect_args={"check_same_thread": False},
|
||||
)
|
||||
event.listen(self._engine, "connect", _sqlite_connect)
|
||||
self.create_schema()
|
||||
|
||||
def create_schema(self) -> None:
|
||||
"""Ensure all four tables exist (idempotent — shared DB file)."""
|
||||
SQLModel.metadata.create_all(self._engine)
|
||||
|
||||
# -- accounts -----------------------------------------------------------
|
||||
|
||||
def insert_account(self, *, email: str, password_hash: str) -> tuple[AccountRow, bool]:
|
||||
"""Check-first insert (the insert_application pattern): an
|
||||
existing email returns (existing_row, False) — the register
|
||||
route's honest 409. The UNIQUE constraint backstops the
|
||||
check-first TOCTOU; its IntegrityError is SURFACED, never
|
||||
swallowed."""
|
||||
row = AccountRow(
|
||||
id=f"acct-{uuid.uuid4().hex[:16]}",
|
||||
email=email,
|
||||
password_hash=password_hash,
|
||||
employer_id=None,
|
||||
created_at=datetime.now(UTC),
|
||||
)
|
||||
row._validate()
|
||||
row._normalize()
|
||||
with Session(self._engine) as session:
|
||||
existing = session.exec(
|
||||
select(AccountRow).where(AccountRow.email == row.email)
|
||||
).one_or_none()
|
||||
if existing is not None:
|
||||
existing._normalize()
|
||||
return existing, False
|
||||
session.add(row)
|
||||
session.commit()
|
||||
session.refresh(row)
|
||||
row._normalize()
|
||||
return row, True
|
||||
|
||||
def get_account_by_email(self, email: str) -> AccountRow | None:
|
||||
with Session(self._engine) as session:
|
||||
row = session.exec(select(AccountRow).where(AccountRow.email == email)).one_or_none()
|
||||
if row is None:
|
||||
return None
|
||||
row._normalize()
|
||||
return row
|
||||
|
||||
def get_account(self, account_id: str) -> AccountRow | None:
|
||||
with Session(self._engine) as session:
|
||||
row = session.get(AccountRow, account_id)
|
||||
if row is None:
|
||||
return None
|
||||
row._normalize()
|
||||
return row
|
||||
|
||||
# -- sessions (D-087: hashed-at-rest; G-306: lazy TTL) -------------------
|
||||
|
||||
def mint_session(
|
||||
self, *, account_id: str, token: str, now: datetime | None = None
|
||||
) -> SessionRow:
|
||||
if not token:
|
||||
raise ValueError("token must be non-empty")
|
||||
moment = _as_utc(now) if now is not None else datetime.now(UTC)
|
||||
row = SessionRow(
|
||||
id=f"ses-{uuid.uuid4().hex[:16]}",
|
||||
# D-087: ONLY the sha256 ever persists — the raw token
|
||||
# lives in the login response and nowhere else.
|
||||
token_hash=_hash_token(token),
|
||||
account_id=account_id,
|
||||
created_at=moment,
|
||||
expires_at=moment + timedelta(days=SESSION_TTL_DAYS),
|
||||
)
|
||||
row._validate()
|
||||
row._normalize()
|
||||
with Session(self._engine) as session:
|
||||
session.add(row)
|
||||
# The UNIQUE(token_hash) constraint surfaces a duplicate
|
||||
# mint as IntegrityError — the caller decides; never
|
||||
# swallowed here.
|
||||
session.commit()
|
||||
session.refresh(row)
|
||||
row._normalize()
|
||||
return row
|
||||
|
||||
def get_session_by_token_hash(
|
||||
self, token_hash: str, *, now: datetime | None = None
|
||||
) -> SessionRow | None:
|
||||
"""G-306: expired rows read as ABSENT — lazy evaluation, no
|
||||
timer, no writes on the read path."""
|
||||
moment = _as_utc(now) if now is not None else datetime.now(UTC)
|
||||
with Session(self._engine) as session:
|
||||
row = session.exec(
|
||||
select(SessionRow).where(SessionRow.token_hash == token_hash)
|
||||
).one_or_none()
|
||||
if row is None:
|
||||
return None
|
||||
row._normalize()
|
||||
assert row.expires_at is not None # mint always sets it
|
||||
if moment >= row.expires_at:
|
||||
return None # expired — reads as absent, stays on disk
|
||||
return row
|
||||
|
||||
def revoke_session(self, token_hash: str) -> bool:
|
||||
"""DELETE the row (logout). True = a row was removed; False =
|
||||
nothing to revoke (unknown/already-revoked token)."""
|
||||
with Session(self._engine) as session:
|
||||
row = session.exec(
|
||||
select(SessionRow).where(SessionRow.token_hash == token_hash)
|
||||
).one_or_none()
|
||||
if row is None:
|
||||
return False
|
||||
session.delete(row)
|
||||
session.commit()
|
||||
return True
|
||||
|
||||
# -- audit log ----------------------------------------------------------
|
||||
|
||||
def append_audit_event(
|
||||
self,
|
||||
kind: str,
|
||||
name: str,
|
||||
*,
|
||||
account_id: str | None = None,
|
||||
employer_id: str | None = None,
|
||||
operator: str | None = None,
|
||||
detail: dict[str, Any] | None = None,
|
||||
) -> AuditEventRow:
|
||||
row = AuditEventRow(
|
||||
account_id=account_id,
|
||||
employer_id=employer_id,
|
||||
kind=kind,
|
||||
name=name,
|
||||
detail=dict(detail or {}),
|
||||
operator=operator,
|
||||
created_at=datetime.now(UTC),
|
||||
)
|
||||
row._validate()
|
||||
row._normalize()
|
||||
with Session(self._engine) as session:
|
||||
session.add(row)
|
||||
session.commit()
|
||||
session.refresh(row)
|
||||
row._normalize()
|
||||
return row
|
||||
|
||||
# -- claims (D-089, REQ-10-002) ---------------------------------------
|
||||
|
||||
def insert_claim(
|
||||
self,
|
||||
*,
|
||||
account_id: str,
|
||||
employer_id: str,
|
||||
evidence: dict[str, Any] | None = None,
|
||||
) -> tuple[ClaimRow, bool]:
|
||||
"""Check-first pending-claim insert (the insert_application
|
||||
precedent): an existing PENDING claim on the entity rides
|
||||
created=False — never a second pending row. G-316: the partial
|
||||
UNIQUE index backstops the race — its IntegrityError SURFACES
|
||||
(the caller maps it to the same honest 409)."""
|
||||
row = ClaimRow(
|
||||
id=f"clm-{uuid.uuid4().hex[:16]}",
|
||||
account_id=account_id,
|
||||
employer_id=employer_id,
|
||||
status="pending",
|
||||
evidence=dict(evidence or {}),
|
||||
created_at=datetime.now(UTC),
|
||||
)
|
||||
row._validate()
|
||||
row._normalize()
|
||||
with Session(self._engine) as session:
|
||||
existing = session.exec(
|
||||
select(ClaimRow).where(
|
||||
ClaimRow.employer_id == employer_id,
|
||||
ClaimRow.status == "pending",
|
||||
)
|
||||
).one_or_none()
|
||||
if existing is not None:
|
||||
# Fast path: the pending claim exists — the existing
|
||||
# row rides, created=False (the route's 409).
|
||||
existing._normalize()
|
||||
return existing, False
|
||||
session.add(row)
|
||||
# G-316: a raced insert lands here — the partial UNIQUE
|
||||
# index refuses the second PENDING row and its
|
||||
# IntegrityError SURFACES, never swallowed here.
|
||||
session.commit()
|
||||
session.refresh(row)
|
||||
row._normalize()
|
||||
return row, True
|
||||
|
||||
def decide_claim(
|
||||
self,
|
||||
claim_id: str,
|
||||
*,
|
||||
decision: str,
|
||||
operator: str,
|
||||
now: datetime | None = None,
|
||||
) -> ClaimRow | None:
|
||||
"""Approve → employer_accounts.employer_id set + decided_* + a
|
||||
`claim` audit event; reject → decided_* + the audit event.
|
||||
The one-owner arms are STRUCTURAL: employer_accounts.employer_id
|
||||
UNIQUE (approve hands its IntegrityError to the caller) and a
|
||||
hand-raised guard when the claim is not pending (the caller's
|
||||
honest 409 — never a silent overwrite)."""
|
||||
if decision not in ("approved", "rejected"):
|
||||
raise ValueError(f"invalid decision {decision!r}")
|
||||
moment = _as_utc(now) if now is not None else datetime.now(UTC)
|
||||
with Session(self._engine) as session:
|
||||
row = session.get(ClaimRow, claim_id)
|
||||
if row is None:
|
||||
return None
|
||||
if row.status != "pending":
|
||||
# Hand-raised IntegrityError — the caller's honest 409
|
||||
# (deciding a decided claim, the IntegrityError shape).
|
||||
raise _constraint_error(
|
||||
f"guard: claim {claim_id!r} is already {row.status!r}",
|
||||
{"claim_id": claim_id},
|
||||
)
|
||||
row.status = decision
|
||||
row.decided_by = operator
|
||||
row.decided_at = moment
|
||||
row._validate()
|
||||
row._normalize()
|
||||
if decision == "approved":
|
||||
account = session.get(AccountRow, row.account_id)
|
||||
if account is None: # pragma: no cover - FK discipline
|
||||
raise _constraint_error(
|
||||
f"guard: claim {claim_id!r} references unknown "
|
||||
"account — refusing to approve",
|
||||
{"claim_id": claim_id},
|
||||
)
|
||||
if account.employer_id is not None:
|
||||
# One account : one entity — the account already
|
||||
# holds an entity. Hand-raised (the account's
|
||||
# employer_id UNIQUE never sees this UPDATE).
|
||||
raise _constraint_error(
|
||||
"guard: employer_accounts.employer_id already set",
|
||||
{"account_id": row.account_id},
|
||||
)
|
||||
account.employer_id = row.employer_id
|
||||
session.flush()
|
||||
# The audit row rides the SAME transaction: the decision
|
||||
# and its provenance land together (all-or-nothing).
|
||||
event = AuditEventRow(
|
||||
account_id=row.account_id,
|
||||
employer_id=row.employer_id,
|
||||
kind="claim",
|
||||
name=f"claim.{decision}",
|
||||
detail={
|
||||
"claim_id": row.id,
|
||||
"employer_id": row.employer_id,
|
||||
"operator": operator,
|
||||
},
|
||||
operator=operator,
|
||||
created_at=moment,
|
||||
)
|
||||
event._validate()
|
||||
event._normalize()
|
||||
session.add(event)
|
||||
session.commit()
|
||||
session.refresh(row)
|
||||
row._normalize()
|
||||
return row
|
||||
|
||||
def list_claims(self, status: str | None = None) -> list[ClaimRow]:
|
||||
"""Newest-first; optional status filter (the admin queue)."""
|
||||
with Session(self._engine) as session:
|
||||
stmt = select(ClaimRow)
|
||||
if status is not None:
|
||||
stmt = stmt.where(ClaimRow.status == status)
|
||||
rows = session.exec(stmt.order_by(col(ClaimRow.created_at).desc(), ClaimRow.id)).all()
|
||||
for row in rows:
|
||||
row._normalize()
|
||||
return list(rows)
|
||||
|
||||
def list_accounts(self) -> list[AccountRow]:
|
||||
"""Created-oldest-first (the admin accounts list)."""
|
||||
with Session(self._engine) as session:
|
||||
rows = session.exec(
|
||||
select(AccountRow).order_by(col(AccountRow.created_at), AccountRow.id)
|
||||
).all()
|
||||
for row in rows:
|
||||
row._normalize()
|
||||
return list(rows)
|
||||
|
||||
def list_audit_events(
|
||||
self,
|
||||
*,
|
||||
account_id: str | None = None,
|
||||
employer_id: str | None = None,
|
||||
kind: str | None = None,
|
||||
name: str | None = None,
|
||||
limit: int = 100,
|
||||
) -> list[AuditEventRow]:
|
||||
"""Newest-first (the list_billing_events shape); optional
|
||||
account/employer/kind/name filters — D-089's operator trail."""
|
||||
with Session(self._engine) as session:
|
||||
stmt = select(AuditEventRow)
|
||||
if account_id is not None:
|
||||
stmt = stmt.where(AuditEventRow.account_id == account_id)
|
||||
if employer_id is not None:
|
||||
stmt = stmt.where(AuditEventRow.employer_id == employer_id)
|
||||
if kind is not None:
|
||||
stmt = stmt.where(AuditEventRow.kind == kind)
|
||||
if name is not None:
|
||||
stmt = stmt.where(AuditEventRow.name == name)
|
||||
rows = session.exec(
|
||||
stmt.order_by(
|
||||
col(AuditEventRow.created_at).desc(),
|
||||
col(AuditEventRow.id),
|
||||
).limit(limit)
|
||||
).all()
|
||||
for row in rows:
|
||||
row._normalize()
|
||||
return list(rows)
|
||||
|
||||
def get_claim(self, claim_id: str) -> ClaimRow | None:
|
||||
with Session(self._engine) as session:
|
||||
row = session.get(ClaimRow, claim_id)
|
||||
if row is None:
|
||||
return None
|
||||
row._normalize()
|
||||
return row
|
||||
|
||||
def get_claim_by_account(
|
||||
self, account_id: str, *, exclude_statuses: tuple[str, ...] = ()
|
||||
) -> ClaimRow | None:
|
||||
"""The account's most recent claim not in exclude_statuses
|
||||
(newest-first; the /me claim-state read)."""
|
||||
with Session(self._engine) as session:
|
||||
stmt = select(ClaimRow).where(ClaimRow.account_id == account_id)
|
||||
if exclude_statuses:
|
||||
stmt = stmt.where(
|
||||
col(ClaimRow.status).not_in(exclude_statuses)
|
||||
)
|
||||
row = session.exec(
|
||||
stmt.order_by(col(ClaimRow.created_at).desc(), ClaimRow.id)
|
||||
).first()
|
||||
if row is None:
|
||||
return None
|
||||
row._normalize()
|
||||
return row
|
||||
|
||||
def close(self) -> None:
|
||||
self._engine.dispose()
|
||||
@@ -66,7 +66,7 @@ from .features import compute_digest
|
||||
from .store import GradeRecord, GradeStore
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - protocol-only import for the optional
|
||||
from ..variants.store import VariantStore # noqa: TC001 (variant-blind without it)
|
||||
from ..variants.store import VariantStore
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -83,7 +83,7 @@ VERDICT_GRADED: Final = "GRADED"
|
||||
_INTEGRITY_FLAG_KEY: Final = "integrity_flag"
|
||||
|
||||
|
||||
def _anchors_context(variant) -> str: # noqa: ANN001 - VariantRecord (duck-typed)
|
||||
def _anchors_context(variant) -> str:
|
||||
"""Render the variant template's difficulty anchors for the grader prompt.
|
||||
|
||||
Contains only the template id + anchor numbers — no learner-identifying
|
||||
@@ -279,7 +279,7 @@ class GradingEngine:
|
||||
created_at=datetime.now(tz=UTC),
|
||||
)
|
||||
|
||||
def _lookup_variant(self, task_id: str): # noqa: ANN202 - VariantRecord | None
|
||||
def _lookup_variant(self, task_id: str):
|
||||
"""MH#4: resolve the graded task's variant (None when not variant-derived)."""
|
||||
if self._variant_store is None:
|
||||
return None
|
||||
|
||||
@@ -37,7 +37,7 @@ from typing import Any, Protocol
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy import JSON, Index
|
||||
from sqlalchemy.orm import validates
|
||||
from sqlmodel import Field, Session, SQLModel, create_engine, select
|
||||
from sqlmodel import Field, Session, SQLModel, col, create_engine, select
|
||||
|
||||
from ..config import Settings
|
||||
|
||||
@@ -225,7 +225,9 @@ class SQLiteGradeStore:
|
||||
.where(GradeRecord.learner_id == learner_id)
|
||||
# Chronological; task_id is a deterministic tie-break for
|
||||
# grades stamped within the same instant.
|
||||
.order_by(GradeRecord.created_at, GradeRecord.task_id)
|
||||
# P5: col() — SQLModel class attrs are Mapped[T], the
|
||||
# column reference rides col() in order_by.
|
||||
.order_by(col(GradeRecord.created_at), GradeRecord.task_id)
|
||||
)
|
||||
results = session.exec(stmt).all()
|
||||
for row in results:
|
||||
|
||||
@@ -87,6 +87,8 @@ class MockIdentityProvider:
|
||||
)
|
||||
return IdentityVerdict(
|
||||
status="verified",
|
||||
# P5: derive_age_band returns str; the verdict's Literal contract —
|
||||
# the derived bands are in-contract by construction.
|
||||
age_band=band, # type: ignore[arg-type]
|
||||
provider="mock",
|
||||
mock=True,
|
||||
|
||||
@@ -22,13 +22,14 @@ module imports config only.
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import sqlite3
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
from typing import Any, Protocol
|
||||
|
||||
from sqlalchemy import event, text
|
||||
from sqlalchemy import event, func, text
|
||||
from sqlalchemy.types import JSON, String
|
||||
from sqlmodel import Field, Session, SQLModel, create_engine
|
||||
from sqlmodel import Field, Session, SQLModel, col, create_engine, select
|
||||
|
||||
from ..config import Settings
|
||||
from .base import IdentityStatus
|
||||
@@ -91,14 +92,16 @@ def _as_utc(ts: datetime) -> datetime:
|
||||
return ts
|
||||
|
||||
|
||||
def _sqlite_connect(dbapi_connection: object, _: object) -> None:
|
||||
"""Per-connection pragmas — mirrors the other D-027 stores."""
|
||||
cursor = dbapi_connection.cursor() # type: ignore[attr-defined]
|
||||
def _sqlite_connect(dbapi_connection: sqlite3.Connection, _: object) -> None:
|
||||
"""Per-connection pragmas — mirrors the other D-027 stores (P5: the
|
||||
concrete sqlite3.Connection type removes the two attr-defined ignores
|
||||
the loose `object` annotation needed)."""
|
||||
cursor = dbapi_connection.cursor()
|
||||
cursor.execute("PRAGMA journal_mode=WAL")
|
||||
cursor.execute("PRAGMA synchronous=NORMAL")
|
||||
cursor.execute("PRAGMA busy_timeout=5000")
|
||||
cursor.execute("PRAGMA foreign_keys=ON")
|
||||
cursor.close() # type: ignore[attr-defined]
|
||||
cursor.close()
|
||||
|
||||
|
||||
class IdentityStore(Protocol):
|
||||
@@ -168,15 +171,16 @@ class SQLiteIdentityStore:
|
||||
# (last inserted wins, mirroring insert-only chronology).
|
||||
# rowid is a SQLite physical column, not a SQLModel field — it
|
||||
# rides the query as raw text.
|
||||
rec = (
|
||||
session.query(IdentityRecord)
|
||||
.filter(IdentityRecord.learner_id == learner_id)
|
||||
rec = session.exec(
|
||||
select(IdentityRecord)
|
||||
.where(IdentityRecord.learner_id == learner_id)
|
||||
.order_by(
|
||||
IdentityRecord.submitted_at.desc(),
|
||||
# P5: col() — SQLModel class attrs are Mapped[T], the
|
||||
# column operators (.desc()) ride col().
|
||||
col(IdentityRecord.submitted_at).desc(),
|
||||
text("rowid DESC"),
|
||||
)
|
||||
.first()
|
||||
)
|
||||
).first()
|
||||
if rec is not None:
|
||||
rec.submitted_at = _as_utc(rec.submitted_at)
|
||||
if rec.verified_at is not None:
|
||||
@@ -185,14 +189,14 @@ class SQLiteIdentityStore:
|
||||
|
||||
def count_pending_for_learner(self, learner_id: str) -> int:
|
||||
with Session(self._engine) as session:
|
||||
return (
|
||||
session.query(IdentityRecord)
|
||||
.filter(
|
||||
return session.exec(
|
||||
select(func.count())
|
||||
.select_from(IdentityRecord)
|
||||
.where(
|
||||
IdentityRecord.learner_id == learner_id,
|
||||
IdentityRecord.status == "pending",
|
||||
)
|
||||
.count()
|
||||
)
|
||||
).one()
|
||||
|
||||
def mark_verified(
|
||||
self, submission_id: str, verdict: dict[str, Any], age_band: str | None
|
||||
|
||||
@@ -12,7 +12,11 @@ from .types import Message
|
||||
|
||||
|
||||
class LLMProvider(Protocol):
|
||||
async def stream_chat(
|
||||
# P5 (D-058): plain `def` returning AsyncIterator — the honest shape for
|
||||
# async-generator implementations. `async def -> AsyncIterator` makes mypy
|
||||
# see a coroutine WRAPPING the iterator (every call site would need an
|
||||
# extra await); async generators ARE functions returning AsyncIterator.
|
||||
def stream_chat(
|
||||
self,
|
||||
messages: list[Message],
|
||||
*,
|
||||
|
||||
@@ -9,6 +9,7 @@ import httpx
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from . import __version__
|
||||
from .agents.registry import AgentRegistry, register_builtin_agents
|
||||
from .agents.session import InMemorySessionStore
|
||||
from .api import (
|
||||
@@ -29,6 +30,11 @@ from .identity.mock import MockIdentityProvider
|
||||
from .identity.store import SQLiteIdentityStore
|
||||
from .llm import create_provider
|
||||
from .sandbox import SandboxManager, UnshareBackend
|
||||
from .sandbox.capability import (
|
||||
DEGRADE_REMEDIATION,
|
||||
container_detected,
|
||||
sandbox_fabric_degraded,
|
||||
)
|
||||
from .telemetry.ingest import TraceIntegrityMap
|
||||
from .telemetry.store import SQLiteTraceStore
|
||||
from .telemetry.tokens import IngestToken
|
||||
@@ -170,6 +176,63 @@ def create_app(settings: Settings | None = None) -> FastAPI:
|
||||
db_path=settings.db_path
|
||||
)
|
||||
|
||||
# Billing engine (v0.9, REQ-9-002): 7th D-027 store family +
|
||||
# the seeded catalog (D-078 — idempotent upsert, safe on every
|
||||
# boot). State-injection override preserved.
|
||||
if getattr(app.state, "billing_store", None) is None:
|
||||
from .billing.store import SQLiteBillingStore
|
||||
|
||||
app.state.billing_store = SQLiteBillingStore(db_path=settings.db_path)
|
||||
if getattr(app.state, "billing_seeded", None) is not True:
|
||||
from .billing.catalog import seed_billing_catalog
|
||||
|
||||
seed_billing_catalog(app.state.billing_store)
|
||||
app.state.billing_seeded = True
|
||||
|
||||
# Employer auth engine (v0.10, REQ-10-001): 8th D-027 store
|
||||
# family on the same SQLite file. State-injection override
|
||||
# preserved (the billing_store getattr-guard template).
|
||||
if getattr(app.state, "employer_store", None) is None:
|
||||
from .employers.store import SQLiteEmployerStore
|
||||
|
||||
app.state.employer_store = SQLiteEmployerStore(
|
||||
db_path=settings.db_path
|
||||
)
|
||||
|
||||
# Placement tracking (v0.11, REQ-11-001): 9th D-027 store
|
||||
# family on the same SQLite file (D-100: the transactional
|
||||
# transition writes the marketplace application row through the
|
||||
# shared metadata — one file, one commit). State-injection
|
||||
# override preserved (the same getattr-guard template).
|
||||
if getattr(app.state, "placement_store", None) is None:
|
||||
from .placements.store import SQLitePlacementStore
|
||||
|
||||
app.state.placement_store = SQLitePlacementStore(
|
||||
db_path=settings.db_path
|
||||
)
|
||||
|
||||
# Payment provider (v0.9 P3, REQ-9-003, D-075): mock-first
|
||||
# default; stripe over the shared httpx pool. G-11 (boot
|
||||
# survival): a misconfigured real provider must never crash the
|
||||
# unattended deploy — fall back to mock loudly (the
|
||||
# voice/embedding pattern).
|
||||
if getattr(app.state, "payment_provider", None) is None:
|
||||
from .billing.factory import payment_provider_from_settings
|
||||
from .billing.mock import MockPaymentProvider
|
||||
|
||||
try:
|
||||
app.state.payment_provider = payment_provider_from_settings(
|
||||
settings, app.state.http_client
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.warning(
|
||||
"payment provider %r unavailable (%s); falling back to "
|
||||
"mock — fix the AI_PAYMENT_* settings and restart",
|
||||
settings.payment_provider,
|
||||
exc,
|
||||
)
|
||||
app.state.payment_provider = MockPaymentProvider()
|
||||
|
||||
# Embedding provider (v0.6 P3, REQ-6-003, D-051): mock-first
|
||||
# feature-hash default; openai-embed against any OpenAI-compatible
|
||||
# embeddings endpoint. State-injection override preserved (the
|
||||
@@ -204,6 +267,19 @@ def create_app(settings: Settings | None = None) -> FastAPI:
|
||||
"author postings, run ingest, and review applications."
|
||||
)
|
||||
|
||||
# G-105 (P5/D-056): an unset origin makes the sitemap serve the
|
||||
# honest empty set and robots omit the Sitemap directive — the
|
||||
# founder must be told loudly at boot (G-11 doctrine; the
|
||||
# request-time fallback never emits malformed/relative URLs).
|
||||
if not (settings.public_base_url or "").strip():
|
||||
logger.warning(
|
||||
"AI_PUBLIC_BASE_URL is unset — /sitemap.xml serves the "
|
||||
"empty static-page set and robots.txt omits the Sitemap "
|
||||
"directive (spec requires absolute URLs). Set the deployed "
|
||||
"origin (e.g. https://nextcraft.example) in .env to serve "
|
||||
"the full sitemap."
|
||||
)
|
||||
|
||||
# Grading persistence + engine (REQ-3-004): GradeStore from the same
|
||||
# SQLite file as traces (D-027), one GradingEngine singleton wired
|
||||
# through app.state — the engine receives its stores via constructor
|
||||
@@ -236,6 +312,24 @@ def create_app(settings: Settings | None = None) -> FastAPI:
|
||||
logger.exception("sandbox reaper pass failed; retrying next tick")
|
||||
|
||||
reaper = asyncio.create_task(_reaper_loop())
|
||||
|
||||
# v0.8 honest degrade (D-068/G-208): probe once at boot; if the
|
||||
# namespace fabric cannot work on this host (unprivileged container
|
||||
# under docker's default seccomp), say so LOUDLY once with the shared
|
||||
# remediation constant — the 503 arm in api/sandboxes.py carries the
|
||||
# same text, so the surfaces cannot drift. The probe is the truth
|
||||
# source; the container marker only tailors the message.
|
||||
if sandbox_fabric_degraded():
|
||||
if container_detected():
|
||||
logger.warning(
|
||||
"SANDBOX FABRIC DEGRADED (container detected): %s",
|
||||
DEGRADE_REMEDIATION,
|
||||
)
|
||||
else:
|
||||
logger.warning(
|
||||
"SANDBOX FABRIC DEGRADED: %s", DEGRADE_REMEDIATION
|
||||
)
|
||||
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
@@ -250,9 +344,12 @@ def create_app(settings: Settings | None = None) -> FastAPI:
|
||||
variant_store.close()
|
||||
defense_store.close()
|
||||
identity_store.close()
|
||||
app.state.billing_store.close()
|
||||
app.state.employer_store.close()
|
||||
app.state.placement_store.close()
|
||||
await app.state.http_client.aclose()
|
||||
|
||||
app = FastAPI(title="Nextcraft AI Service", version="0.3.0", lifespan=lifespan)
|
||||
app = FastAPI(title="Nextcraft AI Service", version=__version__, lifespan=lifespan)
|
||||
|
||||
# A-008 + D-038: no-credentials CORS. Default '*' admits remote-browser
|
||||
# origins in network mode (safe only because allow_credentials stays
|
||||
@@ -261,11 +358,16 @@ def create_app(settings: Settings | None = None) -> FastAPI:
|
||||
# build surface writes workspace files with PUT (engine-client writeFile)
|
||||
# — v0.3 initially shipped without it and every cross-origin Save failed
|
||||
# preflight (caught in P7 review; tests/api/test_cors.py pins the policy).
|
||||
# v0.10 (D-090): "Authorization" joins allow_headers — the employer
|
||||
# session surface sends Bearer tokens, and without it every
|
||||
# cross-origin employer fetch dies preflight in the two-port dev +
|
||||
# D-038 network-mode topologies (the E87 lesson applied before it
|
||||
# ships; test_cors.py pins it).
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=settings.cors_origin_list,
|
||||
allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"],
|
||||
allow_headers=["Content-Type"],
|
||||
allow_headers=["Content-Type", "Authorization"],
|
||||
allow_credentials=False,
|
||||
)
|
||||
|
||||
@@ -298,6 +400,44 @@ def create_app(settings: Settings | None = None) -> FastAPI:
|
||||
app.include_router(marketplace_public_router)
|
||||
app.include_router(marketplace_admin_router)
|
||||
|
||||
# v0.9 billing (REQ-9-002/003): the public catalog + webhook read
|
||||
# surface + the operator checkout routes (admin-gated, D-076). The
|
||||
# mock-complete route is gated by provider selection at runtime
|
||||
# (G-301 — admin-gated AND mock-only), so the router mounts whole.
|
||||
from .api.billing import router as billing_router
|
||||
from .api.billing_admin import router as billing_admin_router
|
||||
|
||||
app.include_router(billing_router)
|
||||
app.include_router(billing_admin_router)
|
||||
|
||||
# v0.10 employers (REQ-10-001): register/login/logout/me session
|
||||
# surface (D-090 Bearer transport; throttles D-088). P2 (REQ-10-002):
|
||||
# the claims route rides the sibling router (session-gated, D-089).
|
||||
from .api.employers import claims_router as employers_claims_router
|
||||
from .api.employers import router as employers_router
|
||||
from .api.employers_admin import router as employers_admin_router
|
||||
|
||||
app.include_router(employers_router)
|
||||
app.include_router(employers_claims_router)
|
||||
# P2 (REQ-10-002, D-089/D-094): the claim review/approve/reject +
|
||||
# accounts/audit operator routes — require_admin (fail-closed).
|
||||
app.include_router(employers_admin_router)
|
||||
|
||||
# v0.11 placements (REQ-11-002, D-106): the operator lane — the
|
||||
# generic transition + revoke + the R-80 re-hire; the reporting/
|
||||
# export reads extend this router in P3/P4. require_admin
|
||||
# composed at the router level (fail-closed, D-090 no-collision).
|
||||
from .api.placements_admin import router as placements_admin_router
|
||||
|
||||
app.include_router(placements_admin_router)
|
||||
|
||||
# v0.6 P5 (REQ-6-006, D-056): dynamic sitemap/robots — request-time
|
||||
# enumeration (build-time Next sitemap.ts cannot see runtime
|
||||
# postings under output:'export'); API routes beat the static mount.
|
||||
from .api.sitemap import router as sitemap_router
|
||||
|
||||
app.include_router(sitemap_router)
|
||||
|
||||
# A-305/D1: PII-safe 422s — FastAPI echoes the offending `input` in
|
||||
# validation errors by default; for the identity submit body that
|
||||
# leaks the raw DOB into responses + client logs. The handler scrubs
|
||||
@@ -305,27 +445,47 @@ def create_app(settings: Settings | None = None) -> FastAPI:
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
def _scrub_pii_validation(request, exc): # type: ignore[unused-arg]
|
||||
pii_fields = frozenset({"date_of_birth"})
|
||||
def _scrub_pii_validation(request, exc):
|
||||
# P5: the old `# type: ignore[unused-arg]` was inert (the unused-arg
|
||||
# code is not enabled by this baseline); removed per D-058.
|
||||
# v0.10 (R-56/open-risk-3): gains "password" + "email" — a pydantic
|
||||
# 422 on an employer register/login body would echo the raw
|
||||
# password into err["input"] (the response + client logs) today.
|
||||
# Security-audit fix (Wave 1-3, task 1-3-01): the field arm alone
|
||||
# leaks on WHOLE-BODY type errors — a non-dict body (list/str/int)
|
||||
# errors at loc == ("body",) with input = the ENTIRE submitted
|
||||
# payload verbatim, which for a mistyped register attempt carries
|
||||
# the raw password. Any body-level error whose input mentions a
|
||||
# PII key (dict or payload-shaped) is scrubbed too.
|
||||
pii_fields = frozenset({"date_of_birth", "password", "email"})
|
||||
scrubbed = []
|
||||
for err in exc.errors():
|
||||
err = dict(err)
|
||||
# FastAPI's default 422s are JSON-safe EXCEPT ctx payloads
|
||||
# carrying raw ValueError objects (pydantic model_validator
|
||||
# errors); strip ctx body-wide so non-PII routes keep their
|
||||
# 422 shape (msg + loc carry the meaning).
|
||||
ctx = err.get("ctx")
|
||||
if isinstance(ctx, dict):
|
||||
err["ctx"] = {
|
||||
k: v for k, v in ctx.items() if isinstance(v, (str, int, float, bool))
|
||||
}
|
||||
if err.get("loc") and err["loc"][-1] in pii_fields:
|
||||
# A-305/D1: never echo the submitted value (input) or the
|
||||
# ctx payload (carries the ValueError); the msg is the
|
||||
# constraint text and is safe.
|
||||
err["input"] = "[redacted]"
|
||||
err.pop("ctx", None)
|
||||
else:
|
||||
# FastAPI's default 422s are JSON-safe EXCEPT ctx payloads
|
||||
# carrying raw ValueError objects (pydantic model_validator
|
||||
# errors); strip ctx body-wide so non-PII routes keep their
|
||||
# 422 shape (msg + loc carry the meaning).
|
||||
ctx = err.get("ctx")
|
||||
if isinstance(ctx, dict):
|
||||
err["ctx"] = {
|
||||
k: v for k, v in ctx.items() if isinstance(v, (str, int, float, bool))
|
||||
}
|
||||
elif err.get("loc") and err["loc"][-1] == "body":
|
||||
# Whole-body error: input is the raw payload — redact
|
||||
# whenever it mentions a PII key (dict with one, or any
|
||||
# container whose repr might embed one). The loc+msg still
|
||||
# carry the failure's meaning; only the echo is dropped.
|
||||
if not isinstance(err.get("input"), dict) or any(
|
||||
key in err["input"] for key in pii_fields
|
||||
):
|
||||
err["input"] = "[redacted]"
|
||||
err.pop("ctx", None)
|
||||
scrubbed.append(err)
|
||||
return JSONResponse(status_code=422, content={"detail": scrubbed})
|
||||
|
||||
@@ -363,7 +523,9 @@ def create_app(settings: Settings | None = None) -> FastAPI:
|
||||
)
|
||||
|
||||
@app.exception_handler(404)
|
||||
async def _spa_404(request, exc): # type: ignore[unused]
|
||||
async def _spa_404(request, exc):
|
||||
# P5: the old `# type: ignore[unused]` was inert (the unused code
|
||||
# is not enabled by this baseline); removed per D-058.
|
||||
not_found_page = web_dir / "404.html"
|
||||
if not_found_page.is_file():
|
||||
return FileResponse(not_found_page, status_code=404)
|
||||
|
||||
@@ -31,7 +31,7 @@ import hashlib
|
||||
import math
|
||||
import re
|
||||
|
||||
from .base import EmbeddingResult
|
||||
from .base import EmbeddingProvider, EmbeddingResult
|
||||
|
||||
#: The mock's fixed dimensionality (D-051) — also its model identity.
|
||||
MOCK_EMBED_DIM = 256
|
||||
@@ -93,7 +93,6 @@ class MockEmbedProvider:
|
||||
|
||||
|
||||
# Protocol-shape parity guard (mock must satisfy the D-051 port).
|
||||
from .base import EmbeddingProvider # noqa: E402
|
||||
|
||||
|
||||
def _assert_protocol() -> None:
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
"""Employer enrichment (REQ-6-004, D-053, A-409).
|
||||
|
||||
One-shot LLM extraction of employer description/social-links/logo from
|
||||
the employer's own posting data, composed through the D-020 pipeline
|
||||
(the D-052 tagging pattern) — no new agent. Enrichment rows are
|
||||
APPEND-ONLY with per-field provenance; merge-on-read precedence is
|
||||
manual > llm > ingested-raw, and every enriched field carries a
|
||||
visible {value, source} marker in API responses (A-304 honesty —
|
||||
LLM-authored copy is never displayed as ingested fact).
|
||||
|
||||
Trigger semantics (enrich-on-first-publish approximation): the publish
|
||||
route fires enrichment when the employer has NO existing llm-source
|
||||
rows — re-publishing the same employer does not re-run (the rows
|
||||
exist). Failure is honest: a warning logs, the publish still succeeds,
|
||||
no rows are written.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
|
||||
from ..agents.structured import structured_completion
|
||||
from ..llm.base import LLMProvider
|
||||
from ..llm.types import Message
|
||||
from .base import Employer
|
||||
from .store import MarketplaceStore
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
#: Prompt version — bump on any wording change (prompts are code).
|
||||
ENRICHMENT_PROMPT_VERSION = 1
|
||||
|
||||
ENRICHMENT_PROMPT = """You are an employer-profile writer for an AI-era
|
||||
roles marketplace. From the employer's own data below, write concise
|
||||
factual profile copy.
|
||||
|
||||
Rules:
|
||||
- description: 1-3 sentences summarizing what the company does, grounded
|
||||
ONLY in the provided data — never invent employers, products, or
|
||||
numbers.
|
||||
- social_links: an object of platform → URL, ONLY for platforms the
|
||||
data names (website, github, linkedin, twitter/x). Empty object if
|
||||
none.
|
||||
- logo_ref: a short reference to the logo source named in the data
|
||||
(e.g. a URL or file name); empty string if none.
|
||||
|
||||
Respond with ONLY the JSON object."""
|
||||
|
||||
_SCHEMA_HINT = (
|
||||
'{"description": "1-3 sentence string", '
|
||||
'"social_links": {"platform": "url"}, '
|
||||
'"logo_ref": "string"}'
|
||||
)
|
||||
|
||||
#: The enrichable field set (D-053) — the manual-override route validates
|
||||
#: against this and the merge walks exactly these keys.
|
||||
ENRICHABLE_FIELDS = ("description", "social_links", "logo")
|
||||
|
||||
_PRECEDENCE = ("manual", "llm")
|
||||
|
||||
|
||||
class EnrichmentUnavailable(Exception):
|
||||
"""The extractor could not produce valid enrichment (provider/parse
|
||||
failure). The publish proceeds; no rows are written (D-053 honesty)."""
|
||||
|
||||
|
||||
class EnrichmentPayload(BaseModel):
|
||||
"""The D-020 extraction schema. extra=forbid keeps the honesty
|
||||
contract (the verifier P2-3 lesson): a non-matching LLM reply must
|
||||
fail validation, not silently parse as all-defaults."""
|
||||
|
||||
model_config = ConfigDict(frozen=True, extra="forbid")
|
||||
|
||||
description: str = ""
|
||||
social_links: dict[str, str] = {}
|
||||
logo_ref: str = ""
|
||||
|
||||
async def enrich_employer(
|
||||
provider: LLMProvider,
|
||||
*,
|
||||
model: str,
|
||||
employer: Employer,
|
||||
postings_hint: list[str] | None = None,
|
||||
) -> EnrichmentPayload:
|
||||
"""One-shot profile extraction via D-020 structured completion.
|
||||
|
||||
`postings_hint` (the employer's posting titles) grounds the copy in
|
||||
the employer's own data. Failures raise EnrichmentUnavailable —
|
||||
honest, never a crash, never fabricated copy."""
|
||||
hint = ""
|
||||
if postings_hint:
|
||||
hint = "\nPosting titles: " + "; ".join(postings_hint[:10])
|
||||
messages = [
|
||||
Message(role="system", content=ENRICHMENT_PROMPT),
|
||||
Message(
|
||||
role="user",
|
||||
content=(
|
||||
f"Employer name: {employer.name}\n"
|
||||
f"Industry: {employer.industry}\n"
|
||||
f"Known description: {employer.description}\n"
|
||||
f"Website: {employer.website}\n"
|
||||
f"Social links: {json.dumps(employer.social_links)}\n"
|
||||
f"Logo: {employer.logo}{hint}"
|
||||
),
|
||||
),
|
||||
]
|
||||
try:
|
||||
return await structured_completion(
|
||||
provider,
|
||||
messages,
|
||||
model=model,
|
||||
schema=EnrichmentPayload,
|
||||
schema_hint=_SCHEMA_HINT,
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.warning(
|
||||
"marketplace enrichment failed for %r: %s — no rows written "
|
||||
"(honest absence, never fabricated copy)",
|
||||
employer.name[:60],
|
||||
exc,
|
||||
)
|
||||
raise EnrichmentUnavailable(str(exc)) from exc
|
||||
|
||||
|
||||
def merge_employer(
|
||||
employer: Employer, rows: list[dict]
|
||||
) -> dict[str, dict]:
|
||||
"""Merge-on-read with per-field provenance (D-053/A-409).
|
||||
|
||||
Precedence per FIELD: manual > llm > ingested-raw — a manual
|
||||
description + llm social_links is legal. Every field carries
|
||||
{value, source, model?}; `social_links` values are dicts (the row
|
||||
stores JSON), the others strings. Newest row per (field, source)
|
||||
wins within a source (append-only, newest-last).
|
||||
"""
|
||||
best: dict[str, dict] = {}
|
||||
for row in rows:
|
||||
field = row.get("field")
|
||||
if field not in ENRICHABLE_FIELDS:
|
||||
continue
|
||||
source = row.get("source")
|
||||
rank = _PRECEDENCE.index(source) if source in _PRECEDENCE else len(_PRECEDENCE)
|
||||
existing = best.get(field)
|
||||
if existing is None or rank < existing["_rank"]:
|
||||
best[field] = {
|
||||
"_rank": rank,
|
||||
"value": row.get("value"),
|
||||
"source": source,
|
||||
"model": row.get("model") or None,
|
||||
}
|
||||
merged: dict[str, dict] = {}
|
||||
for field in ENRICHABLE_FIELDS:
|
||||
raw_value = {
|
||||
"description": employer.description,
|
||||
"social_links": dict(employer.social_links),
|
||||
"logo": employer.logo,
|
||||
}[field]
|
||||
if field in best:
|
||||
entry = best[field]
|
||||
merged[field] = {
|
||||
"value": entry["value"],
|
||||
"source": entry["source"],
|
||||
"model": entry["model"],
|
||||
}
|
||||
else:
|
||||
# No enrichment rows for this field — the ingested raw value
|
||||
# with the honest raw marker (A-304: LLM copy never
|
||||
# masquerades as ingested fact, and vice versa).
|
||||
merged[field] = {"value": raw_value, "source": "raw", "model": None}
|
||||
return merged
|
||||
|
||||
|
||||
async def maybe_enrich_on_publish(
|
||||
store: MarketplaceStore,
|
||||
provider: LLMProvider,
|
||||
*,
|
||||
model: str,
|
||||
employer_id: str,
|
||||
) -> bool:
|
||||
"""Enrich-on-first-publish trigger: fires when the employer has NO
|
||||
existing llm-source rows (re-publishing does not re-run — the rows
|
||||
exist). Returns True when enrichment rows landed. Failures are
|
||||
honest: warning + False, the publish itself already succeeded."""
|
||||
if store.count_enrichment(employer_id, source="llm") > 0:
|
||||
return False
|
||||
employer = store.get_employer(employer_id)
|
||||
if employer is None:
|
||||
return False # dangling employer ref (the seed carries 3) — skip
|
||||
titles = store.employer_posting_titles(employer_id)
|
||||
try:
|
||||
payload = await enrich_employer(
|
||||
provider, model=model, employer=employer, postings_hint=titles
|
||||
)
|
||||
except EnrichmentUnavailable:
|
||||
return False
|
||||
stamp = {"model": model}
|
||||
rows = [
|
||||
("description", payload.description, "llm", stamp),
|
||||
(
|
||||
"social_links",
|
||||
json.dumps(payload.social_links),
|
||||
"llm",
|
||||
stamp,
|
||||
),
|
||||
("logo", payload.logo_ref, "llm", stamp),
|
||||
]
|
||||
for field, value, source, meta in rows:
|
||||
if value not in ("", "{}"):
|
||||
store.append_enrichment(
|
||||
employer_id, field=field, value=value, source=source, **meta
|
||||
)
|
||||
return True
|
||||
@@ -0,0 +1,155 @@
|
||||
"""Resume → profile draft extraction (REQ-6-005, D-054, A-410).
|
||||
|
||||
Pipeline: upload guard (PDF/TXT/MD only, ≤2 MB, text-layer required —
|
||||
empty pypdf extract → honest 422, NO OCR in v0.6) → text extraction →
|
||||
~100K char cap → D-020 structured extraction into ParsedProfile →
|
||||
response carries status="draft" — NOTHING persists to the learner
|
||||
profile until the explicit confirm route (the REQ-6-005 review gate).
|
||||
|
||||
Raw resume bytes are never stored, never logged (A-305 pattern; the
|
||||
existing _scrub_pii_validation handler precedent). The only new
|
||||
dependency is pypdf (probe-verified 6.19.0, pip-reachable via the
|
||||
venv channel).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
from ..agents.structured import structured_completion
|
||||
from ..llm.base import LLMProvider
|
||||
from ..llm.types import Message
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
#: Prompt version — bump on any wording change (prompts are code).
|
||||
RESUME_PROMPT_VERSION = 1
|
||||
|
||||
#: Upload bounds (A-410).
|
||||
MAX_RESUME_BYTES = 2 * 1024 * 1024 # 2 MB
|
||||
ALLOWED_CONTENT_TYPES = ("pdf", "txt", "md")
|
||||
#: Extracted-text cap before the LLM call (A-410: ~100K chars).
|
||||
MAX_EXTRACTED_CHARS = 100_000
|
||||
|
||||
RESUME_PROMPT = """You are a profile parser for an AI-era skills
|
||||
platform. Extract structured profile data from the resume text.
|
||||
|
||||
Rules:
|
||||
- name: the person's name as written, or "" if absent.
|
||||
- headline: a one-line professional headline, or "".
|
||||
- skills: up to 20 concrete skills named in the resume (lowercase,
|
||||
the resume's own vocabulary preferred).
|
||||
- experience_bands: list of {role, years} objects — years is a number
|
||||
(round down; 0 if under a year); [] if none determinable.
|
||||
- competencies: up to 10 competency areas the resume evidences, each a
|
||||
short noun phrase; [] if none.
|
||||
|
||||
Respond with ONLY the JSON object."""
|
||||
|
||||
_SCHEMA_HINT = (
|
||||
'{"name": "string", "headline": "string", '
|
||||
'"skills": ["up to 20 lowercase strings"], '
|
||||
'"experience_bands": [{"role": "string", "years": 0}], '
|
||||
'"competencies": ["up to 10 short phrases"]}'
|
||||
)
|
||||
|
||||
|
||||
class ExperienceBand(BaseModel):
|
||||
"""One role/tenure band the resume evidences."""
|
||||
|
||||
model_config = ConfigDict(frozen=True, extra="forbid")
|
||||
|
||||
role: str = ""
|
||||
years: float = 0
|
||||
|
||||
|
||||
class ParsedProfile(BaseModel):
|
||||
"""The D-020 extraction schema mapped to the competency-profile
|
||||
shape (D-054). extra=forbid keeps the honesty contract — a
|
||||
non-matching reply fails validation, never silently all-defaults
|
||||
(the verifier P2-3 lesson)."""
|
||||
|
||||
model_config = ConfigDict(frozen=True, extra="forbid")
|
||||
|
||||
name: str = ""
|
||||
headline: str = ""
|
||||
skills: list[str] = Field(default_factory=list, max_length=20)
|
||||
experience_bands: list[ExperienceBand] = Field(default_factory=list)
|
||||
competencies: list[str] = Field(default_factory=list, max_length=10)
|
||||
|
||||
|
||||
class ResumeFormatError(Exception):
|
||||
"""Honest upload rejection (422 at the route): unsupported format,
|
||||
missing text layer (empty PDF extract — no OCR in v0.6), or empty
|
||||
file."""
|
||||
|
||||
|
||||
def extract_resume_text(data: bytes, content_type: str) -> str:
|
||||
"""Extract text from an uploaded resume (A-410 bounds enforced by
|
||||
the route BEFORE this call; this handles the decode/parse).
|
||||
|
||||
PDF via pypdf page-text join; TXT/MD raw decode. An empty PDF
|
||||
extract raises ResumeFormatError("text layer required") — the
|
||||
honest no-OCR contract. Raises ResumeFormatError on garbage text
|
||||
bytes too (the honest 422, never a 500)."""
|
||||
ctype = content_type.strip().lower()
|
||||
# Accept both bare and full content types ("application/pdf").
|
||||
if "pdf" in ctype or ctype == "pdf":
|
||||
from io import BytesIO
|
||||
|
||||
from pypdf import PdfReader
|
||||
|
||||
try:
|
||||
reader = PdfReader(BytesIO(data))
|
||||
pages = [(page.extract_text() or "") for page in reader.pages]
|
||||
except Exception as exc:
|
||||
raise ResumeFormatError(
|
||||
"could not read the PDF — is it a valid PDF file?"
|
||||
) from exc
|
||||
text = "\n".join(pages)
|
||||
if not text.strip():
|
||||
raise ResumeFormatError(
|
||||
"text layer required — image-only/scanned PDFs are not "
|
||||
"supported (no OCR in v0.6); upload a text-based PDF, "
|
||||
"TXT, or MD file"
|
||||
)
|
||||
return text
|
||||
if "markdown" in ctype or ctype in ("txt", "md", "text/plain", "text/markdown"):
|
||||
try:
|
||||
text = data.decode("utf-8")
|
||||
except UnicodeDecodeError as exc:
|
||||
raise ResumeFormatError(
|
||||
"could not decode the file as UTF-8 text"
|
||||
) from exc
|
||||
if not text.strip():
|
||||
raise ResumeFormatError("file has no text content")
|
||||
return text
|
||||
raise ResumeFormatError(
|
||||
f"unsupported resume format {content_type!r} — PDF, TXT, or MD only"
|
||||
)
|
||||
|
||||
|
||||
async def parse_resume(
|
||||
provider: LLMProvider,
|
||||
*,
|
||||
model: str,
|
||||
text: str,
|
||||
) -> ParsedProfile:
|
||||
"""Draft extraction via D-020 (never persists — the confirm route
|
||||
is the only write path, D-054/REQ-6-005 review gate)."""
|
||||
capped = text[:MAX_EXTRACTED_CHARS]
|
||||
messages = [
|
||||
Message(role="system", content=RESUME_PROMPT),
|
||||
Message(role="user", content=f"Resume text:\n{capped}"),
|
||||
]
|
||||
# Raw resume text never logs (A-305): only the failure reason rides
|
||||
# the warning below — structured_completion raises on its own path.
|
||||
return await structured_completion(
|
||||
provider,
|
||||
messages,
|
||||
model=model,
|
||||
schema=ParsedProfile,
|
||||
schema_hint=_SCHEMA_HINT,
|
||||
)
|
||||
@@ -21,15 +21,16 @@ this module imports config + base only.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlite3
|
||||
import struct
|
||||
import uuid
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
from typing import Any, Protocol
|
||||
|
||||
from sqlalchemy import UniqueConstraint, event, text
|
||||
from sqlalchemy import UniqueConstraint, event, func, text
|
||||
from sqlalchemy.types import JSON, String
|
||||
from sqlmodel import Field, Session, SQLModel, create_engine
|
||||
from sqlmodel import Field, Session, SQLModel, col, create_engine, select
|
||||
|
||||
from ..config import Settings
|
||||
from .base import (
|
||||
@@ -122,6 +123,7 @@ class PostingRow(SQLModel, table=True):
|
||||
description=self.description,
|
||||
required_competencies=list(self.required_competencies or []),
|
||||
skills=list(self.skills or []),
|
||||
# P5: row stores str; Posting's Literal[...] contract — validated at write.
|
||||
seniority=self.seniority, # type: ignore[arg-type]
|
||||
category=self.category,
|
||||
location=self.location,
|
||||
@@ -129,6 +131,7 @@ class PostingRow(SQLModel, table=True):
|
||||
salary_min=self.salary_min,
|
||||
salary_max=self.salary_max,
|
||||
status=self.status, # type: ignore[arg-type]
|
||||
# P5: tags is the raw JSON dict on the row; Posting wants the model.
|
||||
tags=self.tags, # type: ignore[arg-type]
|
||||
posted_at=_as_utc(self.posted_at) if self.posted_at else None,
|
||||
)
|
||||
@@ -271,14 +274,16 @@ def _decode_vector(blob: bytes, model: str, dim: int) -> list[float]:
|
||||
return list(struct.unpack(f"<{dim}f", bytes(blob)))
|
||||
|
||||
|
||||
def _sqlite_connect(dbapi_connection: object, _: object) -> None:
|
||||
"""Per-connection pragmas — mirrors the other D-027 stores."""
|
||||
cursor = dbapi_connection.cursor() # type: ignore[attr-defined]
|
||||
def _sqlite_connect(dbapi_connection: sqlite3.Connection, _: object) -> None:
|
||||
"""Per-connection pragmas — mirrors the other D-027 stores (P5: the
|
||||
concrete sqlite3.Connection type removes the two attr-defined ignores
|
||||
the loose `object` annotation needed)."""
|
||||
cursor = dbapi_connection.cursor()
|
||||
cursor.execute("PRAGMA journal_mode=WAL")
|
||||
cursor.execute("PRAGMA synchronous=NORMAL")
|
||||
cursor.execute("PRAGMA busy_timeout=5000")
|
||||
cursor.execute("PRAGMA foreign_keys=ON")
|
||||
cursor.close() # type: ignore[attr-defined]
|
||||
cursor.close()
|
||||
|
||||
|
||||
class InvalidTransition(ValueError):
|
||||
@@ -341,12 +346,59 @@ class MarketplaceStore(Protocol):
|
||||
— never a second application."""
|
||||
...
|
||||
|
||||
def get_application(self, application_id: str) -> Application | None:
|
||||
"""Point lookup by application id (D-100: the placements
|
||||
store's transition path reads the row through the shared
|
||||
metadata; this read serves routes + tests — the get_posting
|
||||
shape)."""
|
||||
...
|
||||
|
||||
def get_application_by_posting_learner(
|
||||
self, posting_id: str, learner_id: str
|
||||
) -> Application | None:
|
||||
"""v0.11 P5 (G-322, binding): the mine point-read over the
|
||||
(posting_id, learner_id) unique key — the status panel's
|
||||
application DISCOVERY on revisit; None = no application (the
|
||||
surface renders the apply CTA — never client-persisted
|
||||
application_ids)."""
|
||||
...
|
||||
|
||||
def list_applications_by_postings(
|
||||
self, posting_ids: list[str], status: str | None = None
|
||||
) -> list[Application]:
|
||||
"""v0.11 P2 (D-105/G-319): the employer pipeline's ONE batched
|
||||
read — every application on the given postings (the caller
|
||||
scopes to the session's OWN claimed-entity postings first;
|
||||
this read never enumerates beyond them), created_at DESC then
|
||||
id; optional status facet."""
|
||||
...
|
||||
|
||||
def list_applications(
|
||||
self, posting_id: str | None = None
|
||||
) -> list[Application]:
|
||||
"""Admin review list, newest first; filterable by posting."""
|
||||
...
|
||||
|
||||
def count_applications_by_posting(
|
||||
self, posting_ids: list[str]
|
||||
) -> dict[str, int]:
|
||||
"""v0.10 P3 (G-319/D-092): batched per-posting application
|
||||
COUNTS — ONE grouped read for the whole id set (never a
|
||||
per-posting N+1). Postings with zero applications are absent
|
||||
from the dict (the caller's .get(id, 0) carries the honest 0).
|
||||
Employer-facing surfaces compose this for applicant COUNTS
|
||||
ONLY — learner identifiers never ride any /v1/employers/* read."""
|
||||
...
|
||||
|
||||
def list_postings_by_employer(
|
||||
self, employer_id: str
|
||||
) -> list[Posting]:
|
||||
"""v0.10 P3 (Task 3-1-01): the employer's OWN postings — ALL
|
||||
lifecycle statuses (draft|published|closed — the owner sees the
|
||||
full lifecycle, unlike the public board's published-only page),
|
||||
posted_at DESC then id (the list_postings order)."""
|
||||
...
|
||||
|
||||
def set_posting_tags(self, posting_id: str, tags: PostingTags) -> Posting | None:
|
||||
"""P2 (D-052): persist derived tags — OVERWRITES the tags column
|
||||
(single source of truth; re-tag replaces, never appends)."""
|
||||
@@ -409,6 +461,40 @@ class MarketplaceStore(Protocol):
|
||||
published posting (pure semantic rank path)."""
|
||||
...
|
||||
|
||||
def append_enrichment(
|
||||
self, employer_id: str, *, field: str, value: str, source: str, model: str = ""
|
||||
) -> dict:
|
||||
"""P4-A (D-053/A-409): INSERT an enrichment row — append-only,
|
||||
NO update/delete path exists by design (provenance history is
|
||||
immutable; merge-on-read picks the winner)."""
|
||||
...
|
||||
|
||||
def list_enrichment(self, employer_id: str) -> list[dict]:
|
||||
"""P4-A: all enrichment rows for one employer, newest-first."""
|
||||
...
|
||||
|
||||
def count_enrichment(self, employer_id: str, *, source: str) -> int:
|
||||
"""P4-A: row count filtered by source — the enrich-once trigger
|
||||
(llm rows exist → no re-run)."""
|
||||
...
|
||||
|
||||
def employer_posting_titles(self, employer_id: str) -> list[str]:
|
||||
"""P4-A: the employer's PUBLISHED posting titles (grounding hint
|
||||
for the one-shot extraction)."""
|
||||
...
|
||||
|
||||
def save_learner_profile(
|
||||
self, learner_id: str, profile: dict, *, model: str
|
||||
) -> dict:
|
||||
"""P4-B (G-104/D-054): UPSERT the CONFIRMED learner profile
|
||||
(learner_id PK). The draft NEVER persists without the explicit
|
||||
confirm — this is the only write path."""
|
||||
...
|
||||
|
||||
def get_learner_profile(self, learner_id: str) -> dict | None:
|
||||
"""P4-B: the confirmed profile dict + model, or None."""
|
||||
...
|
||||
|
||||
|
||||
class SQLiteMarketplaceStore:
|
||||
"""SQLite implementation of MarketplaceStore (D-027/D-049)."""
|
||||
@@ -452,14 +538,12 @@ class SQLiteMarketplaceStore:
|
||||
row._validate()
|
||||
row._normalize()
|
||||
with Session(self._engine) as session:
|
||||
existing = (
|
||||
session.query(PostingRow)
|
||||
.filter(
|
||||
existing = session.exec(
|
||||
select(PostingRow).where(
|
||||
PostingRow.source == ingest.source,
|
||||
PostingRow.external_id == ingest.external_id,
|
||||
)
|
||||
.one_or_none()
|
||||
)
|
||||
).one_or_none()
|
||||
if existing is None:
|
||||
session.add(row)
|
||||
else:
|
||||
@@ -530,17 +614,21 @@ class SQLiteMarketplaceStore:
|
||||
self, limit: int, offset: int
|
||||
) -> tuple[list[Posting], int]:
|
||||
with Session(self._engine) as session:
|
||||
total = (
|
||||
session.query(PostingRow)
|
||||
.filter(PostingRow.status == "published")
|
||||
.count()
|
||||
)
|
||||
total = session.exec(
|
||||
select(func.count())
|
||||
.select_from(PostingRow)
|
||||
.where(PostingRow.status == "published")
|
||||
).one()
|
||||
rows = (
|
||||
session.query(PostingRow)
|
||||
.filter(PostingRow.status == "published")
|
||||
.order_by(PostingRow.posted_at.desc(), PostingRow.id)
|
||||
.offset(offset)
|
||||
.limit(limit)
|
||||
session.exec(
|
||||
select(PostingRow)
|
||||
.where(PostingRow.status == "published")
|
||||
# P5: col() — SQLModel class attrs are Mapped[T], the
|
||||
# column operators (.desc()/.isnot()/.in_()) ride col().
|
||||
.order_by(col(PostingRow.posted_at).desc(), PostingRow.id)
|
||||
.offset(offset)
|
||||
.limit(limit)
|
||||
)
|
||||
.all()
|
||||
)
|
||||
return [r.to_posting() for r in rows], total
|
||||
@@ -606,11 +694,9 @@ class SQLiteMarketplaceStore:
|
||||
|
||||
def facets(self) -> dict:
|
||||
with Session(self._engine) as session:
|
||||
rows = (
|
||||
session.query(PostingRow)
|
||||
.filter(PostingRow.status == "published")
|
||||
.all()
|
||||
)
|
||||
rows = session.exec(
|
||||
select(PostingRow).where(PostingRow.status == "published")
|
||||
).all()
|
||||
skills: dict[str, int] = {}
|
||||
seniority: dict[str, int] = {}
|
||||
category: dict[str, int] = {}
|
||||
@@ -675,10 +761,10 @@ class SQLiteMarketplaceStore:
|
||||
self, model_filter: str | None = None
|
||||
) -> list[tuple[str, list[float], str, int]]:
|
||||
with Session(self._engine) as session:
|
||||
query = session.query(EmbeddingRow)
|
||||
stmt = select(EmbeddingRow)
|
||||
if model_filter is not None:
|
||||
query = query.filter(EmbeddingRow.model == model_filter)
|
||||
rows = query.order_by(EmbeddingRow.posting_id).all()
|
||||
stmt = stmt.where(EmbeddingRow.model == model_filter)
|
||||
rows = session.exec(stmt.order_by(EmbeddingRow.posting_id)).all()
|
||||
out: list[tuple[str, list[float], str, int]] = []
|
||||
for row in rows:
|
||||
if row.vector is None or row.dim <= 0:
|
||||
@@ -704,7 +790,7 @@ class SQLiteMarketplaceStore:
|
||||
filter matches postings whose JSON tags.skills array INTERSECTS
|
||||
the requested set (tag-driven sidebar, D-052)."""
|
||||
with Session(self._engine) as session:
|
||||
query = session.query(PostingRow).filter(PostingRow.status == "published")
|
||||
stmt = select(PostingRow).where(PostingRow.status == "published")
|
||||
if skills:
|
||||
# JSON array overlap on the P2 tags column: postings whose
|
||||
# tags.skills INTERSECT the requested set (tag-driven
|
||||
@@ -728,28 +814,30 @@ class SQLiteMarketplaceStore:
|
||||
params,
|
||||
).fetchall()
|
||||
]
|
||||
query = query.filter(PostingRow.id.in_(skill_ids or ["__none__"]))
|
||||
stmt = stmt.where(col(PostingRow.id).in_(skill_ids or ["__none__"]))
|
||||
if seniority is not None:
|
||||
query = query.filter(PostingRow.seniority == seniority)
|
||||
stmt = stmt.where(PostingRow.seniority == seniority)
|
||||
if category is not None:
|
||||
query = query.filter(PostingRow.category == category)
|
||||
stmt = stmt.where(PostingRow.category == category)
|
||||
if location is not None:
|
||||
query = query.filter(PostingRow.location == location)
|
||||
stmt = stmt.where(PostingRow.location == location)
|
||||
if remote is not None:
|
||||
query = query.filter(PostingRow.remote == remote)
|
||||
stmt = stmt.where(PostingRow.remote == remote)
|
||||
if salary_min is not None:
|
||||
# a posting qualifies when its advertised band overlaps
|
||||
# the requested band: posting.salary_max >= salary_min.
|
||||
query = query.filter(
|
||||
PostingRow.salary_max.isnot(None),
|
||||
PostingRow.salary_max >= salary_min,
|
||||
stmt = stmt.where(
|
||||
col(PostingRow.salary_max).isnot(None),
|
||||
col(PostingRow.salary_max) >= salary_min,
|
||||
)
|
||||
if salary_max is not None:
|
||||
query = query.filter(
|
||||
PostingRow.salary_min.isnot(None),
|
||||
PostingRow.salary_min <= salary_max,
|
||||
stmt = stmt.where(
|
||||
col(PostingRow.salary_min).isnot(None),
|
||||
col(PostingRow.salary_min) <= salary_max,
|
||||
)
|
||||
rows = query.order_by(PostingRow.posted_at.desc(), PostingRow.id).all()
|
||||
rows = session.exec(
|
||||
stmt.order_by(col(PostingRow.posted_at).desc(), PostingRow.id)
|
||||
).all()
|
||||
return [r.to_posting() for r in rows]
|
||||
|
||||
# -- employers ----------------------------------------------------------
|
||||
@@ -771,14 +859,12 @@ class SQLiteMarketplaceStore:
|
||||
)
|
||||
row._validate()
|
||||
with Session(self._engine) as session:
|
||||
existing = (
|
||||
session.query(EmployerRow)
|
||||
.filter(
|
||||
existing = session.exec(
|
||||
select(EmployerRow).where(
|
||||
EmployerRow.source == employer.source,
|
||||
EmployerRow.external_id == employer.external_id,
|
||||
)
|
||||
.one_or_none()
|
||||
)
|
||||
).one_or_none()
|
||||
if existing is None:
|
||||
session.add(row)
|
||||
else:
|
||||
@@ -824,14 +910,12 @@ class SQLiteMarketplaceStore:
|
||||
row._validate()
|
||||
row._normalize()
|
||||
with Session(self._engine) as session:
|
||||
existing = (
|
||||
session.query(ApplicationRow)
|
||||
.filter(
|
||||
existing = session.exec(
|
||||
select(ApplicationRow).where(
|
||||
ApplicationRow.posting_id == posting_id,
|
||||
ApplicationRow.learner_id == learner_id,
|
||||
)
|
||||
.one_or_none()
|
||||
)
|
||||
).one_or_none()
|
||||
if existing is not None:
|
||||
# A-408: idempotent — the EXISTING application rides the
|
||||
# 200, never a second row.
|
||||
@@ -843,15 +927,208 @@ class SQLiteMarketplaceStore:
|
||||
session.refresh(row)
|
||||
return row.to_application(), True
|
||||
|
||||
def get_application(self, application_id: str) -> Application | None:
|
||||
"""Point lookup by application id (D-100, the get_posting shape)."""
|
||||
with Session(self._engine) as session:
|
||||
row = session.get(ApplicationRow, application_id)
|
||||
if row is None:
|
||||
return None
|
||||
session.refresh(row)
|
||||
return row.to_application()
|
||||
|
||||
def get_application_by_posting_learner(
|
||||
self, posting_id: str, learner_id: str
|
||||
) -> Application | None:
|
||||
"""v0.11 P5 (G-322): the mine point-read — one row over the
|
||||
insert_application unique key (the get_posting point-read
|
||||
discipline)."""
|
||||
with Session(self._engine) as session:
|
||||
row = session.exec(
|
||||
select(ApplicationRow).where(
|
||||
ApplicationRow.posting_id == posting_id,
|
||||
ApplicationRow.learner_id == learner_id,
|
||||
)
|
||||
).one_or_none()
|
||||
if row is None:
|
||||
return None
|
||||
session.refresh(row)
|
||||
return row.to_application()
|
||||
|
||||
def list_applications_by_postings(
|
||||
self, posting_ids: list[str], status: str | None = None
|
||||
) -> list[Application]:
|
||||
"""v0.11 P2 (D-105/G-319): ONE batched read over the given
|
||||
postings — created_at DESC then id; optional status facet.
|
||||
Empty posting set → empty list (the honest no-postings case)."""
|
||||
if not posting_ids:
|
||||
return []
|
||||
with Session(self._engine) as session:
|
||||
stmt = select(ApplicationRow).where(
|
||||
col(ApplicationRow.posting_id).in_(posting_ids)
|
||||
)
|
||||
if status is not None:
|
||||
stmt = stmt.where(ApplicationRow.status == status)
|
||||
rows = session.exec(
|
||||
stmt.order_by(
|
||||
col(ApplicationRow.created_at).desc(), ApplicationRow.id
|
||||
)
|
||||
).all()
|
||||
return [r.to_application() for r in rows]
|
||||
|
||||
def list_applications(
|
||||
self, posting_id: str | None = None
|
||||
) -> list[Application]:
|
||||
with Session(self._engine) as session:
|
||||
query = session.query(ApplicationRow)
|
||||
stmt = select(ApplicationRow)
|
||||
if posting_id is not None:
|
||||
query = query.filter(ApplicationRow.posting_id == posting_id)
|
||||
rows = query.order_by(ApplicationRow.created_at.desc()).all()
|
||||
stmt = stmt.where(ApplicationRow.posting_id == posting_id)
|
||||
rows = session.exec(
|
||||
stmt.order_by(col(ApplicationRow.created_at).desc())
|
||||
).all()
|
||||
return [r.to_application() for r in rows]
|
||||
|
||||
def count_applications_by_posting(
|
||||
self, posting_ids: list[str]
|
||||
) -> dict[str, int]:
|
||||
"""G-319: ONE grouped read — SELECT posting_id, COUNT(*) ...
|
||||
GROUP BY posting_id — for the whole id set. Zero-application
|
||||
postings absent (honest 0 via the caller's .get(id, 0))."""
|
||||
if not posting_ids:
|
||||
return {}
|
||||
with Session(self._engine) as session:
|
||||
rows = session.exec(
|
||||
select(
|
||||
ApplicationRow.posting_id,
|
||||
func.count(),
|
||||
)
|
||||
.where(col(ApplicationRow.posting_id).in_(posting_ids))
|
||||
.group_by(ApplicationRow.posting_id)
|
||||
).all()
|
||||
return {posting_id: count for posting_id, count in rows}
|
||||
|
||||
def list_postings_by_employer(
|
||||
self, employer_id: str
|
||||
) -> list[Posting]:
|
||||
"""The owner's full-lifecycle read (Task 3-1-01): ALL statuses,
|
||||
posted_at DESC then id (the list_postings order — drafts with
|
||||
no posted_at sort last within the None-ordered tie band)."""
|
||||
with Session(self._engine) as session:
|
||||
rows = (
|
||||
session.exec(
|
||||
select(PostingRow)
|
||||
.where(PostingRow.employer_id == employer_id)
|
||||
.order_by(
|
||||
col(PostingRow.posted_at).desc(), PostingRow.id
|
||||
)
|
||||
)
|
||||
.all()
|
||||
)
|
||||
return [r.to_posting() for r in rows]
|
||||
|
||||
# -- P4-A: enrichment (append-only, D-053) --------------------------------
|
||||
|
||||
def append_enrichment(
|
||||
self, employer_id: str, *, field: str, value: str, source: str, model: str = ""
|
||||
) -> dict:
|
||||
row = EmployerEnrichmentRow(
|
||||
id=f"enr-{uuid.uuid4().hex[:16]}",
|
||||
employer_id=employer_id,
|
||||
field=field,
|
||||
value=value,
|
||||
source=source,
|
||||
model=model,
|
||||
created_at=datetime.now(UTC),
|
||||
)
|
||||
with Session(self._engine) as session:
|
||||
session.add(row) # INSERT only — no update/delete path exists
|
||||
session.commit()
|
||||
return {
|
||||
"id": row.id,
|
||||
"employer_id": row.employer_id,
|
||||
"field": row.field,
|
||||
"value": row.value,
|
||||
"source": row.source,
|
||||
"model": row.model,
|
||||
"created_at": row.created_at,
|
||||
}
|
||||
|
||||
def list_enrichment(self, employer_id: str) -> list[dict]:
|
||||
with Session(self._engine) as session:
|
||||
rows = session.exec(
|
||||
select(EmployerEnrichmentRow)
|
||||
.where(EmployerEnrichmentRow.employer_id == employer_id)
|
||||
.order_by(col(EmployerEnrichmentRow.created_at).desc(), EmployerEnrichmentRow.id)
|
||||
).all()
|
||||
return [
|
||||
{
|
||||
"id": r.id,
|
||||
"employer_id": r.employer_id,
|
||||
"field": r.field,
|
||||
"value": r.value,
|
||||
"source": r.source,
|
||||
"model": r.model,
|
||||
"created_at": _as_utc(r.created_at) if r.created_at else None,
|
||||
}
|
||||
for r in rows
|
||||
]
|
||||
|
||||
def count_enrichment(self, employer_id: str, *, source: str) -> int:
|
||||
with Session(self._engine) as session:
|
||||
return session.exec(
|
||||
select(func.count())
|
||||
.select_from(EmployerEnrichmentRow)
|
||||
.where(
|
||||
EmployerEnrichmentRow.employer_id == employer_id,
|
||||
EmployerEnrichmentRow.source == source,
|
||||
)
|
||||
).one()
|
||||
|
||||
def employer_posting_titles(self, employer_id: str) -> list[str]:
|
||||
with Session(self._engine) as session:
|
||||
rows = session.exec(
|
||||
select(PostingRow)
|
||||
.where(
|
||||
PostingRow.employer_id == employer_id,
|
||||
PostingRow.status == "published",
|
||||
)
|
||||
.order_by(col(PostingRow.posted_at).desc())
|
||||
).all()
|
||||
return [r.title for r in rows]
|
||||
|
||||
# -- P4-B: confirmed learner profiles (G-104/D-054) ----------------------
|
||||
|
||||
def save_learner_profile(
|
||||
self, learner_id: str, profile: dict, *, model: str
|
||||
) -> dict:
|
||||
with Session(self._engine) as session:
|
||||
row = session.get(LearnerProfileRow, learner_id)
|
||||
if row is None:
|
||||
row = LearnerProfileRow(learner_id=learner_id)
|
||||
row.profile = dict(profile)
|
||||
row.model = model
|
||||
row.confirmed_at = datetime.now(UTC)
|
||||
session.add(row)
|
||||
session.commit()
|
||||
session.refresh(row)
|
||||
return {
|
||||
"learner_id": row.learner_id,
|
||||
"profile": dict(row.profile),
|
||||
"model": row.model,
|
||||
"confirmed_at": _as_utc(row.confirmed_at) if row.confirmed_at else None,
|
||||
}
|
||||
|
||||
def get_learner_profile(self, learner_id: str) -> dict | None:
|
||||
with Session(self._engine) as session:
|
||||
row = session.get(LearnerProfileRow, learner_id)
|
||||
if row is None:
|
||||
return None
|
||||
session.refresh(row)
|
||||
return {
|
||||
"learner_id": row.learner_id,
|
||||
"profile": dict(row.profile),
|
||||
"model": row.model,
|
||||
"confirmed_at": _as_utc(row.confirmed_at) if row.confirmed_at else None,
|
||||
}
|
||||
|
||||
def close(self) -> None:
|
||||
self._engine.dispose()
|
||||
|
||||
@@ -0,0 +1,380 @@
|
||||
"""Placement contracts: the D-099 hiring-state matrix, the D-101
|
||||
event vocabulary + GENESIS, and the placement wire shapes (REQ-11-001).
|
||||
|
||||
Boundary (D-031 family): `placements/` never imports `api/`; stdlib +
|
||||
pydantic + the marketplace WIRE contracts only. The store imports the
|
||||
marketplace ROW (the sanctioned D-100 cross-family seam — one
|
||||
transaction covers both tables on the shared DB file).
|
||||
|
||||
Id honesty (A-305, the family rule): every id in this module is an
|
||||
opaque handle minted UNIQUELY per creation call — never derived from
|
||||
user input or a deterministic hash of it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime
|
||||
from typing import Any, Literal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
#: D-099 application status vocabulary (snake_case, the billing
|
||||
#: `past_due` precedent): the hiring lifecycle. `submitted` is the
|
||||
#: v0.6 status (zero migration); hired/rejected/withdrawn are TERMINAL.
|
||||
ApplicationStatus = Literal[
|
||||
"submitted",
|
||||
"in_review",
|
||||
"interview",
|
||||
"offer",
|
||||
"hired",
|
||||
"rejected",
|
||||
"withdrawn",
|
||||
]
|
||||
|
||||
#: Tuple mirror of the Literal (docs + tests import this).
|
||||
APPLICATION_STATUSES: tuple[ApplicationStatus, ...] = (
|
||||
"submitted",
|
||||
"in_review",
|
||||
"interview",
|
||||
"offer",
|
||||
"hired",
|
||||
"rejected",
|
||||
"withdrawn",
|
||||
)
|
||||
|
||||
#: Terminal statuses — no outgoing edges (D-099).
|
||||
TERMINAL_APPLICATION_STATUSES: tuple[ApplicationStatus, ...] = (
|
||||
"hired",
|
||||
"rejected",
|
||||
"withdrawn",
|
||||
)
|
||||
|
||||
#: D-099 transition matrix (the billing/store.py `_VALID_TRANSITIONS`
|
||||
#: shape): forward-only WITH skip-forward — from any non-terminal
|
||||
#: status, any LATER stage and any terminal are legal (a fast-track
|
||||
#: `submitted → hired` is a legal hire — CIRR counts the hire, not the
|
||||
#: ceremony); NO backward moves; terminals have empty tuples.
|
||||
TRANSITION_MATRIX: dict[str, tuple[str, ...]] = {
|
||||
"submitted": (
|
||||
"in_review",
|
||||
"interview",
|
||||
"offer",
|
||||
"hired",
|
||||
"rejected",
|
||||
"withdrawn",
|
||||
),
|
||||
"in_review": ("interview", "offer", "hired", "rejected", "withdrawn"),
|
||||
"interview": ("offer", "hired", "rejected", "withdrawn"),
|
||||
"offer": ("hired", "rejected", "withdrawn"),
|
||||
"hired": (),
|
||||
"rejected": (),
|
||||
"withdrawn": (),
|
||||
}
|
||||
|
||||
#: Placement lifecycle (D-102): created `active`; the ONLY transition
|
||||
#: is the operator correction `active → revoked`. Revoked rows stay in
|
||||
#: history (the partial unique index never touches them — re-hire
|
||||
#: creates a fresh row, R-80).
|
||||
PlacementStatus = Literal["active", "revoked"]
|
||||
PLACEMENT_STATUSES: tuple[PlacementStatus, ...] = ("active", "revoked")
|
||||
|
||||
#: D-101 actor vocabulary (the billing `_BILLING_EVENT_KINDS` shape).
|
||||
ACTOR_TYPES: tuple[str, ...] = ("employer", "learner", "operator", "system")
|
||||
|
||||
#: D-101 event-name vocabulary: application-stage events (one per
|
||||
#: transition — NO backfill: pre-v0.11 `submitted` rows carry only
|
||||
#: their created_at, never a fabricated event, A-304) + the placement
|
||||
#: lane (created on hired, revoked on the D-102 correction, rehired
|
||||
#: on the R-80 operator re-hire).
|
||||
EVENT_APPLICATION_TRANSITION: dict[str, str] = {
|
||||
"in_review": "application.in_review",
|
||||
"interview": "application.interview",
|
||||
"offer": "application.offer",
|
||||
"hired": "application.hired",
|
||||
"rejected": "application.rejected",
|
||||
"withdrawn": "application.withdrawn",
|
||||
}
|
||||
EVENT_PLACEMENT_CREATED = "placement.created"
|
||||
EVENT_PLACEMENT_REVOKED = "placement.revoked"
|
||||
EVENT_PLACEMENT_REHIRED = "placement.rehired"
|
||||
EVENT_NAMES: tuple[str, ...] = (
|
||||
*EVENT_APPLICATION_TRANSITION.values(),
|
||||
EVENT_PLACEMENT_CREATED,
|
||||
EVENT_PLACEMENT_REVOKED,
|
||||
EVENT_PLACEMENT_REHIRED,
|
||||
)
|
||||
|
||||
#: D-101: the chain's genesis — the first event's prev_hash. A module
|
||||
#: constant, test-pinned (never a row — the walk starts here).
|
||||
GENESIS_HASH = "0" * 64
|
||||
|
||||
|
||||
class InvalidTransition(ValueError):
|
||||
"""A matrix-illegal application status move (D-099) or placement
|
||||
status move (D-102) — the route's honest 409."""
|
||||
|
||||
|
||||
def is_terminal(status: str) -> bool:
|
||||
"""True when the application status has no outgoing edges."""
|
||||
return status in TERMINAL_APPLICATION_STATUSES
|
||||
|
||||
|
||||
def validate_transition(from_status: str, to_status: str) -> None:
|
||||
"""D-099 matrix validation — raises InvalidTransition on any
|
||||
illegal move (backward, terminal-source, unknown status)."""
|
||||
if from_status not in TRANSITION_MATRIX:
|
||||
raise InvalidTransition(f"unknown application status {from_status!r}")
|
||||
if to_status not in APPLICATION_STATUSES:
|
||||
raise InvalidTransition(f"unknown application status {to_status!r}")
|
||||
if to_status not in TRANSITION_MATRIX[from_status]:
|
||||
legal = TRANSITION_MATRIX[from_status] or "(terminal)"
|
||||
raise InvalidTransition(
|
||||
f"illegal transition {from_status!r} → {to_status!r} "
|
||||
f"(legal: {legal})"
|
||||
)
|
||||
|
||||
|
||||
class HireTransitionRequest(BaseModel):
|
||||
"""The hire body (D-103/G-324): role_title is employer-attested
|
||||
free text — never silently the posting title — with the house
|
||||
Field bounds (empty-string → 422); start_date is the employment
|
||||
start DATE (first day of work), never a datetime: timezone-free by
|
||||
construction, future + past allowed (D-103)."""
|
||||
|
||||
role_title: str = Field(min_length=1, max_length=200)
|
||||
start_date: date
|
||||
|
||||
|
||||
class PlacementRead(BaseModel):
|
||||
"""A placement record over the wire (the PlacementRow read shape).
|
||||
|
||||
employer/learner/posting are ID REFERENCES (G-302) — resolved from
|
||||
source rows at read/export, never trusted denormalized copies."""
|
||||
|
||||
model_config = ConfigDict(frozen=True)
|
||||
|
||||
id: str = Field(min_length=1)
|
||||
learner_id: str = Field(min_length=1)
|
||||
employer_id: str = Field(min_length=1)
|
||||
posting_id: str = Field(min_length=1)
|
||||
application_id: str = Field(min_length=1)
|
||||
role_title: str = Field(min_length=1)
|
||||
start_date: date
|
||||
status: PlacementStatus
|
||||
created_at: datetime
|
||||
decided_at: datetime
|
||||
|
||||
|
||||
class PlacementEventRead(BaseModel):
|
||||
"""One ledger event over the wire (the PlacementEventRow read
|
||||
shape) — application-stage events carry application_id with
|
||||
placement_id None; the placement lane carries placement_id set."""
|
||||
|
||||
model_config = ConfigDict(frozen=True)
|
||||
|
||||
id: int
|
||||
application_id: str | None = None
|
||||
placement_id: str | None = None
|
||||
event_type: str = Field(min_length=1)
|
||||
actor_type: str = Field(min_length=1)
|
||||
actor_ref: str = Field(min_length=1)
|
||||
payload: dict[str, Any] = Field(default_factory=dict)
|
||||
prev_hash: str = Field(min_length=1)
|
||||
hash: str = Field(min_length=1)
|
||||
created_at: datetime
|
||||
|
||||
|
||||
class EmployerApplicationSummary(BaseModel):
|
||||
"""An employer-facing application row (D-105/G-319): the pipeline
|
||||
list + per-application reads. learner_id IS visible here — the
|
||||
G-319 supersession scopes it to applications on the session's OWN
|
||||
claimed-entity postings (the cross-entity arm 403s carry no data;
|
||||
the own-postings LIST stays counts-only — the pin split)."""
|
||||
|
||||
model_config = ConfigDict(frozen=True)
|
||||
|
||||
id: str = Field(min_length=1)
|
||||
posting_id: str = Field(min_length=1)
|
||||
learner_id: str = Field(min_length=1)
|
||||
status: ApplicationStatus
|
||||
created_at: datetime | None = None
|
||||
|
||||
|
||||
class EmployerApplicationsResponse(BaseModel):
|
||||
"""GET /v1/employers/applications response: own-pipeline
|
||||
applications (every status) + per-status facet counts (every
|
||||
status key ALWAYS present — a zero-count status carries its
|
||||
honest 0)."""
|
||||
|
||||
model_config = ConfigDict(frozen=True)
|
||||
|
||||
applications: list[EmployerApplicationSummary] = Field(default_factory=list)
|
||||
facets: dict[str, int] = Field(default_factory=dict)
|
||||
total: int = 0
|
||||
|
||||
|
||||
class ApplicationTransitionResponse(BaseModel):
|
||||
"""The transition result (per-target routes): the application's
|
||||
new status + the placement record when the transition created
|
||||
one (hire)."""
|
||||
|
||||
model_config = ConfigDict(frozen=True)
|
||||
|
||||
application_id: str = Field(min_length=1)
|
||||
status: ApplicationStatus
|
||||
placement: PlacementRead | None = None
|
||||
|
||||
|
||||
class AdminTransitionRequest(BaseModel):
|
||||
"""POST /v1/placements/admin/applications/{id}/transition body
|
||||
(D-106/G-327): `to` is a CLOSED Literal of the seven D-099
|
||||
statuses — unknown values die at pydantic (422), matrix-illegal
|
||||
known values reach the store (409 InvalidTransition); the route
|
||||
never sees a status outside the vocabulary. role_title/start_date
|
||||
are required iff to=hired (enforced at the route, the honest 422
|
||||
with required-fields detail)."""
|
||||
|
||||
model_config = ConfigDict(frozen=True)
|
||||
|
||||
to: ApplicationStatus
|
||||
role_title: str | None = Field(default=None, min_length=1, max_length=200)
|
||||
start_date: date | None = None
|
||||
|
||||
|
||||
#: D-107: the guiding outcome's north star (PROJECT.md line 7 — the
|
||||
#: noun is LEARNERS, not placements).
|
||||
GUIDING_GOAL = 1000
|
||||
|
||||
#: D-108/G-321/G-325 (R-67/R-68): the export's methodology block —
|
||||
#: written from in-tree facts, stating its own three pilot gaps
|
||||
#: explicitly (an audit methodology that omits its own verification
|
||||
#: limits is A-304-class dishonesty) AND the chain's proof scope
|
||||
#: (G-321: what it proves, what it does not — wholesale DB replacement
|
||||
#: is undetectable by the walk alone; export-to-export continuity is
|
||||
#: the auditor's anchor — plus the event↔row cross-consistency check).
|
||||
#: CIRR kept as naming, not citation — the text stands on its own
|
||||
#: definitions (R-67).
|
||||
EXPORT_METHODOLOGY: dict[str, Any] = {
|
||||
"placement_definition": (
|
||||
"A placement is a `placement` row created by the hired transition "
|
||||
"of a marketplace application, with an employer-attested role_title "
|
||||
"and start_date (the employment start DATE, D-103), status=active "
|
||||
"at export time. One ACTIVE placement per application is "
|
||||
"structurally enforced (the partial unique index); revoked "
|
||||
"placements stay in history and are excluded from every count."
|
||||
),
|
||||
"counting_rules": (
|
||||
"The guiding metric is DISTINCT learners with at least one active "
|
||||
"placement, all-time cumulative toward the 1,000-learner guiding "
|
||||
"goal (a learner placed twice counts ONCE — the outcome's noun is "
|
||||
"learners, not placements). Revoked placements are excluded from "
|
||||
"every count. Cohort month is the calendar month of start_date "
|
||||
"(YYYY-MM) — the employment-start month, not a graduation cohort "
|
||||
"(no graduation events exist in a marketplace; this divergence "
|
||||
"from CIRR cohort convention is deliberate and documented)."
|
||||
),
|
||||
"verification": (
|
||||
"WHAT THE CHAIN PROVES: the global sha256 ledger (events ordered "
|
||||
"by id, each hash covering the canonical JSON of its row + the "
|
||||
"prior event's hash, from the GENESIS constant to the head) "
|
||||
"detects in-place mutation of any event row and makes a chain "
|
||||
"fork structurally impossible (UNIQUE(prev_hash)). WHAT IT DOES "
|
||||
"NOT PROVE: a wholesale replacement of the database (delete every "
|
||||
"event, re-append a fresh plausible chain from GENESIS) walks "
|
||||
"green — the walk alone cannot detect it. THE AUDITOR'S ANCHOR "
|
||||
"is export-to-export continuity: a prior export's ledger.events "
|
||||
"must appear as an exact PREFIX of a later export's events, and "
|
||||
"the prior export's head_hash must equal the hash at that prefix "
|
||||
"position in the later export. EVENT↔ROW CROSS-CONSISTENCY: "
|
||||
"every active placement must have a placement.created event; "
|
||||
"every revoked placement a placement.revoked event; summary."
|
||||
"revoked_count must equal the number of placement.revoked "
|
||||
"events. EVIDENCE CLASS: verification is employer-principal "
|
||||
"attestation (an authenticated hire by a claim-verified, "
|
||||
"operator-approved employer principal) plus operator oversight — "
|
||||
"recorded decisions, not third-party employment verification."
|
||||
),
|
||||
"scope": (
|
||||
"PILOT LIMITS, stated explicitly (R-67): (a) no minimum-employed-"
|
||||
"duration check — a placement here is a RECORDED HIRE, not a "
|
||||
"90-day sustained role; (b) no salary or compensation tracking "
|
||||
"(out of scope by decision D-098); (c) verification is employer-"
|
||||
"attested with operator oversight, NOT third-party employment "
|
||||
"verification — no external auditor integration exists at "
|
||||
"pilot; this export IS the third-party-auditor deliverable. "
|
||||
"Coverage: every placement in the database, unbounded by date. "
|
||||
"CIRR-style describes this export's format; the definitions "
|
||||
"above are the operative ones."
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
class PlacementOverview(BaseModel):
|
||||
"""GET /v1/placements/admin/overview response (D-107): counts
|
||||
computed from rows at query time — NEVER denormalized counters
|
||||
(G-302/G-306). The guiding metric is DISTINCT learners with ≥1
|
||||
active placement (a learner placed twice counts ONCE); revoked
|
||||
excluded from every count; cohort month = the calendar month of
|
||||
start_date (YYYY-MM, employment-start month — not hired month)."""
|
||||
|
||||
model_config = ConfigDict(frozen=True)
|
||||
|
||||
total_active_placements: int = 0
|
||||
distinct_learners_placed: int = 0
|
||||
guiding_goal: int = GUIDING_GOAL
|
||||
by_employer: list[dict[str, Any]] = Field(default_factory=list)
|
||||
by_cohort_month: list[dict[str, Any]] = Field(default_factory=list)
|
||||
|
||||
|
||||
class EmployerPlacementsResponse(BaseModel):
|
||||
"""GET /v1/employers/placements response (D-109 surface 2's data
|
||||
source): the claimed entity's OWN placements (active + revoked —
|
||||
the employer sees their full history), created_at then id."""
|
||||
|
||||
model_config = ConfigDict(frozen=True)
|
||||
|
||||
placements: list[PlacementRead] = Field(default_factory=list)
|
||||
total: int = 0
|
||||
|
||||
|
||||
class LearnerApplicationSummary(BaseModel):
|
||||
"""The application row on the learner status read (D-104,
|
||||
REQ-11-005): the mine-visible fields only — ids + status + the
|
||||
apply timestamp (nullable per the v0.6 row shape — honest
|
||||
absence); references resolve at render (G-302), never
|
||||
denormalized copies."""
|
||||
|
||||
model_config = ConfigDict(frozen=True)
|
||||
|
||||
id: str = Field(min_length=1)
|
||||
posting_id: str = Field(min_length=1)
|
||||
learner_id: str = Field(min_length=1)
|
||||
status: ApplicationStatus
|
||||
created_at: datetime | None = None
|
||||
|
||||
|
||||
class LearnerApplicationStatusResponse(BaseModel):
|
||||
"""GET /v1/marketplace/applications/{application_id}?learner_id=
|
||||
response (REQ-11-005, D-104): current status + the FULL id-ordered
|
||||
timestamped event history for THIS application (a scoped query —
|
||||
never another learner's events) + the placement record when hired
|
||||
(the honest null otherwise — never a fabricated placement, A-304)."""
|
||||
|
||||
model_config = ConfigDict(frozen=True)
|
||||
|
||||
application: LearnerApplicationSummary
|
||||
events: list[PlacementEventRead] = Field(default_factory=list)
|
||||
placement: PlacementRead | None = None
|
||||
|
||||
|
||||
class MineApplicationResponse(BaseModel):
|
||||
"""GET /v1/marketplace/applications/mine?posting_id=&learner_id=
|
||||
response (G-322, binding): {application_id, status} — the status
|
||||
panel's application DISCOVERY read on revisit; 404 = no application
|
||||
on this posting (the surface renders the apply CTA — the panel
|
||||
NEVER depends on client-persisted application_ids)."""
|
||||
|
||||
model_config = ConfigDict(frozen=True)
|
||||
|
||||
application_id: str = Field(min_length=1)
|
||||
status: ApplicationStatus
|
||||
@@ -0,0 +1,912 @@
|
||||
"""Placement persistence — the 9th D-027 store (REQ-11-001, D-112).
|
||||
|
||||
TWO tables on the shared DB file (R-72): `placement` (immutable at
|
||||
creation except status — D-102) + `placement_event` (the append-only
|
||||
GLOBAL hash chain — D-101). Mechanics mirror employers/store.py
|
||||
exactly (pragmas, _validate/_normalize, Protocol + SQLite pair,
|
||||
surfaced IntegrityError, _constraint_error helper).
|
||||
|
||||
NO DELETE PATH (R-70, binding): this module contains NO delete method
|
||||
and NO DELETE SQL — deleting the top ledger row would make SQLite's
|
||||
INTEGER PRIMARY KEY reuse max+1 and break the chain. Pinned by test.
|
||||
|
||||
STATUS-COLUMN OWNERSHIP (R-78, binding): the marketplace store writes
|
||||
`application.status` EXACTLY ONCE at creation (insert_application);
|
||||
THIS store is the ONLY post-creation writer — via the ONE
|
||||
`transition_application` method, never a second append path (D-100:
|
||||
the status write + the ledger event + the placement-on-hired land in
|
||||
ONE transaction; a two-commit alternative leaves a crash window that
|
||||
voids the tamper-evidence this milestone sells).
|
||||
|
||||
Canonical serialization (D-101/R-69/R-79, binding): the hash covers
|
||||
the canonical JSON of {id, application_id, placement_id, event_type,
|
||||
actor_type, actor_ref, payload, created_at} + prev_hash — sorted keys,
|
||||
compact separators, created_at ALWAYS `_as_utc(dt).isoformat()` (ONE
|
||||
pinned normalization: naive-in-SQLite vs aware-on-read must never
|
||||
drift), payload values str/int/bool/None only (floats REJECTED —
|
||||
R-69).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import sqlite3
|
||||
import uuid
|
||||
from datetime import UTC, date, datetime
|
||||
from pathlib import Path
|
||||
from typing import Any, Protocol
|
||||
|
||||
from sqlalchemy import Index, event, func, text
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.types import JSON, String
|
||||
from sqlmodel import Field, Session, SQLModel, col, create_engine, select
|
||||
|
||||
from ..config import Settings
|
||||
from ..marketplace.store import ApplicationRow
|
||||
from .base import (
|
||||
ACTOR_TYPES,
|
||||
EVENT_APPLICATION_TRANSITION,
|
||||
EVENT_PLACEMENT_CREATED,
|
||||
EVENT_PLACEMENT_REHIRED,
|
||||
EVENT_PLACEMENT_REVOKED,
|
||||
EXPORT_METHODOLOGY,
|
||||
GENESIS_HASH,
|
||||
InvalidTransition,
|
||||
validate_transition,
|
||||
)
|
||||
|
||||
_PLACEMENT_ID_PREFIX = "plc-"
|
||||
|
||||
|
||||
def _as_utc(ts: datetime) -> datetime:
|
||||
"""SQLite stores naive; read paths re-label tz-aware UTC (D-027
|
||||
pattern). Aware NON-UTC inputs CONVERT to the true instant (the
|
||||
security review's P0-1: re-labeling preserves the offset — an
|
||||
append-time canonical form of 12:00-04:00 would re-read as
|
||||
12:00+00:00 and permanently break the chain, with no delete path
|
||||
to recover)."""
|
||||
if ts.tzinfo is None:
|
||||
return ts.replace(tzinfo=UTC)
|
||||
return ts.astimezone(UTC)
|
||||
|
||||
|
||||
def _constraint_error(message: str, params: dict[str, Any]) -> IntegrityError:
|
||||
"""Hand-raised IntegrityError (the guard arms) — the caller's
|
||||
honest 409, never a silent overwrite."""
|
||||
return IntegrityError(message, params, ValueError(message))
|
||||
|
||||
|
||||
def _sqlite_connect(dbapi_connection: sqlite3.Connection, _: object) -> None:
|
||||
"""Per-connection pragmas — mirrors the other D-027 stores."""
|
||||
cursor = dbapi_connection.cursor()
|
||||
cursor.execute("PRAGMA journal_mode=WAL")
|
||||
cursor.execute("PRAGMA synchronous=NORMAL")
|
||||
cursor.execute("PRAGMA busy_timeout=5000")
|
||||
cursor.execute("PRAGMA foreign_keys=ON")
|
||||
cursor.close()
|
||||
|
||||
|
||||
def _check_payload(value: Any) -> None:
|
||||
"""R-69: payload values are str/int/bool/None ONLY — floats (and
|
||||
any nested container) are rejected at the store boundary: float
|
||||
representation is a canonical-serialization drift the chain must
|
||||
never depend on."""
|
||||
if isinstance(value, bool) or value is None:
|
||||
return
|
||||
if isinstance(value, str):
|
||||
return
|
||||
if isinstance(value, int):
|
||||
return
|
||||
raise ValueError(
|
||||
f"payload values must be str/int/bool/None, got {type(value).__name__}"
|
||||
)
|
||||
|
||||
|
||||
class PlacementRow(SQLModel, table=True):
|
||||
"""A placement record (D-102): created by the hired transition,
|
||||
IMMUTABLE except `status` (exactly one transition active → revoked,
|
||||
operator-only by route). role_title/start_date/decided_at and the
|
||||
four ID references are set once and NEVER rewritten — a silent
|
||||
rewrite is exactly the tamper the ledger exists to detect.
|
||||
|
||||
G-316 shape: the partial UNIQUE index uq_active_placement_per_
|
||||
application makes one-ACTIVE-placement-per-application a
|
||||
STRUCTURAL guard — revoked rows stay in history and never match
|
||||
the partial WHERE, so a re-hire after a mistaken revoke creates a
|
||||
fresh row (R-80) and an operator fat-finger never permanently
|
||||
erases a learner from the ≥1,000 count.
|
||||
"""
|
||||
|
||||
__tablename__ = "placement"
|
||||
__table_args__ = (
|
||||
Index(
|
||||
"uq_active_placement_per_application",
|
||||
"application_id",
|
||||
unique=True,
|
||||
sqlite_where=text("status='active'"),
|
||||
),
|
||||
)
|
||||
|
||||
id: str = Field(primary_key=True, sa_type=String)
|
||||
learner_id: str = Field(index=True, sa_type=String)
|
||||
employer_id: str = Field(sa_type=String)
|
||||
#: G-302: ID references resolved from source rows at read/export.
|
||||
posting_id: str = Field(sa_type=String)
|
||||
application_id: str = Field(index=True, sa_type=String)
|
||||
role_title: str = Field(sa_type=String)
|
||||
#: D-103: ISO YYYY-MM-DD — a calendar date, no datetime coercion.
|
||||
start_date: str = Field(sa_type=String)
|
||||
status: str = Field(default="active", sa_type=String)
|
||||
created_at: datetime | None = Field(default=None)
|
||||
#: D-102: the hired transition's store-stamped created_at (G-326:
|
||||
#: the re-hire arm stamps the RE-HIRE event's created_at).
|
||||
decided_at: datetime | None = Field(default=None)
|
||||
|
||||
def _validate(self) -> None:
|
||||
if not self.id:
|
||||
raise ValueError("id must be non-empty")
|
||||
for field_name in (
|
||||
"learner_id",
|
||||
"employer_id",
|
||||
"posting_id",
|
||||
"application_id",
|
||||
"role_title",
|
||||
"start_date",
|
||||
):
|
||||
if not getattr(self, field_name):
|
||||
raise ValueError(f"{field_name} must be non-empty")
|
||||
if self.status not in ("active", "revoked"):
|
||||
raise ValueError(f"invalid placement status {self.status!r}")
|
||||
|
||||
def _normalize(self) -> None:
|
||||
self.created_at = _as_utc(self.created_at) if self.created_at else None
|
||||
self.decided_at = _as_utc(self.decided_at) if self.decided_at else None
|
||||
|
||||
|
||||
class PlacementEventRow(SQLModel, table=True):
|
||||
"""One append-only ledger event (D-101): ONE GLOBAL chain ordered
|
||||
by autoincrement id. Each row stores prev_hash (the prior event's
|
||||
hash; GENESIS_HASH for the first) + its own hash = sha256 over the
|
||||
canonical JSON + prev_hash. UNIQUE(prev_hash) makes a chain fork
|
||||
structurally impossible — two events claiming the same
|
||||
predecessor surface IntegrityError (the G-316 backstop class).
|
||||
|
||||
Application-stage events carry application_id (placement_id
|
||||
None); the placement lane (created/revoked/rehired) carries
|
||||
placement_id set from hired onward.
|
||||
"""
|
||||
|
||||
__tablename__ = "placement_event"
|
||||
|
||||
id: int | None = Field(default=None, primary_key=True)
|
||||
application_id: str | None = Field(default=None, index=True, sa_type=String)
|
||||
placement_id: str | None = Field(default=None, sa_type=String)
|
||||
event_type: str = Field(sa_type=String)
|
||||
actor_type: str = Field(sa_type=String)
|
||||
actor_ref: str = Field(sa_type=String)
|
||||
payload: dict[str, Any] = Field(default_factory=dict, sa_type=JSON)
|
||||
prev_hash: str = Field(unique=True, sa_type=String)
|
||||
hash: str = Field(default="", sa_type=String)
|
||||
created_at: datetime | None = Field(default=None)
|
||||
|
||||
def _validate(self) -> None:
|
||||
if self.id is not None and self.id < 1:
|
||||
raise ValueError("id must be a positive int when set")
|
||||
if not self.event_type:
|
||||
raise ValueError("event_type must be non-empty")
|
||||
if self.actor_type not in ACTOR_TYPES:
|
||||
raise ValueError(f"unknown actor_type {self.actor_type!r}")
|
||||
if not self.actor_ref:
|
||||
raise ValueError("actor_ref must be non-empty")
|
||||
if not self.prev_hash:
|
||||
raise ValueError("prev_hash must be non-empty")
|
||||
for value in self.payload.values():
|
||||
_check_payload(value)
|
||||
|
||||
def _normalize(self) -> None:
|
||||
self.created_at = _as_utc(self.created_at) if self.created_at else None
|
||||
|
||||
def canonical_json(self) -> str:
|
||||
"""D-101/R-79: the canonical serialization — sorted keys,
|
||||
compact separators, created_at ALWAYS `_as_utc(dt).isoformat()`
|
||||
(ONE pinned normalization; the hashing and reading paths share
|
||||
this function so they can never drift)."""
|
||||
return json.dumps(
|
||||
{
|
||||
"id": self.id,
|
||||
"application_id": self.application_id,
|
||||
"placement_id": self.placement_id,
|
||||
"event_type": self.event_type,
|
||||
"actor_type": self.actor_type,
|
||||
"actor_ref": self.actor_ref,
|
||||
"payload": self.payload,
|
||||
"created_at": (
|
||||
_as_utc(self.created_at).isoformat()
|
||||
if self.created_at is not None
|
||||
else None
|
||||
),
|
||||
},
|
||||
sort_keys=True,
|
||||
separators=(",", ":"),
|
||||
)
|
||||
|
||||
|
||||
def _compute_hash(canonical_json: str, prev_hash: str) -> str:
|
||||
"""sha256 over the canonical JSON + prev_hash (D-101 — the D-087
|
||||
stdlib sha256 precedent; hexdigest)."""
|
||||
return hashlib.sha256((canonical_json + prev_hash).encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
class PlacementStore(Protocol):
|
||||
"""Persistence contract for placements (D-101/D-102/D-112)."""
|
||||
|
||||
def create_schema(self) -> None:
|
||||
"""Ensure both tables exist (idempotent — shared DB file)."""
|
||||
...
|
||||
|
||||
def transition_application(
|
||||
self,
|
||||
application_id: str,
|
||||
to_status: str,
|
||||
actor_type: str,
|
||||
actor_ref: str,
|
||||
role_title: str | None = None,
|
||||
start_date: date | None = None,
|
||||
now: datetime | None = None,
|
||||
) -> tuple[ApplicationRow, PlacementRow | None]:
|
||||
"""D-100: the ONE transactional transition — update the
|
||||
marketplace application row + append the ledger event + create
|
||||
the PlacementRow on hired, ALL IN ONE COMMIT. One append per
|
||||
transaction per lane (transition/revoke/rehire each append
|
||||
exactly once); R-70: the appends race nothing — the chain's
|
||||
prev_hash read-then-write is single-threaded-safe through
|
||||
SQLite's writer serialization + the UNIQUE backstop."""
|
||||
...
|
||||
|
||||
def verify_chain(self) -> tuple[bool, str]:
|
||||
"""Recompute the walk from GENESIS_HASH → head; (ok, head_hash)."""
|
||||
...
|
||||
|
||||
def get_placement(self, placement_id: str) -> PlacementRow | None:
|
||||
...
|
||||
|
||||
def get_placement_by_application(
|
||||
self, application_id: str
|
||||
) -> PlacementRow | None:
|
||||
"""v0.11 P5 (REQ-11-005): the learner status read's placement
|
||||
arm — the ACTIVE placement on this application (the G-316
|
||||
partial-unique shape: at most one; revoked-only history →
|
||||
None, the honest null — the events carry the correction)."""
|
||||
...
|
||||
|
||||
def list_placements(self, status: str | None = None) -> list[PlacementRow]:
|
||||
...
|
||||
|
||||
def get_application_events(self, application_id: str) -> list[PlacementEventRow]:
|
||||
...
|
||||
|
||||
def list_events(self) -> list[PlacementEventRow]:
|
||||
...
|
||||
|
||||
def revoke_placement(
|
||||
self, placement_id: str, actor_ref: str, now: datetime | None = None
|
||||
) -> PlacementRow | None:
|
||||
"""D-102: the one status-only mutation active → revoked + the
|
||||
placement.revoked event, one transaction (operator-only by
|
||||
route)."""
|
||||
...
|
||||
|
||||
def rehire_placement(
|
||||
self,
|
||||
application_id: str,
|
||||
role_title: str,
|
||||
start_date: date,
|
||||
actor_ref: str,
|
||||
now: datetime | None = None,
|
||||
) -> PlacementRow:
|
||||
"""R-80/G-326: a FRESH PlacementRow + placement.rehired event
|
||||
WITHOUT touching the application's terminal status — the
|
||||
correction lane. decided_at = the re-hire event's created_at.
|
||||
An existing ACTIVE placement on the application surfaces its
|
||||
IntegrityError (the caller's honest 409)."""
|
||||
...
|
||||
|
||||
def list_placements_by_employer(
|
||||
self, employer_id: str
|
||||
) -> list[PlacementRow]:
|
||||
"""v0.11 P3 (D-109): the claimed entity's OWN placements
|
||||
(active + revoked — the employer sees their full history),
|
||||
created_at then id (the deterministic order)."""
|
||||
...
|
||||
|
||||
def build_export(self, now: datetime | None = None) -> dict[str, Any]:
|
||||
"""v0.11 P4 (D-108/G-321/G-325): the self-contained audit
|
||||
document — {schema_version, generated_at, summary, cohort,
|
||||
evidence_bundles, methodology, ledger} — resolved from SOURCE
|
||||
ROWS at export time (G-302 snapshot-at-export). The summary
|
||||
route renders FROM this dict (one truth source)."""
|
||||
...
|
||||
|
||||
def close(self) -> None:
|
||||
...
|
||||
|
||||
|
||||
class SQLitePlacementStore:
|
||||
"""SQLite implementation of PlacementStore (D-027/D-112)."""
|
||||
|
||||
def __init__(self, db_path: Path | None = None) -> None:
|
||||
self._db_path: Path = db_path if db_path is not None else Settings().db_path
|
||||
self._engine = create_engine(
|
||||
f"sqlite:///{self._db_path}",
|
||||
connect_args={"check_same_thread": False},
|
||||
)
|
||||
event.listen(self._engine, "connect", _sqlite_connect)
|
||||
self.create_schema()
|
||||
|
||||
def create_schema(self) -> None:
|
||||
"""Ensure both tables exist (idempotent — shared DB file)."""
|
||||
SQLModel.metadata.create_all(self._engine)
|
||||
|
||||
# -- chain core (D-101/R-70) -------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def _chain_head(session: Session) -> tuple[int | None, str]:
|
||||
"""(last event id, its hash) or (None, GENESIS_HASH) — the
|
||||
next append's prev_hash source."""
|
||||
row = session.exec(
|
||||
select(PlacementEventRow).order_by(col(PlacementEventRow.id).desc())
|
||||
).first()
|
||||
if row is None or row.hash == "":
|
||||
return None, GENESIS_HASH
|
||||
return row.id, row.hash
|
||||
|
||||
@staticmethod
|
||||
def _append_event(
|
||||
session: Session,
|
||||
*,
|
||||
application_id: str | None,
|
||||
placement_id: str | None,
|
||||
event_type: str,
|
||||
actor_type: str,
|
||||
actor_ref: str,
|
||||
payload: dict[str, Any] | None,
|
||||
prev_hash: str,
|
||||
created_at: datetime,
|
||||
) -> PlacementEventRow:
|
||||
"""R-70: flush-then-hash-then-commit — the row's own
|
||||
autoincrement id participates in its own hash, so the append
|
||||
flushes (id assigned), computes the hash, sets the column, and
|
||||
flushes again. The CALLER owns the transaction (D-100: the
|
||||
status write + the events + the placement land in one commit);
|
||||
this helper never commits."""
|
||||
row = PlacementEventRow(
|
||||
application_id=application_id,
|
||||
placement_id=placement_id,
|
||||
event_type=event_type,
|
||||
actor_type=actor_type,
|
||||
actor_ref=actor_ref,
|
||||
payload=dict(payload or {}),
|
||||
prev_hash=prev_hash,
|
||||
hash="",
|
||||
created_at=created_at,
|
||||
)
|
||||
row._validate()
|
||||
row._normalize()
|
||||
session.add(row)
|
||||
# flush #1: the autoincrement id is assigned
|
||||
session.flush()
|
||||
assert row.id is not None # flush assigns it
|
||||
# the hash covers the canonical JSON + prev_hash
|
||||
row.hash = _compute_hash(row.canonical_json(), row.prev_hash)
|
||||
# flush #2: the hash column lands
|
||||
session.flush()
|
||||
return row
|
||||
|
||||
def verify_chain(self) -> tuple[bool, str]:
|
||||
"""Recompute the walk GENESIS_HASH → head (R-70: O(n) sha256
|
||||
over tiny rows — milliseconds at pilot scale)."""
|
||||
with Session(self._engine) as session:
|
||||
prev = GENESIS_HASH
|
||||
last_hash = GENESIS_HASH
|
||||
rows = session.exec(select(PlacementEventRow).order_by(col(PlacementEventRow.id))).all()
|
||||
for row in rows:
|
||||
row._normalize()
|
||||
expected = _compute_hash(row.canonical_json(), prev)
|
||||
if row.prev_hash != prev or row.hash != expected:
|
||||
return False, last_hash
|
||||
prev = row.hash
|
||||
last_hash = row.hash
|
||||
return True, last_hash
|
||||
|
||||
# -- the ONE transition (D-100) ------------------------------------------
|
||||
|
||||
def transition_application(
|
||||
self,
|
||||
application_id: str,
|
||||
to_status: str,
|
||||
actor_type: str,
|
||||
actor_ref: str,
|
||||
role_title: str | None = None,
|
||||
start_date: date | None = None,
|
||||
now: datetime | None = None,
|
||||
) -> tuple[ApplicationRow, PlacementRow | None]:
|
||||
"""D-100: ONE Session on the placements engine covering BOTH
|
||||
tables + the marketplace application row (the sanctioned
|
||||
cross-family write — R-72: global SQLModel metadata means the
|
||||
placements engine sees ApplicationRow; both stores share the
|
||||
one SQLite file, so one commit covers everything atomically,
|
||||
the decide_claim all-or-nothing precedent).
|
||||
|
||||
R-78: this is the ONLY post-creation writer of
|
||||
application.status — never a second caller.
|
||||
"""
|
||||
moment = _as_utc(now) if now is not None else datetime.now(UTC)
|
||||
with Session(self._engine) as session:
|
||||
application = session.get(ApplicationRow, application_id)
|
||||
if application is None:
|
||||
raise InvalidTransition(f"unknown application {application_id!r}")
|
||||
validate_transition(application.status, to_status)
|
||||
if to_status == "hired":
|
||||
if not role_title:
|
||||
raise ValueError("role_title is required on hire (D-103)")
|
||||
if start_date is None:
|
||||
raise ValueError("start_date is required on hire (D-103)")
|
||||
|
||||
# the status write (the only post-creation writer — R-78);
|
||||
# the pre-transition status is captured BEFORE the mutation
|
||||
from_status = application.status
|
||||
application.status = to_status
|
||||
application._normalize()
|
||||
|
||||
prev_id, prev_hash = self._chain_head(session)
|
||||
payload: dict[str, Any] = {"from_status": from_status, "to_status": to_status}
|
||||
self._append_event(
|
||||
session,
|
||||
application_id=application_id,
|
||||
placement_id=None,
|
||||
event_type=EVENT_APPLICATION_TRANSITION[to_status],
|
||||
actor_type=actor_type,
|
||||
actor_ref=actor_ref,
|
||||
payload=payload,
|
||||
prev_hash=prev_hash,
|
||||
created_at=moment,
|
||||
)
|
||||
|
||||
placement: PlacementRow | None = None
|
||||
if to_status == "hired":
|
||||
assert role_title is not None and start_date is not None
|
||||
placement = PlacementRow(
|
||||
id=f"{_PLACEMENT_ID_PREFIX}{uuid.uuid4().hex[:16]}",
|
||||
learner_id=application.learner_id,
|
||||
employer_id=self._posting_employer_id(session, application.posting_id),
|
||||
posting_id=application.posting_id,
|
||||
application_id=application.id,
|
||||
role_title=role_title,
|
||||
start_date=start_date.isoformat(),
|
||||
status="active",
|
||||
created_at=moment,
|
||||
decided_at=moment,
|
||||
)
|
||||
placement._validate()
|
||||
placement._normalize()
|
||||
session.add(placement)
|
||||
# the placement row must exist before its event references it
|
||||
session.flush()
|
||||
_, prev_hash_2 = self._chain_head(session)
|
||||
self._append_event(
|
||||
session,
|
||||
application_id=application_id,
|
||||
placement_id=placement.id,
|
||||
event_type=EVENT_PLACEMENT_CREATED,
|
||||
actor_type=actor_type,
|
||||
actor_ref=actor_ref,
|
||||
payload={
|
||||
"role_title": role_title,
|
||||
"start_date": start_date.isoformat(),
|
||||
},
|
||||
prev_hash=prev_hash_2,
|
||||
created_at=moment,
|
||||
)
|
||||
|
||||
session.commit()
|
||||
session.refresh(application)
|
||||
application._normalize()
|
||||
if placement is not None:
|
||||
session.refresh(placement)
|
||||
placement._normalize()
|
||||
return application, placement
|
||||
|
||||
@staticmethod
|
||||
def _posting_employer_id(session: Session, posting_id: str) -> str:
|
||||
"""G-302: resolve the posting's employer_id from the SOURCE row
|
||||
at placement-creation time — never trusted from the caller."""
|
||||
from ..marketplace.store import PostingRow
|
||||
|
||||
posting = session.get(PostingRow, posting_id)
|
||||
if posting is None:
|
||||
raise _constraint_error(
|
||||
f"guard: application references unknown posting "
|
||||
f"{posting_id!r} — refusing to create placement",
|
||||
{"posting_id": posting_id},
|
||||
)
|
||||
return posting.employer_id
|
||||
|
||||
# -- reads (consume-free, G-302 ID references) ---------------------------
|
||||
|
||||
def get_placement(self, placement_id: str) -> PlacementRow | None:
|
||||
with Session(self._engine) as session:
|
||||
row = session.get(PlacementRow, placement_id)
|
||||
if row is None:
|
||||
return None
|
||||
row._normalize()
|
||||
return row
|
||||
|
||||
def get_placement_by_application(
|
||||
self, application_id: str
|
||||
) -> PlacementRow | None:
|
||||
"""v0.11 P5 (REQ-11-005): the ACTIVE placement on this
|
||||
application — the G-316 partial unique index makes
|
||||
at-most-one structural; revoked-only history → None (the
|
||||
honest null — never a fabricated placement, A-304)."""
|
||||
with Session(self._engine) as session:
|
||||
row = session.exec(
|
||||
select(PlacementRow).where(
|
||||
PlacementRow.application_id == application_id,
|
||||
PlacementRow.status == "active",
|
||||
)
|
||||
).one_or_none()
|
||||
if row is None:
|
||||
return None
|
||||
row._normalize()
|
||||
return row
|
||||
|
||||
def list_placements(self, status: str | None = None) -> list[PlacementRow]:
|
||||
"""created_at then id (the list_postings ordering discipline,
|
||||
R-73 — deterministic export ordering)."""
|
||||
with Session(self._engine) as session:
|
||||
stmt = select(PlacementRow)
|
||||
if status is not None:
|
||||
stmt = stmt.where(PlacementRow.status == status)
|
||||
rows = session.exec(
|
||||
stmt.order_by(col(PlacementRow.created_at), PlacementRow.id)
|
||||
).all()
|
||||
for row in rows:
|
||||
row._normalize()
|
||||
return list(rows)
|
||||
|
||||
def get_application_events(self, application_id: str) -> list[PlacementEventRow]:
|
||||
"""id-ordered (the chain order) — scoped to ONE application."""
|
||||
with Session(self._engine) as session:
|
||||
rows = session.exec(
|
||||
select(PlacementEventRow)
|
||||
.where(PlacementEventRow.application_id == application_id)
|
||||
.order_by(col(PlacementEventRow.id))
|
||||
).all()
|
||||
for row in rows:
|
||||
row._normalize()
|
||||
return list(rows)
|
||||
|
||||
def list_events(self) -> list[PlacementEventRow]:
|
||||
"""The whole ledger, id-ordered (the export embeds every event
|
||||
so the auditor's walk is offline — R-70)."""
|
||||
with Session(self._engine) as session:
|
||||
rows = session.exec(
|
||||
select(PlacementEventRow).order_by(col(PlacementEventRow.id))
|
||||
).all()
|
||||
for row in rows:
|
||||
row._normalize()
|
||||
return list(rows)
|
||||
|
||||
def count_events(self, event_type: str | None = None) -> int:
|
||||
with Session(self._engine) as session:
|
||||
stmt = select(func.count()).select_from(PlacementEventRow)
|
||||
if event_type is not None:
|
||||
stmt = stmt.where(PlacementEventRow.event_type == event_type)
|
||||
return session.exec(stmt).one()
|
||||
|
||||
# -- the D-102 correction lane ------------------------------------------
|
||||
|
||||
def revoke_placement(
|
||||
self, placement_id: str, actor_ref: str, now: datetime | None = None
|
||||
) -> PlacementRow | None:
|
||||
"""D-102: the one status-only mutation active → revoked + the
|
||||
placement.revoked event, one transaction (operator-only by
|
||||
route). None = unknown placement (route 404s)."""
|
||||
moment = _as_utc(now) if now is not None else datetime.now(UTC)
|
||||
with Session(self._engine) as session:
|
||||
row = session.get(PlacementRow, placement_id)
|
||||
if row is None:
|
||||
return None
|
||||
if row.status != "active":
|
||||
raise InvalidTransition(
|
||||
f"placement {placement_id!r} is {row.status!r} — "
|
||||
"only an active placement can be revoked"
|
||||
)
|
||||
row.status = "revoked"
|
||||
row._validate()
|
||||
row._normalize()
|
||||
_, prev_hash = self._chain_head(session)
|
||||
self._append_event(
|
||||
session,
|
||||
application_id=row.application_id,
|
||||
placement_id=row.id,
|
||||
event_type=EVENT_PLACEMENT_REVOKED,
|
||||
actor_type="operator",
|
||||
actor_ref=actor_ref,
|
||||
payload={"placement_id": placement_id},
|
||||
prev_hash=prev_hash,
|
||||
created_at=moment,
|
||||
)
|
||||
session.commit()
|
||||
session.refresh(row)
|
||||
row._normalize()
|
||||
return row
|
||||
|
||||
def rehire_placement(
|
||||
self,
|
||||
application_id: str,
|
||||
role_title: str,
|
||||
start_date: date,
|
||||
actor_ref: str,
|
||||
now: datetime | None = None,
|
||||
) -> PlacementRow:
|
||||
"""R-80/G-326: the operator re-hire — a FRESH PlacementRow +
|
||||
placement.rehired event WITHOUT touching the application's
|
||||
terminal status (hired → hired is a 409 on every
|
||||
matrix-validated surface; placements, not applications, are
|
||||
the correction lane). decided_at = the re-hire event's
|
||||
store-stamped created_at (G-326 — D-102's stamp rule extended).
|
||||
|
||||
The partial unique index is the guard: an existing ACTIVE
|
||||
placement on the application refuses the insert and its
|
||||
IntegrityError SURFACES (the caller's honest 409 — revoked
|
||||
rows never match the partial WHERE, the exact G-316 property).
|
||||
"""
|
||||
if not role_title:
|
||||
raise ValueError("role_title is required on re-hire (D-103)")
|
||||
if start_date is None:
|
||||
raise ValueError("start_date is required on re-hire (D-103)")
|
||||
moment = _as_utc(now) if now is not None else datetime.now(UTC)
|
||||
with Session(self._engine) as session:
|
||||
application = session.get(ApplicationRow, application_id)
|
||||
if application is None:
|
||||
raise InvalidTransition(f"unknown application {application_id!r}")
|
||||
if application.status != "hired":
|
||||
raise InvalidTransition(
|
||||
f"application {application_id!r} is {application.status!r} — "
|
||||
"re-hire is the correction lane for a hired application"
|
||||
)
|
||||
placement = PlacementRow(
|
||||
id=f"{_PLACEMENT_ID_PREFIX}{uuid.uuid4().hex[:16]}",
|
||||
learner_id=application.learner_id,
|
||||
employer_id=self._posting_employer_id(session, application.posting_id),
|
||||
posting_id=application.posting_id,
|
||||
application_id=application.id,
|
||||
role_title=role_title,
|
||||
start_date=start_date.isoformat(),
|
||||
status="active",
|
||||
created_at=moment,
|
||||
# G-326: the re-hire event's stamp, not the original hire's
|
||||
decided_at=moment,
|
||||
)
|
||||
placement._validate()
|
||||
placement._normalize()
|
||||
session.add(placement)
|
||||
# the partial unique index refuses a second ACTIVE row —
|
||||
# its IntegrityError SURFACES (never swallowed, the
|
||||
# insert_claim discipline)
|
||||
session.flush()
|
||||
_, prev_hash = self._chain_head(session)
|
||||
self._append_event(
|
||||
session,
|
||||
application_id=application.id,
|
||||
placement_id=placement.id,
|
||||
event_type=EVENT_PLACEMENT_REHIRED,
|
||||
actor_type="operator",
|
||||
actor_ref=actor_ref,
|
||||
payload={
|
||||
"role_title": role_title,
|
||||
"start_date": start_date.isoformat(),
|
||||
},
|
||||
prev_hash=prev_hash,
|
||||
created_at=moment,
|
||||
)
|
||||
session.commit()
|
||||
session.refresh(placement)
|
||||
placement._normalize()
|
||||
return placement
|
||||
|
||||
def list_placements_by_employer(
|
||||
self, employer_id: str
|
||||
) -> list[PlacementRow]:
|
||||
"""v0.11 P3 (D-109): the claimed entity's OWN placements
|
||||
(active + revoked — the full history), created_at then id."""
|
||||
with Session(self._engine) as session:
|
||||
rows = session.exec(
|
||||
select(PlacementRow)
|
||||
.where(PlacementRow.employer_id == employer_id)
|
||||
.order_by(col(PlacementRow.created_at), PlacementRow.id)
|
||||
).all()
|
||||
for row in rows:
|
||||
row._normalize()
|
||||
return list(rows)
|
||||
|
||||
# -- the audit export (v0.11 P4, D-108/G-321/G-325/R-73) -----------------
|
||||
|
||||
EXPORT_SCHEMA_VERSION = 1
|
||||
|
||||
def build_export(self, now: datetime | None = None) -> dict[str, Any]:
|
||||
"""D-108: ONE self-contained JSON document via this single
|
||||
builder (the export route AND the summary route render from
|
||||
the SAME dict — the summary can never drift from the export).
|
||||
|
||||
G-325: evidence_bundles cover EVERY placement (active AND
|
||||
revoked) — the correction history (hired → revoked → rehired)
|
||||
is precisely what an auditor most wants to inspect; cohort
|
||||
stays active-only; revoked_count equals the placement.revoked
|
||||
events (cross-checkable, rides the G-321(c) methodology).
|
||||
|
||||
R-73 determinism: events by id (chain order); by_cohort_month
|
||||
ascending; cohort/evidence ordered created_at then id; float
|
||||
absence (counts are ints by construction); generated_at is
|
||||
export-only metadata (a function of the request, not the rows
|
||||
— R-79) and is EXCLUDED from determinism comparison.
|
||||
"""
|
||||
moment = _as_utc(now) if now is not None else datetime.now(UTC)
|
||||
all_placements = self.list_placements() # created_at then id
|
||||
active = [row for row in all_placements if row.status == "active"]
|
||||
revoked = [row for row in all_placements if row.status == "revoked"]
|
||||
events = self.list_events() # id order — the chain order
|
||||
|
||||
# summary (the D-107 computation — one implementation, reused)
|
||||
learner_ids = {row.learner_id for row in active}
|
||||
by_month: dict[str, int] = {}
|
||||
for row in active:
|
||||
month = row.start_date[:7]
|
||||
by_month[month] = by_month.get(month, 0) + 1
|
||||
|
||||
# evidence bundles: G-302 — resolved from SOURCE ROWS at export
|
||||
with Session(self._engine) as session:
|
||||
from ..marketplace.store import ApplicationRow, PostingRow
|
||||
|
||||
evidence_bundles: list[dict[str, Any]] = []
|
||||
cohort: list[dict[str, Any]] = []
|
||||
for row in all_placements:
|
||||
application = session.get(ApplicationRow, row.application_id)
|
||||
posting = session.get(PostingRow, row.posting_id)
|
||||
transition_history = [
|
||||
{
|
||||
"id": event.id,
|
||||
"event_type": event.event_type,
|
||||
"actor_type": event.actor_type,
|
||||
"actor_ref": event.actor_ref,
|
||||
"created_at": (
|
||||
_as_utc(event.created_at).isoformat()
|
||||
if event.created_at is not None
|
||||
else None
|
||||
),
|
||||
}
|
||||
for event in events
|
||||
if event.application_id == row.application_id
|
||||
]
|
||||
hired_at: str | None = None
|
||||
for e in events:
|
||||
if (
|
||||
e.application_id == row.application_id
|
||||
and e.event_type == "application.hired"
|
||||
and e.created_at is not None
|
||||
):
|
||||
hired_at = _as_utc(e.created_at).isoformat()
|
||||
break
|
||||
decision_provenance = {
|
||||
"hired_event": hired_at,
|
||||
"decided_at": (
|
||||
_as_utc(row.decided_at).isoformat()
|
||||
if row.decided_at is not None
|
||||
else None
|
||||
),
|
||||
}
|
||||
bundle: dict[str, Any] = {
|
||||
"placement_id": row.id,
|
||||
"placement_status": row.status,
|
||||
"role_title": row.role_title,
|
||||
"start_date": row.start_date,
|
||||
"learner_id": row.learner_id,
|
||||
"employer_id": row.employer_id,
|
||||
"posting_record": (
|
||||
{
|
||||
"id": posting.id,
|
||||
"title": posting.title,
|
||||
"employer_id": posting.employer_id,
|
||||
"status": posting.status,
|
||||
}
|
||||
if posting is not None
|
||||
else None
|
||||
),
|
||||
"application_record": (
|
||||
{
|
||||
"id": application.id,
|
||||
"learner_id": application.learner_id,
|
||||
"posting_id": application.posting_id,
|
||||
"status": application.status,
|
||||
"created_at": (
|
||||
_as_utc(application.created_at).isoformat()
|
||||
if application.created_at is not None
|
||||
else None
|
||||
),
|
||||
}
|
||||
if application is not None
|
||||
else None
|
||||
),
|
||||
# D-101/A-304: NO backfill — pre-v0.11 submitted rows
|
||||
# carry only their created_at, never a fabricated
|
||||
# application.submitted event
|
||||
"transition_history": transition_history,
|
||||
"decision_provenance": decision_provenance,
|
||||
}
|
||||
evidence_bundles.append(bundle)
|
||||
if row.status == "active":
|
||||
cohort.append(
|
||||
{
|
||||
"placement_id": row.id,
|
||||
"learner_id": row.learner_id,
|
||||
"employer_id": row.employer_id,
|
||||
"posting_id": row.posting_id,
|
||||
"application_id": row.application_id,
|
||||
"role_title": row.role_title,
|
||||
"start_date": row.start_date,
|
||||
}
|
||||
)
|
||||
|
||||
ok, head_hash = self.verify_chain()
|
||||
if not ok:
|
||||
# P4 review P2-1: a raise (not an assert — stripped under
|
||||
# python -O) keeps the export FAIL-CLOSED on a broken
|
||||
# chain: no document is ever served that would not walk.
|
||||
raise RuntimeError(
|
||||
"placement ledger chain verification failed — "
|
||||
"refusing to build the audit export"
|
||||
)
|
||||
|
||||
return {
|
||||
"schema_version": self.EXPORT_SCHEMA_VERSION,
|
||||
"generated_at": moment.isoformat(),
|
||||
"summary": {
|
||||
"distinct_learners_placed": len(learner_ids),
|
||||
"total_active_placements": len(active),
|
||||
"revoked_count": len(revoked),
|
||||
"by_cohort_month": [
|
||||
{"month": month, "count": count}
|
||||
for month, count in sorted(by_month.items())
|
||||
],
|
||||
},
|
||||
"cohort": cohort,
|
||||
"evidence_bundles": evidence_bundles,
|
||||
"methodology": EXPORT_METHODOLOGY,
|
||||
"ledger": {
|
||||
"events": [
|
||||
{
|
||||
"id": event.id,
|
||||
"application_id": event.application_id,
|
||||
"placement_id": event.placement_id,
|
||||
"event_type": event.event_type,
|
||||
"actor_type": event.actor_type,
|
||||
"actor_ref": event.actor_ref,
|
||||
"payload": event.payload,
|
||||
"created_at": (
|
||||
_as_utc(event.created_at).isoformat()
|
||||
if event.created_at is not None
|
||||
else None
|
||||
),
|
||||
"prev_hash": event.prev_hash,
|
||||
"hash": event.hash,
|
||||
}
|
||||
for event in events
|
||||
],
|
||||
"head_hash": head_hash,
|
||||
},
|
||||
}
|
||||
|
||||
def close(self) -> None:
|
||||
self._engine.dispose()
|
||||
@@ -0,0 +1,86 @@
|
||||
"""Sandbox capability probe — the honest degrade truth source (D-068, v0.8).
|
||||
|
||||
Runtime promotion of the test-tier userns probe (``tests/helpers/userns.py``
|
||||
mechanism, verbatim): a REAL ``unshare --user --map-root-user`` attempt is
|
||||
the truth source for whether the namespace fabric can provision learner
|
||||
environments on this host. Container detection (``/.dockerenv`` or the
|
||||
``NC_CONTAINER`` marker the image sets) is belt-and-suspenders context for
|
||||
the remediation text — the degrade decision itself is ALWAYS the probe,
|
||||
never a guess from the marker (a privileged container with working userns
|
||||
must NOT report degraded).
|
||||
|
||||
The single remediation constant (G-208) is shared by the boot notice
|
||||
(``main.py`` lifespan) and the 503 arm (``api/sandboxes.py``) so the two
|
||||
surfaces can never drift.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import shutil
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
#: Remediation text (G-208): names the unprivileged default, the seccomp
|
||||
#: constraint, the privileged variant with exact flags, and the host-side
|
||||
#: alternative. One constant — boot notice and 503 payload import it, so
|
||||
#: they cannot drift apart.
|
||||
DEGRADE_REMEDIATION = (
|
||||
"learner sandbox builds are unavailable on this host: the namespace "
|
||||
"fabric needs unprivileged user namespaces and the capability probe "
|
||||
"failed. The nextcraft container runs unprivileged by default and "
|
||||
"docker's default seccomp profile denies the nested `unshare --user` "
|
||||
"the fabric requires. Options: (1) run the image with "
|
||||
"`--security-opt seccomp=unconfined` (and `--security-opt "
|
||||
"apparmor=unconfined` where apparmor applies) on a host that allows "
|
||||
"unprivileged userns; or (2) run the stack binary-side on the host "
|
||||
"(`nextcraft deploy --service`) where the fabric works natively. "
|
||||
"Everything else in this deployment is unaffected."
|
||||
)
|
||||
|
||||
_probe_result: bool | None = None
|
||||
|
||||
|
||||
def userns_available() -> bool:
|
||||
"""True only if `unshare` exists AND `--user --map-root-user` works here.
|
||||
|
||||
The result is cached per process (the probe spawns a subprocess; one
|
||||
answer per boot is the contract — the boot notice and every 503 read
|
||||
the same truth).
|
||||
"""
|
||||
global _probe_result
|
||||
if _probe_result is None:
|
||||
_probe_result = _probe()
|
||||
return _probe_result
|
||||
|
||||
|
||||
def _probe() -> bool:
|
||||
if shutil.which("unshare") is None:
|
||||
return False
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["unshare", "--user", "--map-root-user", "true"],
|
||||
capture_output=True,
|
||||
timeout=10,
|
||||
)
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
return False
|
||||
return result.returncode == 0
|
||||
|
||||
|
||||
def container_detected() -> bool:
|
||||
"""Context marker (not the degrade truth): /.dockerenv or NC_CONTAINER.
|
||||
|
||||
Used by the boot notice to tailor the message and by the CLI's
|
||||
container-mode branches. A privileged container with working userns
|
||||
is NOT degraded — the probe alone decides that.
|
||||
"""
|
||||
if Path("/.dockerenv").exists():
|
||||
return True
|
||||
import os
|
||||
|
||||
return os.environ.get("NC_CONTAINER") == "1"
|
||||
|
||||
|
||||
def sandbox_fabric_degraded() -> bool:
|
||||
"""The degrade decision: the probe fails. Marker never overrides it."""
|
||||
return not userns_available()
|
||||
@@ -38,6 +38,7 @@ BOUNDARY: this module NEVER imports `api/` or `agents/`.
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import builtins
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
@@ -281,7 +282,7 @@ class SandboxManager:
|
||||
|
||||
# -- reapers ------------------------------------------------------------
|
||||
|
||||
async def reap_expired(self) -> list[str]:
|
||||
async def reap_expired(self) -> builtins.list[str]:
|
||||
"""One reaper pass: wall-clock timeout + G-2 workdir-size sweep.
|
||||
|
||||
Destroys sandboxes older than `settings.sandbox_timeout_s`, then sweeps
|
||||
@@ -290,9 +291,14 @@ class SandboxManager:
|
||||
signal). Returns the ids destroyed this pass. Invoke on an async timer
|
||||
(the app lifespan owns the loop interval); both checks deliberately
|
||||
share one pass so the periodic work is O(live sandboxes) once.
|
||||
|
||||
P5: the return annotation is `builtins.list` because this class's
|
||||
own `list()` method shadows the `list[...]` subscript form in
|
||||
annotations below it (a mypy scoping quirk — the method name is
|
||||
public API and stays).
|
||||
"""
|
||||
now = self._clock()
|
||||
destroyed: list[str] = []
|
||||
destroyed: builtins.list[str] = []
|
||||
timeout_s = float(self._settings.sandbox_timeout_s)
|
||||
cap_bytes = int(self._settings.sandbox_max_workdir_mb) * 1024 * 1024
|
||||
|
||||
|
||||
@@ -21,7 +21,7 @@ Boundary (D-027): telemetry/ never imports agents/ or api/.
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any, Literal
|
||||
from typing import Any, Literal, get_args
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
from sqlalchemy import JSON, Index, String
|
||||
@@ -38,7 +38,9 @@ EventKind = Literal[
|
||||
"stdin",
|
||||
"stdout",
|
||||
]
|
||||
_EVENT_KINDS: frozenset[str] = frozenset(EventKind.__args__)
|
||||
# P5: get_args() is the typed accessor for Literal values (bare __args__
|
||||
# trips mypy on the typing special form).
|
||||
_EVENT_KINDS: frozenset[str] = frozenset(get_args(EventKind))
|
||||
|
||||
|
||||
class TelemetryEvent(SQLModel, table=True):
|
||||
|
||||
@@ -28,7 +28,7 @@ from pathlib import Path
|
||||
from typing import Any, Protocol
|
||||
|
||||
import sqlalchemy as sa
|
||||
from sqlmodel import Session, SQLModel, create_engine, select
|
||||
from sqlmodel import Session, SQLModel, col, create_engine, select
|
||||
|
||||
from ..config import Settings
|
||||
from .models import TelemetryEvent
|
||||
@@ -151,7 +151,9 @@ class SQLiteTraceStore:
|
||||
select(TelemetryEvent)
|
||||
.where(TelemetryEvent.learner_id == learner_id)
|
||||
.where(TelemetryEvent.task_id == task_id)
|
||||
.order_by(TelemetryEvent.seq)
|
||||
# P5: col() — SQLModel class attrs are Mapped[T], the
|
||||
# column reference rides col() in order_by/func.count.
|
||||
.order_by(col(TelemetryEvent.seq))
|
||||
)
|
||||
results = session.exec(stmt).all()
|
||||
# Detach from the session: callers must not depend on open-session
|
||||
@@ -167,7 +169,7 @@ class SQLiteTraceStore:
|
||||
select(TelemetryEvent.seq)
|
||||
.where(TelemetryEvent.learner_id == learner_id)
|
||||
.where(TelemetryEvent.task_id == task_id)
|
||||
.order_by(TelemetryEvent.seq)
|
||||
.order_by(col(TelemetryEvent.seq))
|
||||
)
|
||||
# sqlmodel scalar select: rows are plain ints, not 1-tuples.
|
||||
return [int(seq) for seq in session.exec(stmt).all()]
|
||||
@@ -196,7 +198,7 @@ class SQLiteTraceStore:
|
||||
# docstring-free body keeps it obvious what the query shape is.
|
||||
with self._session() as session:
|
||||
stmt = (
|
||||
select(sa.func.count(TelemetryEvent.seq))
|
||||
select(sa.func.count(col(TelemetryEvent.seq)))
|
||||
.where(TelemetryEvent.learner_id == learner_id)
|
||||
.where(TelemetryEvent.task_id == task_id)
|
||||
)
|
||||
|
||||
@@ -43,7 +43,7 @@ from typing import Any, Protocol
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy import JSON, Index, String, UniqueConstraint
|
||||
from sqlalchemy.orm import validates
|
||||
from sqlmodel import Field, Session, SQLModel, create_engine, select
|
||||
from sqlmodel import Field, Session, SQLModel, col, create_engine, select
|
||||
|
||||
from ..config import Settings
|
||||
|
||||
@@ -325,7 +325,9 @@ class SQLiteVariantStore:
|
||||
.where(VariantRecord.learner_id == learner_id)
|
||||
# Chronological; task_id is a deterministic tie-break for
|
||||
# variants stamped within the same instant.
|
||||
.order_by(VariantRecord.created_at, VariantRecord.task_id)
|
||||
# P5: col() — SQLModel class attrs are Mapped[T], the
|
||||
# column reference rides col() in order_by.
|
||||
.order_by(col(VariantRecord.created_at), VariantRecord.task_id)
|
||||
)
|
||||
results = session.exec(stmt).all()
|
||||
for row in results:
|
||||
@@ -339,7 +341,7 @@ class SQLiteVariantStore:
|
||||
select(VariantRecord)
|
||||
.where(VariantRecord.template_id == template_id)
|
||||
# Chronological; learner_id is a deterministic tie-break.
|
||||
.order_by(VariantRecord.created_at, VariantRecord.learner_id)
|
||||
.order_by(col(VariantRecord.created_at), VariantRecord.learner_id)
|
||||
)
|
||||
results = session.exec(stmt).all()
|
||||
for row in results:
|
||||
|
||||
@@ -63,22 +63,24 @@ from collections.abc import Iterator
|
||||
from contextlib import contextmanager
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
from typing import Any, Literal, Protocol
|
||||
from typing import Any, Literal, Protocol, get_args
|
||||
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy import JSON, Index, String
|
||||
from sqlalchemy.orm import validates
|
||||
from sqlmodel import Field, Session, SQLModel, create_engine, select
|
||||
from sqlmodel import Field, Session, SQLModel, col, create_engine, select
|
||||
|
||||
from ..config import Settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
DefenseStatus = Literal["in_progress", "finished"]
|
||||
_DEFENSE_STATUSES: frozenset[str] = frozenset(DefenseStatus.__args__)
|
||||
# P5: get_args() is the typed accessor for Literal values (bare __args__
|
||||
# trips mypy on the typing special form).
|
||||
_DEFENSE_STATUSES: frozenset[str] = frozenset(get_args(DefenseStatus))
|
||||
|
||||
TurnRole = Literal["examiner", "learner"]
|
||||
_TURN_ROLES: frozenset[str] = frozenset(TurnRole.__args__)
|
||||
_TURN_ROLES: frozenset[str] = frozenset(get_args(TurnRole))
|
||||
|
||||
|
||||
class DefenseRecord(SQLModel, table=True):
|
||||
@@ -464,7 +466,9 @@ class SQLiteDefenseStore:
|
||||
stmt = (
|
||||
select(DefenseTurn)
|
||||
.where(DefenseTurn.defense_id == defense_id)
|
||||
.order_by(DefenseTurn.seq)
|
||||
# P5: col() — SQLModel class attrs are Mapped[T], the
|
||||
# column reference rides col() in order_by.
|
||||
.order_by(col(DefenseTurn.seq))
|
||||
)
|
||||
turns = session.exec(stmt).all()
|
||||
for turn in turns:
|
||||
@@ -489,7 +493,7 @@ class SQLiteDefenseStore:
|
||||
.where(DefenseRecord.learner_id == learner_id)
|
||||
# Chronological; id is a deterministic tie-break for
|
||||
# defenses stamped within the same instant.
|
||||
.order_by(DefenseRecord.created_at, DefenseRecord.id)
|
||||
.order_by(col(DefenseRecord.created_at), DefenseRecord.id)
|
||||
)
|
||||
results = session.exec(stmt).all()
|
||||
for row in results:
|
||||
|
||||
@@ -11,12 +11,14 @@ descriptor then honestly reports mode='mock' so the UI badge cannot lie.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import cast
|
||||
|
||||
import httpx
|
||||
|
||||
from ..config import Settings
|
||||
from .base import VoiceProvider
|
||||
from .mock import MockVoiceProvider
|
||||
from .openai_audio import OpenAIAudioProvider
|
||||
from .openai_audio import OpenAIAudioProvider, TtsFormat
|
||||
|
||||
|
||||
class UnknownVoiceProviderError(ValueError):
|
||||
@@ -60,7 +62,10 @@ def voice_provider_from_settings(
|
||||
stt_model=settings.voice_stt_model,
|
||||
tts_model=settings.voice_tts_model,
|
||||
tts_voice=settings.voice_tts_voice,
|
||||
tts_format=settings.voice_tts_format,
|
||||
# P5: Settings.voice_tts_format is str, but its pydantic
|
||||
# validator normalizes to exactly mp3|wav|opus (invalid → mp3
|
||||
# with a warning) — the cast states that provenance.
|
||||
tts_format=cast(TtsFormat, settings.voice_tts_format),
|
||||
)
|
||||
raise UnknownVoiceProviderError(
|
||||
f"unknown AI_VOICE_PROVIDER {name!r}: use 'mock', 'browser', or 'openai-audio'"
|
||||
|
||||
@@ -14,7 +14,7 @@ import struct
|
||||
import wave
|
||||
from collections.abc import AsyncIterator
|
||||
|
||||
from .base import TranscriptSegment
|
||||
from .base import TranscriptSegment, VoiceProvider
|
||||
|
||||
|
||||
def _tone_wav(duration_ms: int = 250, freq_hz: float = 1000.0) -> bytes:
|
||||
@@ -73,7 +73,7 @@ class MockVoiceProvider:
|
||||
duration_ms=max(1, len(audio) // 32), # deterministic pseudo-duration
|
||||
)
|
||||
|
||||
async def synthesize(self, text: str, voice: str = "default") -> AsyncIterator[bytes]: # noqa: ASYNC109 (protocol parity)
|
||||
async def synthesize(self, text: str, voice: str = "default") -> AsyncIterator[bytes]:
|
||||
# NOTE: protocol parity matters more than the async-generator purity
|
||||
# lint; the real provider (openai_audio.py) streams over HTTP.
|
||||
self.synthesize_calls += 1
|
||||
@@ -86,7 +86,6 @@ class MockVoiceProvider:
|
||||
|
||||
|
||||
# Protocol-shape parity guard (mock must satisfy the D-030 port).
|
||||
from .base import VoiceProvider # noqa: E402
|
||||
|
||||
|
||||
def _assert_protocol() -> None:
|
||||
|
||||
@@ -19,6 +19,10 @@ import httpx
|
||||
|
||||
from .base import TranscriptSegment, VoiceDescriptor
|
||||
|
||||
#: TTS response formats the OpenAI audio endpoint accepts (P5: named so
|
||||
#: the factory can type-honestly pass the config-normalized value through).
|
||||
TtsFormat = Literal["mp3", "wav", "opus"]
|
||||
|
||||
|
||||
class OpenAIAudioProvider:
|
||||
"""Server STT (`/audio/transcriptions`) + TTS (`/audio/speech`)."""
|
||||
@@ -31,7 +35,7 @@ class OpenAIAudioProvider:
|
||||
stt_model: str = "whisper-1",
|
||||
tts_model: str = "tts-1",
|
||||
tts_voice: str = "alloy",
|
||||
tts_format: Literal["mp3", "wav", "opus"] = "mp3",
|
||||
tts_format: TtsFormat = "mp3",
|
||||
) -> None:
|
||||
self._client = http_client
|
||||
self._base_url = base_url.rstrip("/")
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
{
|
||||
"name": "@nextcraft/ai-service",
|
||||
"private": true,
|
||||
"version": "0.2.0",
|
||||
"version": "0.6.5",
|
||||
"scripts": {
|
||||
"dev": "bash scripts/dev.sh",
|
||||
"test": "bash scripts/test.sh",
|
||||
"bootstrap": "bash scripts/bootstrap.sh",
|
||||
"lint": "bash scripts/lint.sh"
|
||||
"lint": "bash scripts/lint.sh",
|
||||
"typecheck": "bash scripts/typecheck.sh"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "nextcraft-ai-service"
|
||||
version = "0.2.0"
|
||||
version = "0.6.5"
|
||||
description = "Nextcraft AI tutor service — six LLM agents behind a provider-agnostic layer"
|
||||
requires-python = ">=3.11"
|
||||
dependencies = [
|
||||
@@ -14,20 +14,32 @@ dependencies = [
|
||||
"pydantic-settings>=2.15,<2.16",
|
||||
"httpx>=0.28,<0.29",
|
||||
"sse-starlette>=3.4,<3.5",
|
||||
"sqlmodel>=0.0.24,<0.1",
|
||||
"sqlmodel>=0.0.24,<0.0.43",
|
||||
# ^ P1 CI finding: sqlmodel 0.0.43+ (up to 0.0.47 resolved in fresh CI
|
||||
# venvs) tightens Literal-arg inference on pydantic models — 15 mypy
|
||||
# arg-type errors surface (DefenseRecord/TelemetryEvent/DefenseTurn).
|
||||
# The v0.7-shipped line was 0.0.42; cap below .43 until the Literal
|
||||
# annotations are tightened deliberately (per-module overrides later).
|
||||
"sqlalchemy>=2.0,<2.1",
|
||||
"websockets>=13,<16",
|
||||
"aiofiles>=24.1,<26",
|
||||
# POST /v1/defense/{id}/answer multipart audio (REQ-3-006): FastAPI
|
||||
# form/File parsing requires python-multipart at runtime.
|
||||
"python-multipart>=0.0.32,<0.1",
|
||||
# P4-B resume parse (REQ-6-005, D-054, A-410): PDF text extraction.
|
||||
# Pure-Python, probe-verified 6.19.0 — the ONLY new v0.6 dependency.
|
||||
"pypdf>=6.19,<7",
|
||||
]
|
||||
|
||||
[project.optional-dependencies]
|
||||
dev = [
|
||||
"pytest>=9.1,<10",
|
||||
"pytest-asyncio>=1.4,<2",
|
||||
"pytest-cov>=7.1,<8",
|
||||
"pytest-timeout>=2.4,<3",
|
||||
"ruff>=0.14",
|
||||
# P5 type hardening (D-058): mypy relaxed-first baseline. Resolved 2.3.1.
|
||||
"mypy>=2.3,<2.4",
|
||||
]
|
||||
|
||||
[tool.setuptools.packages.find]
|
||||
@@ -35,13 +47,105 @@ include = ["ai_service*"]
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
asyncio_mode = "auto"
|
||||
# D-056: pin the fixture loop scope — pytest-asyncio 1.4 warns at configure
|
||||
# time when this is unset and a future default flip would change loop reuse
|
||||
# for async fixtures. "function" is the current-effective default semantics.
|
||||
asyncio_default_fixture_loop_scope = "function"
|
||||
testpaths = ["tests"]
|
||||
# P1 harness wiring (D-053/D-054): strict markers + a 60s global timeout.
|
||||
# `timeout` also ships its own marker (`pytest.mark.timeout`); the 180s
|
||||
# override for real_server/userns tests is applied by the collection hook
|
||||
# in tests/conftest.py — marker-level values beat this global default.
|
||||
markers = [
|
||||
"fast: in-process unit test (default tier — unmarked tests are fast)",
|
||||
"real_server: spins a real uvicorn server process",
|
||||
"userns: enters a real unshare user namespace",
|
||||
]
|
||||
addopts = "--strict-markers --timeout=60 --timeout-method=signal"
|
||||
# P3 zero-warning policy (D-056): base action `error` — every warning fails
|
||||
# the run; new first-party warnings can never pass silently. The ONLY
|
||||
# entries after "error" are the 2 known upstream import-time deprecations,
|
||||
# each scoped by exact message prefix + emitting module (the module whose
|
||||
# import triggers the warning, i.e. the frame the warning is attributed to
|
||||
# after stacklevel adjustment — NOT the package the warning text mentions):
|
||||
#
|
||||
# 1. fastapi.testclient re-exports starlette's TestClient, and importing
|
||||
# it emits starlette's httpx→httpx2 migration warning (stacklevel=2
|
||||
# attributes it to fastapi/testclient.py's import line).
|
||||
# 2. starlette.testclient resolves `anyio.abc.BlockingPortal` in a
|
||||
# module-level type alias; anyio's lazy-import __getattr__ emits the
|
||||
# alias-deprecation (stacklevel=3 attributes it to starlette's
|
||||
# testclient.py).
|
||||
#
|
||||
# G-104 invariant: category-scoped ignores and ANY ignore matching
|
||||
# ai_service.* are forbidden forever; new upstream deprecations may join
|
||||
# this list only as module+message-scoped entries, justified in ship notes.
|
||||
# Fields: action:message-regex:category:module-regex:lineno (pytest parses
|
||||
# ini entries as raw regex — dots below are explicitly escaped).
|
||||
filterwarnings = [
|
||||
"error",
|
||||
# Upstream (1/2): starlette 1.6 httpx→httpx2 migration notice, raised
|
||||
# while importing fastapi.testclient (importer frame is fastapi's).
|
||||
"ignore:Using `httpx` with `starlette\\.testclient` is deprecated:starlette.exceptions.StarletteDeprecationWarning:fastapi\\.testclient",
|
||||
# Upstream (2/2): anyio 4.x lazy-import alias deprecation, raised while
|
||||
# starlette.testclient evaluates its `_PortalFactoryType` alias.
|
||||
"ignore:The anyio\\.abc\\.BlockingPortal alias is deprecated:DeprecationWarning:starlette\\.testclient",
|
||||
]
|
||||
|
||||
[tool.coverage.run]
|
||||
source = ["ai_service"] # tests/ excluded by construction — only the package is measured
|
||||
branch = true
|
||||
|
||||
[tool.coverage.report]
|
||||
# exclude_also APPENDS to coverage.py's built-ins (which already cover
|
||||
# `pragma: no cover` and `if TYPE_CHECKING:`); these add the __main__
|
||||
# entry-point guard (none in ai_service today — future-proof).
|
||||
exclude_also = [
|
||||
"if __name__ == [\"']__main__[\"']:",
|
||||
"if TYPE_CHECKING:",
|
||||
"pragma: no cover",
|
||||
]
|
||||
|
||||
[tool.ruff]
|
||||
line-length = 100
|
||||
target-version = "py311"
|
||||
|
||||
[tool.ruff.lint]
|
||||
select = ["E", "F", "W", "I", "UP", "B"]
|
||||
select = ["E", "F", "W", "I", "UP", "B", "RUF100"]
|
||||
# B008: Depends() in argument defaults is the idiomatic FastAPI DI pattern
|
||||
ignore = ["B008"]
|
||||
ignore = ["B008"]
|
||||
|
||||
# P5 mypy relaxed-first baseline (D-058) — NOT full strict. The flags
|
||||
# below are the binding set from the decision; per-module tightening via
|
||||
# [[tool.mypy.overrides]] is available later (the plan's Wave-5 follow-up
|
||||
# form). Scope decision (recorded per the task's pragmatic clause): ALL
|
||||
# THREE trees pass — ai_service/ + scripts/sandbox-agent.py + tests/ —
|
||||
# so tests are NOT excluded; every test violation was either fixed at
|
||||
# source or scoped with a coded ignore + reason inline. Tests remain
|
||||
# fully checked; a future tests.* per-module relaxation override stays
|
||||
# available (D-058) if the annotation burden grows.
|
||||
[tool.mypy]
|
||||
python_version = "3.11"
|
||||
files = [
|
||||
"ai_service",
|
||||
"scripts/sandbox-agent.py",
|
||||
"tests",
|
||||
]
|
||||
# Untracked runtime droppings under tests/ (gitignored via
|
||||
# `apps/ai-service/**/sandboxes/`) must never be type-checked.
|
||||
exclude = ["tests/sandboxes"]
|
||||
# D-058 relaxed-first baseline:
|
||||
check_untyped_defs = true # real bugs hide in unannotated bodies too
|
||||
no_implicit_optional = true # implicit Optional is a genuine bug class
|
||||
warn_unused_ignores = true # stale `# type: ignore` becomes an error (self-eliminating suppressions)
|
||||
warn_redundant_casts = true
|
||||
warn_unreachable = true
|
||||
warn_unused_configs = true
|
||||
# Start strict on imports: every runtime dep checked code imports ships
|
||||
# stubs (verified py.typed: fastapi/uvicorn/pydantic/pydantic-settings/
|
||||
# httpx/sse-starlette/sqlmodel/sqlalchemy/websockets/python-multipart/
|
||||
# pypdf/pytest/pytest-asyncio; aiofiles + pytest-timeout/pytest-cov are
|
||||
# never imported by checked code). Overrides are reserved for deps that
|
||||
# genuinely lack stubs — currently NONE, so no ignore_missing_imports
|
||||
# overrides are listed; warn_unused_configs would flag any added no-op.
|
||||
ignore_missing_imports = false
|
||||
|
||||
@@ -72,4 +72,4 @@ fi
|
||||
|
||||
"$VENV/bin/pip" install --quiet --upgrade pip
|
||||
"$VENV/bin/pip" install --quiet -e "$APP_DIR[dev]"
|
||||
echo "bootstrap complete: $VENV"
|
||||
echo "bootstrap complete: $VENV"
|
||||
|
||||
@@ -37,4 +37,4 @@ HOST="${AI_HOST:-0.0.0.0}"
|
||||
PORT="${AI_PORT:-8420}"
|
||||
|
||||
cd "$APP_DIR"
|
||||
exec "$VENV/bin/uvicorn" ai_service.main:app --reload --host "$HOST" --port "$PORT"
|
||||
exec "$VENV/bin/uvicorn" ai_service.main:app --reload --host "$HOST" --port "$PORT"
|
||||
|
||||
@@ -11,4 +11,4 @@ if [ ! -x "$VENV/bin/ruff" ]; then
|
||||
fi
|
||||
|
||||
cd "$APP_DIR"
|
||||
exec "$VENV/bin/ruff" check .
|
||||
exec "$VENV/bin/ruff" check .
|
||||
|
||||
@@ -209,21 +209,36 @@ class WsConnection:
|
||||
path += "?" + parts.query
|
||||
|
||||
sock = socket.create_connection((host, port), timeout=timeout_s)
|
||||
if parts.scheme == "wss":
|
||||
sock = ssl.create_default_context().wrap_socket(sock, server_hostname=host)
|
||||
try:
|
||||
if parts.scheme == "wss":
|
||||
sock = ssl.create_default_context().wrap_socket(
|
||||
sock, server_hostname=host
|
||||
)
|
||||
|
||||
key = base64.b64encode(secrets.token_bytes(16)).decode("ascii")
|
||||
request = (
|
||||
f"GET {path} HTTP/1.1\r\n"
|
||||
f"Host: {host}:{port}\r\n"
|
||||
"Upgrade: websocket\r\n"
|
||||
"Connection: Upgrade\r\n"
|
||||
f"Sec-WebSocket-Key: {key}\r\n"
|
||||
"Sec-WebSocket-Version: 13\r\n\r\n"
|
||||
)
|
||||
sock.sendall(request.encode("ascii"))
|
||||
response = cls._read_http_response(sock)
|
||||
cls._validate_handshake(response, key)
|
||||
key = base64.b64encode(secrets.token_bytes(16)).decode("ascii")
|
||||
request = (
|
||||
f"GET {path} HTTP/1.1\r\n"
|
||||
f"Host: {host}:{port}\r\n"
|
||||
"Upgrade: websocket\r\n"
|
||||
"Connection: Upgrade\r\n"
|
||||
f"Sec-WebSocket-Key: {key}\r\n"
|
||||
"Sec-WebSocket-Version: 13\r\n\r\n"
|
||||
)
|
||||
sock.sendall(request.encode("ascii"))
|
||||
response = cls._read_http_response(sock)
|
||||
cls._validate_handshake(response, key)
|
||||
except BaseException:
|
||||
# P3 (Task 3-2-02): a failed connect after the TCP dial leaves
|
||||
# the raw socket with no WsConnection owner — the supervisor's
|
||||
# except block re-raised before one existed, so every failed
|
||||
# reconnect leaked the fd (unclosed-socket ResourceWarnings;
|
||||
# fd exhaustion over a long outage). Close it HERE and re-raise
|
||||
# the same exception: the backoff/reconnect logic is unchanged.
|
||||
try:
|
||||
sock.close()
|
||||
except OSError:
|
||||
pass
|
||||
raise
|
||||
return cls(sock)
|
||||
|
||||
@staticmethod
|
||||
@@ -550,6 +565,10 @@ class Agent:
|
||||
"""Maintain the WS connection: connect, flush backlog, read, backoff."""
|
||||
backoff = self.config.backoff_base_s
|
||||
while not self._stop.is_set():
|
||||
# P5: explicit Optional — the else-branch read can observe None
|
||||
# (a concurrent _drop_conn between the check and the read), so
|
||||
# the `conn is None` guard below is genuinely reachable.
|
||||
conn: WsConnection | None
|
||||
if self._current_conn() is None:
|
||||
try:
|
||||
conn = WsConnection.connect(self.config.ingest_url)
|
||||
@@ -780,18 +799,18 @@ def main() -> int:
|
||||
# activity until SIGTERM/SIGINT so the agent's lifecycle is tied to
|
||||
# the sandbox (destroy() reaps it) rather than to stdin EOF.
|
||||
if sys.stdin is None or sys.stdin.closed: # pragma: no cover - defensive
|
||||
agent._stop.wait() # noqa: SLF001 - daemon block
|
||||
agent._stop.wait()
|
||||
else:
|
||||
line = sys.stdin.readline()
|
||||
while line:
|
||||
agent.run_command(line)
|
||||
line = sys.stdin.readline()
|
||||
if not agent._stop.is_set() and not sys.stdin.isatty(): # noqa: SLF001
|
||||
if not agent._stop.is_set() and not sys.stdin.isatty():
|
||||
# EOF on a pipe (DEVNULL): daemonize — watch + stream until killed.
|
||||
import signal
|
||||
|
||||
signal.signal(signal.SIGTERM, lambda *_: agent._stop.set()) # noqa: SLF001
|
||||
agent._stop.wait() # noqa: SLF001
|
||||
signal.signal(signal.SIGTERM, lambda *_: agent._stop.set())
|
||||
agent._stop.wait()
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
finally:
|
||||
|
||||
@@ -1,5 +1,12 @@
|
||||
#!/usr/bin/env bash
|
||||
# Test runner: pytest via venv — mock provider only, zero network calls.
|
||||
#
|
||||
# P1 harness wiring (Task 1-1-01/1-1-02):
|
||||
# default full suite WITH coverage (term + missing lines)
|
||||
# NO_COV=1 coverage off (bare pytest flags, no --cov args)
|
||||
# FAST=1 fast subset only: -m "not real_server and not userns"
|
||||
#
|
||||
# Extra args pass through: `bash scripts/test.sh tests/api -k foo`.
|
||||
set -euo pipefail
|
||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||
APP_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
|
||||
@@ -11,4 +18,21 @@ if [ ! -x "$VENV/bin/pytest" ]; then
|
||||
fi
|
||||
|
||||
cd "$APP_DIR"
|
||||
exec "$VENV/bin/pytest" -q "$@"
|
||||
|
||||
# Assemble args; pytest arg order: later options win, so user-passed "$@"
|
||||
# always overrides the wiring below.
|
||||
ARGS=("-q")
|
||||
if [ "${FAST:-0}" = "1" ]; then
|
||||
# Fast subset: exclude the real-server and user-namespace tiers.
|
||||
# The fast loop is the dev loop — coverage evidence comes from the full run.
|
||||
ARGS+=("-m" "not real_server and not userns")
|
||||
NO_COV=1
|
||||
fi
|
||||
if [ "${NO_COV:-0}" = "1" ]; then
|
||||
# Opt-out: bare run, no coverage tooling at all.
|
||||
ARGS+=()
|
||||
else
|
||||
ARGS+=("--cov=ai_service" "--cov-report=term-missing")
|
||||
fi
|
||||
|
||||
exec "$VENV/bin/pytest" "${ARGS[@]}" "$@"
|
||||
|
||||
Executable
+19
@@ -0,0 +1,19 @@
|
||||
#!/usr/bin/env bash
|
||||
# Type check: mypy via venv — the D-058 relaxed-first baseline
|
||||
# (check_untyped_defs, no_implicit_optional, warn_unused_ignores,
|
||||
# warn_redundant_casts, warn_unreachable; config in pyproject.toml
|
||||
# [tool.mypy], scope = ai_service + scripts/sandbox-agent.py + tests).
|
||||
#
|
||||
# Extra args pass through: `bash scripts/typecheck.sh --verbose`.
|
||||
set -euo pipefail
|
||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||
APP_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
|
||||
VENV="$APP_DIR/.venv"
|
||||
|
||||
if [ ! -x "$VENV/bin/mypy" ]; then
|
||||
echo "venv missing mypy — run scripts/bootstrap.sh (or pip install the dev extras) first" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
cd "$APP_DIR"
|
||||
exec "$VENV/bin/mypy" "$@"
|
||||
@@ -1,7 +1,11 @@
|
||||
"""Telemetry + artifacts corpus tests (REQ-2-007/008 inputs, D-021)."""
|
||||
"""Telemetry + artifacts corpus tests (REQ-2-007/008 inputs).
|
||||
|
||||
The D-021 TS↔py ID-sync pin (test_corpus_ids_align_with_ts_mock_data) was
|
||||
cut in P4 Wave 4-2: its counterpart packages/mock-data/ai-scenarios.ts was
|
||||
dead (zero imports) and removed as dead code, so the sync contract it
|
||||
guarded no longer exists. The Python corpus here is the single source.
|
||||
"""
|
||||
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -15,7 +19,6 @@ from ai_service.corpus.artifacts import (
|
||||
rubric_for_competency,
|
||||
)
|
||||
from ai_service.corpus.telemetry import (
|
||||
LAB_SCENARIOS,
|
||||
get_lab_scenario,
|
||||
summarize_scenario,
|
||||
)
|
||||
@@ -35,15 +38,22 @@ def test_lab_scenarios_addressable_by_id():
|
||||
def test_lab_scenarios_have_distinct_event_profiles():
|
||||
strong = get_lab_scenario("lab-scenario-strong")
|
||||
struggling = get_lab_scenario("lab-scenario-struggling")
|
||||
kinds = lambda s: {e.kind for e in s.events} # noqa: E731
|
||||
flagged = get_lab_scenario("lab-scenario-flagged")
|
||||
assert strong is not None, "seed scenario must resolve"
|
||||
assert struggling is not None, "seed scenario must resolve"
|
||||
assert flagged is not None, "seed scenario must resolve"
|
||||
def kinds(s):
|
||||
return {e.kind for e in s.events}
|
||||
assert "test_pass" in kinds(strong)
|
||||
assert "test_fail" in kinds(struggling)
|
||||
assert "idle" in kinds(struggling)
|
||||
assert "paste" in kinds(get_lab_scenario("lab-scenario-flagged"))
|
||||
assert "paste" in kinds(flagged)
|
||||
|
||||
|
||||
def test_summarize_scenario_mentions_events():
|
||||
text = summarize_scenario(get_lab_scenario("lab-scenario-struggling"))
|
||||
scenario = get_lab_scenario("lab-scenario-struggling")
|
||||
assert scenario is not None, "seed scenario must resolve"
|
||||
text = summarize_scenario(scenario)
|
||||
assert "test_fail" in text
|
||||
assert "ImportError" in text
|
||||
assert "stack-orchestration-c002" in text
|
||||
@@ -76,6 +86,7 @@ def test_transcripts_pair_with_artifacts():
|
||||
|
||||
def test_rubric_render_mentions_all_criteria():
|
||||
rubric = rubric_for_competency("stack-orchestration-c002")
|
||||
assert rubric is not None, "seed rubric must resolve"
|
||||
text = render_rubric(rubric)
|
||||
for criterion in rubric.criteria:
|
||||
assert criterion.criterion_id in text
|
||||
@@ -83,38 +94,12 @@ def test_rubric_render_mentions_all_criteria():
|
||||
|
||||
def test_transcript_render_has_both_speakers():
|
||||
transcript = get_transcript_for_artifact("art-eval-rag-dashboard")
|
||||
assert transcript is not None, "seed transcript must resolve"
|
||||
text = render_transcript(transcript)
|
||||
assert "examiner:" in text
|
||||
assert "learner:" in text
|
||||
|
||||
|
||||
_TS_SOURCE_CANDIDATES = [
|
||||
Path(__file__).resolve().parents[4] / "packages" / "mock-data" / "ai-scenarios.ts",
|
||||
Path(__file__).resolve().parents[2] / "ai-scenarios.ts",
|
||||
]
|
||||
|
||||
|
||||
def _ts_source() -> Path:
|
||||
for candidate in _TS_SOURCE_CANDIDATES:
|
||||
if candidate.exists():
|
||||
return candidate
|
||||
pytest.skip("ai-scenarios.ts not found in this checkout layout")
|
||||
|
||||
|
||||
def test_corpus_ids_align_with_ts_mock_data():
|
||||
"""D-021: Python corpus IDs string-identical to ai-scenarios.ts."""
|
||||
content = _ts_source().read_text()
|
||||
ts_ids = re.findall(r"id:\s*'([^']+)'", content)
|
||||
ts_scenarios = ts_ids[: len(LAB_SCENARIOS)]
|
||||
ts_artifacts = ts_ids[len(LAB_SCENARIOS):]
|
||||
assert sorted(ts_scenarios) == sorted(LAB_SCENARIOS), (
|
||||
f"scenario IDs drifted: py={sorted(LAB_SCENARIOS)} ts={sorted(ts_scenarios)}"
|
||||
)
|
||||
assert sorted(ts_artifacts) == sorted(ARTIFACTS), (
|
||||
f"artifact IDs drifted: py={sorted(ARTIFACTS)} ts={sorted(ts_artifacts)}"
|
||||
)
|
||||
|
||||
|
||||
def test_rubric_weights_sum_to_one():
|
||||
"""Every rubric's criteria weights must sum to exactly 1.0."""
|
||||
for rubric in RUBRICS.values():
|
||||
|
||||
@@ -25,9 +25,13 @@ async def test_stream_feedback_mentions_scenario_events():
|
||||
ctx = get_learner_context()
|
||||
strong = get_lab_scenario("lab-scenario-strong")
|
||||
struggling = get_lab_scenario("lab-scenario-struggling")
|
||||
assert strong is not None, "seed scenario must resolve"
|
||||
assert struggling is not None, "seed scenario must resolve"
|
||||
|
||||
strong_reply = "".join([t async for t in lab.stream_feedback(strong, ctx)])
|
||||
struggling_reply = "".join([t async for t in lab.stream_feedback(struggling, ctx)])
|
||||
# P5 scoped: corpus scenario stands in for the TraceDigest (dormant-
|
||||
# corpus test seam — render_digest_timeline duck-types model_dump_json).
|
||||
strong_reply = "".join([t async for t in lab.stream_feedback(strong, ctx)]) # type: ignore[arg-type]
|
||||
struggling_reply = "".join([t async for t in lab.stream_feedback(struggling, ctx)]) # type: ignore[arg-type]
|
||||
assert strong_reply
|
||||
assert strong_reply != struggling_reply # scenario-driven, not canned
|
||||
|
||||
@@ -35,6 +39,7 @@ async def test_stream_feedback_mentions_scenario_events():
|
||||
def test_build_evaluation_messages_carry_timeline():
|
||||
lab = make_lab()
|
||||
scenario = get_lab_scenario("lab-scenario-flagged")
|
||||
assert scenario is not None, "seed scenario must resolve"
|
||||
timeline = summarize_scenario(scenario)
|
||||
messages = lab.build_messages(None, timeline, get_learner_context())
|
||||
assert messages[0].role == "system"
|
||||
|
||||
@@ -34,7 +34,8 @@ def test_proctor_scenarios_addressable_and_distinct_type():
|
||||
healthy = get_proctor_scenario("proctor-scenario-healthy")
|
||||
flagged = get_proctor_scenario("proctor-scenario-flagged")
|
||||
assert healthy is not None and flagged is not None
|
||||
kinds = lambda s: {e.kind for e in s.events} # noqa: E731
|
||||
def kinds(s):
|
||||
return {e.kind for e in s.events}
|
||||
assert "tab_switch" in kinds(get_proctor_scenario("proctor-scenario-distracted"))
|
||||
assert "paste_large" in kinds(flagged)
|
||||
assert not kinds(healthy) & {"tab_switch", "paste_large", "focus_lost"}
|
||||
@@ -48,7 +49,13 @@ async def test_assess_returns_validated_signals():
|
||||
provider = ScriptedJSONProvider(VALID_ASSESSMENT)
|
||||
proctor = make_proctor(provider)
|
||||
scenario = get_proctor_scenario("proctor-scenario-distracted")
|
||||
result = await proctor.assess(scenario, get_learner_context())
|
||||
assert scenario is not None, "seed scenario must resolve"
|
||||
# P5 scoped: corpus scenario stands in for the TraceDigest (dormant-
|
||||
# corpus test seam — the agent renders digest.model_dump_json).
|
||||
result = await proctor.assess(
|
||||
scenario, # type: ignore[arg-type]
|
||||
learner_context=get_learner_context(),
|
||||
)
|
||||
assert isinstance(result, ProctorAssessment)
|
||||
assert len(result.signals) == 2
|
||||
assert result.signals[0].severity == "low"
|
||||
@@ -58,8 +65,13 @@ async def test_assess_returns_validated_signals():
|
||||
async def test_assess_rejects_invalid_after_retry():
|
||||
proctor = make_proctor(MockProvider()) # non-schema JSON
|
||||
scenario = get_proctor_scenario("proctor-scenario-healthy")
|
||||
assert scenario is not None, "seed scenario must resolve"
|
||||
with pytest.raises(StructuredOutputError):
|
||||
await proctor.assess(scenario, get_learner_context())
|
||||
# P5 scoped: corpus scenario as digest — same dormant-corpus seam.
|
||||
await proctor.assess(
|
||||
scenario, # type: ignore[arg-type]
|
||||
learner_context=get_learner_context(),
|
||||
)
|
||||
|
||||
|
||||
def test_system_prompt_is_coaching_not_punitive():
|
||||
@@ -71,6 +83,7 @@ def test_system_prompt_is_coaching_not_punitive():
|
||||
|
||||
def test_timeline_summary_carries_events():
|
||||
scenario = get_proctor_scenario("proctor-scenario-flagged")
|
||||
assert scenario is not None, "seed scenario must resolve"
|
||||
text = summarize_proctor_scenario(scenario)
|
||||
assert "paste_large" in text
|
||||
assert "3,100 chars" in text
|
||||
|
||||
@@ -187,7 +187,10 @@ class TestProctorEndpoint:
|
||||
from ai_service.variants.store import SQLiteVariantStore
|
||||
from ai_service.voice.defense_store import SQLiteDefenseStore
|
||||
|
||||
app = create_app(Settings(provider="mock"))
|
||||
# P1 CI finding: bare Settings() defaults db_path to ~/.nextcraft —
|
||||
# hermeticity rule violated (CI job containers have no ~/.nextcraft;
|
||||
# sqlite fails "unable to open database file"). Pin all state to tmp.
|
||||
app = create_app(Settings(provider="mock", db_path=tmp_path / "app.db"))
|
||||
provider = RecordingProvider(PROCTOR_JSON)
|
||||
app.state.provider = provider
|
||||
app.state.trace_store = SQLiteTraceStore(db_path=tmp_path / "t.db")
|
||||
|
||||
@@ -14,7 +14,9 @@ async def test_create_and_get():
|
||||
store = InMemorySessionStore()
|
||||
session = await store.create("s1", agent="coach")
|
||||
assert session.agent == "coach"
|
||||
assert (await store.get("s1")).session_id == "s1"
|
||||
got = await store.get("s1")
|
||||
assert got is not None
|
||||
assert got.session_id == "s1"
|
||||
assert await store.get("missing") is None
|
||||
|
||||
|
||||
|
||||
@@ -69,7 +69,8 @@ async def test_structured_completion_retries_then_raises():
|
||||
# Plain MockProvider returns non-schema JSON for json_object requests →
|
||||
# both attempts fail validation → StructuredOutputError after ONE retry.
|
||||
provider = MockProvider()
|
||||
provider.received_calls = []
|
||||
# P5 scoped: test-only call ledger attribute on the shared mock.
|
||||
provider.received_calls = [] # type: ignore[attr-defined]
|
||||
messages = [Message(role="user", content="grade me")]
|
||||
with pytest.raises(StructuredOutputError):
|
||||
await structured_completion(
|
||||
@@ -141,7 +142,7 @@ async def test_structured_completion_sends_schema_instruction():
|
||||
messages, model=model, temperature=temperature, response_format=response_format
|
||||
)
|
||||
|
||||
provider.chat = recording_chat
|
||||
provider.chat = recording_chat # type: ignore[method-assign] # P5: monkeypatching the shared mock
|
||||
messages = [Message(role="user", content="grade")]
|
||||
await structured_completion(provider, messages, model="m", schema=Score, schema_hint=HINT)
|
||||
assert captured, "provider was never called"
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from collections.abc import Iterator
|
||||
from datetime import UTC, datetime
|
||||
|
||||
import pytest
|
||||
@@ -33,8 +34,8 @@ class CoachingMock(MockProvider):
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def client(tmp_path) -> TestClient:
|
||||
app = create_app(Settings(provider="mock"))
|
||||
def client(tmp_path) -> Iterator[TestClient]:
|
||||
app = create_app(Settings(provider="mock", db_path=tmp_path / "app.db"))
|
||||
app.state.provider = CoachingMock()
|
||||
app.state.trace_store = SQLiteTraceStore(db_path=tmp_path / "t.db")
|
||||
app.state.grade_store = SQLiteGradeStore(db_path=tmp_path / "g.db")
|
||||
@@ -45,8 +46,10 @@ def client(tmp_path) -> TestClient:
|
||||
|
||||
def _seed_grade(client: TestClient) -> None:
|
||||
|
||||
# P5: TestClient.app is typed ASGIApp (Callable); at runtime it is the
|
||||
# FastAPI instance — this state-injection seam is the suite's pattern.
|
||||
app = client.app
|
||||
store: SQLiteGradeStore = app.state.grade_store
|
||||
store: SQLiteGradeStore = app.state.grade_store # type: ignore[attr-defined]
|
||||
store.save(
|
||||
GradeRecord(
|
||||
learner_id="api-learner",
|
||||
|
||||
@@ -80,3 +80,25 @@ def test_credentials_never_allowed(client: TestClient) -> None:
|
||||
},
|
||||
)
|
||||
assert resp.headers.get("access-control-allow-credentials") != "true"
|
||||
|
||||
|
||||
def test_preflight_allows_authorization_header(
|
||||
client: TestClient,
|
||||
) -> None:
|
||||
"""v0.10 (D-090, E87 lesson): the employer session surface sends
|
||||
`Authorization: Bearer <token>` — the preflight grant must carry
|
||||
the header or every cross-origin employer fetch dies preflight in
|
||||
the two-port dev + D-038 network-mode topologies."""
|
||||
resp = client.options(
|
||||
"/v1/employers/auth/login",
|
||||
headers={
|
||||
"Origin": ALLOWED_ORIGIN,
|
||||
"Access-Control-Request-Method": "POST",
|
||||
"Access-Control-Request-Headers": "Authorization, Content-Type",
|
||||
},
|
||||
)
|
||||
assert resp.status_code == 200, f"preflight failed: {resp.status_code}"
|
||||
allowed = resp.headers["access-control-allow-headers"]
|
||||
assert "authorization" in allowed.lower(), (
|
||||
f"Authorization missing from CORS headers: {allowed}"
|
||||
)
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from collections.abc import Iterator
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
@@ -56,6 +57,7 @@ def app(tmp_path: Path):
|
||||
provider="mock",
|
||||
voice_provider="mock",
|
||||
learner_allowlist=SUITE_LEARNERS,
|
||||
db_path=tmp_path / "app.db", # hermeticity (P1 CI finding)
|
||||
)
|
||||
application = create_app(settings)
|
||||
identity_store = SQLiteIdentityStore(db_path=tmp_path / "identity.db")
|
||||
@@ -77,7 +79,7 @@ def app(tmp_path: Path):
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def client(app) -> TestClient:
|
||||
def client(app) -> Iterator[TestClient]:
|
||||
with TestClient(app) as c:
|
||||
yield c
|
||||
|
||||
@@ -134,6 +136,7 @@ class TestBrowserFallback:
|
||||
provider="mock",
|
||||
voice_provider="browser",
|
||||
learner_allowlist=SUITE_LEARNERS,
|
||||
db_path=tmp_path / "app-b.db", # hermeticity (P1 CI finding)
|
||||
)
|
||||
)
|
||||
identity_store = SQLiteIdentityStore(db_path=tmp_path / "identity-b.db")
|
||||
|
||||
@@ -12,14 +12,11 @@ Probe-guarded for user namespaces (the in-sandbox exec needs them).
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import contextlib
|
||||
import json
|
||||
import socket
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
import uvicorn
|
||||
|
||||
from ai_service.config import Settings
|
||||
from ai_service.grading.store import SQLiteGradeStore
|
||||
@@ -29,7 +26,12 @@ from ai_service.telemetry.ingest import TraceIntegrityMap
|
||||
from ai_service.telemetry.store import SQLiteTraceStore
|
||||
from ai_service.variants.store import SQLiteVariantStore
|
||||
from ai_service.voice.defense_store import SQLiteDefenseStore
|
||||
from tests.sandbox.test_isolation import USERSNS_AVAILABLE
|
||||
from tests.helpers import free_port, serve, skip_if_no_userns
|
||||
|
||||
# P1 tier marker (Task 1-1-02): this suite boots a REAL uvicorn server
|
||||
# (uvicorn.Server + serve loop, below) — real_server tier, 180s timeout
|
||||
# via the conftest collection hook.
|
||||
pytestmark = [pytest.mark.real_server]
|
||||
|
||||
COACHING_JSON = json.dumps(
|
||||
{
|
||||
@@ -97,20 +99,13 @@ class FlowLLM(MockProvider):
|
||||
return "Walk me through your last fix — what changed and why?"
|
||||
|
||||
|
||||
def _free_port() -> int:
|
||||
with socket.socket() as s:
|
||||
s.bind(("127.0.0.1", 0))
|
||||
return s.getsockname()[1]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_full_credential_flow(tmp_path: Path) -> None:
|
||||
if not USERSNS_AVAILABLE:
|
||||
pytest.skip("user namespaces unavailable on this host (probe)")
|
||||
skip_if_no_userns()
|
||||
|
||||
import httpx
|
||||
|
||||
port = _free_port()
|
||||
port = free_port()
|
||||
from ai_service.identity.store import SQLiteIdentityStore
|
||||
from tests.conftest import SUITE_LEARNERS, seed_verified_identity
|
||||
|
||||
@@ -131,15 +126,7 @@ async def test_full_credential_flow(tmp_path: Path) -> None:
|
||||
app.state.defense_store = SQLiteDefenseStore(db_path=tmp_path / "d.db")
|
||||
app.state.trace_integrity = TraceIntegrityMap()
|
||||
|
||||
server = uvicorn.Server(uvicorn.Config(app, host="127.0.0.1", port=port, log_level="warning"))
|
||||
serve_task = asyncio.get_running_loop().create_task(server.serve())
|
||||
try:
|
||||
for _ in range(100):
|
||||
if server.started:
|
||||
break
|
||||
await asyncio.sleep(0.1)
|
||||
assert server.started
|
||||
|
||||
async with serve(app, "127.0.0.1", port):
|
||||
base = f"http://127.0.0.1:{port}"
|
||||
async with httpx.AsyncClient(base_url=base, timeout=30.0) as client:
|
||||
# 1. Variant (real seeded generation, mock-rendered).
|
||||
@@ -221,7 +208,3 @@ async def test_full_credential_flow(tmp_path: Path) -> None:
|
||||
assert not any(
|
||||
m in json.dumps(payload) for m in corpus_markers
|
||||
), "corpus fixture leaked into the learner path"
|
||||
finally:
|
||||
server.should_exit = True
|
||||
with contextlib.suppress(Exception):
|
||||
await asyncio.wait_for(serve_task, timeout=10.0)
|
||||
|
||||
@@ -7,6 +7,7 @@ scenarios; empty trace is a valid "no telemetry yet" coaching path.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterator
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
@@ -44,8 +45,8 @@ class StreamingMock(MockProvider):
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def client(tmp_path: Path) -> TestClient:
|
||||
app = create_app(Settings(provider="mock"))
|
||||
def client(tmp_path: Path) -> Iterator[TestClient]:
|
||||
app = create_app(Settings(provider="mock", db_path=tmp_path / "app.db"))
|
||||
app.state.provider = StreamingMock()
|
||||
app.state.trace_store = SQLiteTraceStore(db_path=tmp_path / "t.db")
|
||||
app.state.grade_store = SQLiteGradeStore(db_path=tmp_path / "g.db")
|
||||
@@ -55,7 +56,7 @@ def client(tmp_path: Path) -> TestClient:
|
||||
|
||||
|
||||
def test_live_trace_streams_full_envelope(client: TestClient) -> None:
|
||||
store: SQLiteTraceStore = client.app.state.trace_store
|
||||
store: SQLiteTraceStore = client.app.state.trace_store # type: ignore[attr-defined] # P5: TestClient.app is typed ASGIApp; runtime FastAPI
|
||||
for e in [
|
||||
_event(0, "file_diff", {"path": "x.py"}, 0),
|
||||
_event(1, "command", {"cmd": "pytest -q"}, 10),
|
||||
|
||||
@@ -7,6 +7,7 @@ and gathers digest + defense signals + variant context server-side.
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from collections.abc import Iterator
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
@@ -49,8 +50,8 @@ class BrokenJSON(MockProvider):
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def client(tmp_path: Path) -> TestClient:
|
||||
app = create_app(Settings(provider="mock"))
|
||||
def client(tmp_path: Path) -> Iterator[TestClient]:
|
||||
app = create_app(Settings(provider="mock", db_path=tmp_path / "app.db"))
|
||||
app.state.trace_store = SQLiteTraceStore(db_path=tmp_path / "t.db")
|
||||
app.state.grade_store = SQLiteGradeStore(db_path=tmp_path / "g.db")
|
||||
app.state.variant_store = SQLiteVariantStore(db_path=tmp_path / "v.db")
|
||||
@@ -61,7 +62,7 @@ def client(tmp_path: Path) -> TestClient:
|
||||
|
||||
|
||||
def _seed_trace(client: TestClient) -> None:
|
||||
store: SQLiteTraceStore = client.app.state.trace_store
|
||||
store: SQLiteTraceStore = client.app.state.trace_store # type: ignore[attr-defined] # P5: TestClient.app is typed ASGIApp; runtime FastAPI
|
||||
for e in [
|
||||
TelemetryEvent(
|
||||
learner_id="p-learner",
|
||||
@@ -86,7 +87,7 @@ def _seed_trace(client: TestClient) -> None:
|
||||
|
||||
|
||||
def test_signals_returns_validated_json(client: TestClient) -> None:
|
||||
client.app.state.provider = ProctorJSON()
|
||||
client.app.state.provider = ProctorJSON() # type: ignore[attr-defined] # P5: TestClient.app is typed ASGIApp; runtime FastAPI
|
||||
_seed_trace(client)
|
||||
resp = client.post(
|
||||
"/v1/proctor/signals", json={"learner_id": "p-learner", "task_id": "p-task"}
|
||||
@@ -99,7 +100,7 @@ def test_signals_returns_validated_json(client: TestClient) -> None:
|
||||
|
||||
def test_empty_trace_is_valid_not_404(client: TestClient) -> None:
|
||||
"""No telemetry → the proctor still assesses (nothing to flag)."""
|
||||
client.app.state.provider = ProctorJSON()
|
||||
client.app.state.provider = ProctorJSON() # type: ignore[attr-defined] # P5: TestClient.app is typed ASGIApp; runtime FastAPI
|
||||
resp = client.post(
|
||||
"/v1/proctor/signals", json={"learner_id": "nobody", "task_id": "nothing"}
|
||||
)
|
||||
@@ -107,7 +108,7 @@ def test_empty_trace_is_valid_not_404(client: TestClient) -> None:
|
||||
|
||||
|
||||
def test_unparseable_provider_502(client: TestClient) -> None:
|
||||
client.app.state.provider = BrokenJSON()
|
||||
client.app.state.provider = BrokenJSON() # type: ignore[attr-defined] # P5: TestClient.app is typed ASGIApp; runtime FastAPI
|
||||
_seed_trace(client)
|
||||
resp = client.post(
|
||||
"/v1/proctor/signals", json={"learner_id": "p-learner", "task_id": "p-task"}
|
||||
@@ -116,6 +117,6 @@ def test_unparseable_provider_502(client: TestClient) -> None:
|
||||
|
||||
|
||||
def test_missing_fields_422(client: TestClient) -> None:
|
||||
client.app.state.provider = ProctorJSON()
|
||||
client.app.state.provider = ProctorJSON() # type: ignore[attr-defined] # P5: TestClient.app is typed ASGIApp; runtime FastAPI
|
||||
resp = client.post("/v1/proctor/signals", json={"learner_id": "x"})
|
||||
assert resp.status_code == 422
|
||||
|
||||
@@ -64,8 +64,13 @@ class StubBackend:
|
||||
"""Structural SandboxBackend: lays out the workdir, spawns nothing.
|
||||
|
||||
Tracks spawn/destroy calls so lifespan shutdown behaviour is assertable.
|
||||
`structural = True` exempts it from the v0.8 degrade guard (D-068): the
|
||||
stub fabric never touches userns, so it must stay usable inside
|
||||
unprivileged CI job containers (D-063 fast lane).
|
||||
"""
|
||||
|
||||
structural = True
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.spawned_specs: list[SandboxSpec] = []
|
||||
self.destroyed_ids: list[str] = []
|
||||
|
||||
@@ -22,12 +22,19 @@ Covered:
|
||||
- reconnect after flood still cannot append (flag is terminal)
|
||||
- unknown trace GET → 404 (traces + gaps)
|
||||
- missing identity query params → handshake rejected
|
||||
|
||||
P2 (Task 2-1-04, deterministic waits): the old ``_drain()`` helper slept a
|
||||
fixed 50 ms "to give the portal a beat" after sending frames. That was never
|
||||
the synchronization — every read below is a BLOCKING portal receive, and the
|
||||
app's status frames travel a strictly-ordered unbounded memory stream, so a
|
||||
blocking ``ws.receive()`` returns each frame the moment the app produces it
|
||||
(the sibling ack/ping tests in this file never slept). The sleep added
|
||||
latency, not determinism; it is gone and the reads are the event-driven wait.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import time
|
||||
from collections.abc import Iterator
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
@@ -46,6 +53,12 @@ LEARNER = "learner-9"
|
||||
TASK = "task-9"
|
||||
_BASE_TS = datetime(2026, 9, 11, 12, 0, 0, tzinfo=UTC)
|
||||
|
||||
# P1 tier marker (Task 1-1-02): the queue-overflow leak-regression test
|
||||
# boots a REAL uvicorn server (TestClient teardown would hide the leak) —
|
||||
# real_server tier, 180s timeout via the conftest collection hook.
|
||||
# The rest of the suite is in-process TestClient-only.
|
||||
pytestmark = [pytest.mark.real_server]
|
||||
|
||||
KNOWN_KINDS = ("command", "file_diff", "run_result", "test_result", "activity")
|
||||
|
||||
#: Shared test token — minted into every test URL, verified by the endpoint
|
||||
@@ -65,17 +78,6 @@ def _frame(seq: int, kind: str = "command", sandbox_id: str = "") -> str:
|
||||
)
|
||||
|
||||
|
||||
def _drain(ws) -> None:
|
||||
"""Give the portal a beat to deliver queued frames.
|
||||
|
||||
Starlette's TestClient runs the app on a portal thread; frames produced in
|
||||
the app loop still need a portal round-trip to reach the test thread. A
|
||||
real (tiny) sleep flushes them deterministically without hardcoding
|
||||
protocol timing.
|
||||
"""
|
||||
time.sleep(0.05)
|
||||
|
||||
|
||||
def _recv_status(ws) -> dict:
|
||||
"""Next JSON status frame, skipping keepalive pings; re-raise close.
|
||||
|
||||
@@ -230,8 +232,7 @@ def test_skip_to_seq_5_reports_gap_warning_and_gaps_endpoint(
|
||||
for seq in (0, 1, 2):
|
||||
ws.send_text(_frame(seq))
|
||||
ws.send_text(_frame(5)) # skips 3,4 → gap_warning frame
|
||||
_drain(ws)
|
||||
frames = [_recv_status(ws)]
|
||||
frames = [_recv_status(ws)] # blocking receive = the event-driven wait
|
||||
assert frames == [{"type": "gap_warning", "missing_seqs": [3, 4]}]
|
||||
|
||||
gaps = client.get(f"/v1/telemetry/gaps/{LEARNER}/{TASK}")
|
||||
@@ -250,7 +251,8 @@ def test_burst_past_cap_closes_1008_and_marks_incomplete_flooded(
|
||||
with client.websocket_connect(_ingest_url()) as ws:
|
||||
for seq in range(6):
|
||||
ws.send_text(_frame(seq))
|
||||
_drain(ws) # let the app flush the flooded frame + 1008 close
|
||||
# No settle sleep needed: the read loop below blocks until the app
|
||||
# delivers the flooded frame and the 1008 close (P2 Task 2-1-04).
|
||||
frames: list[dict] = []
|
||||
with pytest.raises(WebSocketDisconnect) as excinfo:
|
||||
while True:
|
||||
@@ -281,7 +283,6 @@ def test_queue_overflow_also_floods(
|
||||
with client.websocket_connect(_ingest_url(learner_id="L-q", task_id="T-q")) as ws:
|
||||
for seq in range(64): # receiver out-drains the drainer with bound=1
|
||||
ws.send_text(_frame(seq))
|
||||
_drain(ws)
|
||||
with pytest.raises(WebSocketDisconnect) as excinfo:
|
||||
while True:
|
||||
_recv_status(ws)
|
||||
@@ -301,14 +302,11 @@ async def test_queue_overflow_flood_session_task_terminates(tmp_path, monkeypatc
|
||||
stopped after the flood; the session tasks must be gone shortly after.
|
||||
"""
|
||||
import asyncio
|
||||
import contextlib
|
||||
import socket as socket_mod
|
||||
|
||||
import uvicorn
|
||||
import websockets
|
||||
|
||||
from ai_service.main import create_app
|
||||
from ai_service.telemetry.ingest import TraceIntegrityMap
|
||||
from ai_service.telemetry.store import SQLiteTraceStore
|
||||
from tests.helpers import free_port, serve
|
||||
|
||||
monkeypatch.setattr(ingest_mod, "INBOUND_QUEUE_MAX", 1)
|
||||
store = SQLiteTraceStore(db_path=tmp_path / "leak.db")
|
||||
@@ -324,56 +322,40 @@ async def test_queue_overflow_flood_session_task_terminates(tmp_path, monkeypatc
|
||||
# v0.4.7: real-server dial needs a token the endpoint accepts
|
||||
app.state.ingest_token = TEST_TOKEN
|
||||
|
||||
with socket_mod.socket() as s:
|
||||
s.bind(("127.0.0.1", 0))
|
||||
port = s.getsockname()[1]
|
||||
server = uvicorn.Server(
|
||||
uvicorn.Config(app, host="127.0.0.1", port=port, log_level="warning")
|
||||
)
|
||||
serve_task = asyncio.get_running_loop().create_task(server.serve())
|
||||
port = free_port()
|
||||
leaked = True
|
||||
try:
|
||||
for _ in range(100):
|
||||
if server.started:
|
||||
break
|
||||
await asyncio.sleep(0.1)
|
||||
assert server.started
|
||||
async with serve(app, "127.0.0.1", port):
|
||||
uri = (
|
||||
f"ws://127.0.0.1:{port}/v1/telemetry/ingest"
|
||||
f"?learner_id=L-leak&task_id=T-leak"
|
||||
f"&token={TEST_TOKEN.mint('L-leak', 'T-leak', '')}"
|
||||
)
|
||||
async with websockets.connect(uri) as ws:
|
||||
for seq in range(64): # bound=1 → guaranteed overflow
|
||||
await ws.send(_frame(seq, sandbox_id=""))
|
||||
# The flood close (1008) reaches the client.
|
||||
try:
|
||||
await asyncio.wait_for(ws.recv(), timeout=10.0)
|
||||
await asyncio.wait_for(ws.recv(), timeout=10.0)
|
||||
except (websockets.exceptions.ConnectionClosed, TimeoutError, OSError):
|
||||
pass
|
||||
assert app.state.trace_integrity.is_incomplete("L-leak", "T-leak")
|
||||
|
||||
import websockets
|
||||
|
||||
uri = (
|
||||
f"ws://127.0.0.1:{port}/v1/telemetry/ingest"
|
||||
f"?learner_id=L-leak&task_id=T-leak"
|
||||
f"&token={TEST_TOKEN.mint('L-leak', 'T-leak', '')}"
|
||||
)
|
||||
async with websockets.connect(uri) as ws:
|
||||
for seq in range(64): # bound=1 → guaranteed overflow
|
||||
await ws.send(_frame(seq, sandbox_id=""))
|
||||
# The flood close (1008) reaches the client.
|
||||
try:
|
||||
await asyncio.wait_for(ws.recv(), timeout=10.0)
|
||||
await asyncio.wait_for(ws.recv(), timeout=10.0)
|
||||
except (websockets.exceptions.ConnectionClosed, TimeoutError, OSError):
|
||||
pass
|
||||
assert app.state.trace_integrity.is_incomplete("L-leak", "T-leak")
|
||||
|
||||
# The session's run() must have returned: no lingering nc-* tasks
|
||||
# holding the socket open. Poll briefly — teardown is async.
|
||||
deadline = asyncio.get_running_loop().time() + 5.0
|
||||
while asyncio.get_running_loop().time() < deadline:
|
||||
names = {
|
||||
t.get_name()
|
||||
for t in asyncio.all_tasks()
|
||||
if t is not asyncio.current_task()
|
||||
}
|
||||
if not any("ingest" in n.lower() for n in names):
|
||||
leaked = False
|
||||
break
|
||||
await asyncio.sleep(0.1)
|
||||
# The session's run() must have returned: no lingering nc-* tasks
|
||||
# holding the socket open. Poll briefly — teardown is async.
|
||||
deadline = asyncio.get_running_loop().time() + 5.0
|
||||
while asyncio.get_running_loop().time() < deadline:
|
||||
names = {
|
||||
t.get_name()
|
||||
for t in asyncio.all_tasks()
|
||||
if t is not asyncio.current_task()
|
||||
}
|
||||
if not any("ingest" in n.lower() for n in names):
|
||||
leaked = False
|
||||
break
|
||||
await asyncio.sleep(0.1)
|
||||
finally:
|
||||
server.should_exit = True
|
||||
with contextlib.suppress(Exception):
|
||||
await asyncio.wait_for(serve_task, timeout=10.0)
|
||||
store.close()
|
||||
assert not leaked, "IngestSession task set leaked after queue-overflow flood"
|
||||
|
||||
@@ -386,7 +368,6 @@ def test_reconnect_after_flood_cannot_resurrect_trace(
|
||||
with client.websocket_connect(_ingest_url()) as ws:
|
||||
for seq in range(6):
|
||||
ws.send_text(_frame(seq))
|
||||
_drain(ws)
|
||||
with pytest.raises(WebSocketDisconnect):
|
||||
while True:
|
||||
_recv_status(ws)
|
||||
@@ -394,7 +375,6 @@ def test_reconnect_after_flood_cannot_resurrect_trace(
|
||||
|
||||
with client.websocket_connect(_ingest_url()) as ws:
|
||||
ws.send_text(_frame(5))
|
||||
_drain(ws)
|
||||
with pytest.raises(WebSocketDisconnect) as excinfo:
|
||||
while True:
|
||||
_recv_status(ws)
|
||||
@@ -412,7 +392,6 @@ def test_frame_with_learner_id_in_body_rejected(client: TestClient) -> None:
|
||||
bad = json.loads(_frame(0))
|
||||
bad["learner_id"] = "spoofed"
|
||||
ws.send_text(json.dumps(bad))
|
||||
_drain(ws)
|
||||
frames = [_recv_status(ws)]
|
||||
assert frames[0]["type"] == "event_rejected"
|
||||
assert client.get(f"/v1/telemetry/traces/{LEARNER}/{TASK}").status_code == 404
|
||||
@@ -421,7 +400,6 @@ def test_frame_with_learner_id_in_body_rejected(client: TestClient) -> None:
|
||||
def test_unknown_event_kind_rejected_nothing_stored(client: TestClient) -> None:
|
||||
with client.websocket_connect(_ingest_url()) as ws:
|
||||
ws.send_text(_frame(0, kind="rm_rf_everything"))
|
||||
_drain(ws)
|
||||
frames = [_recv_status(ws)]
|
||||
assert frames[0]["type"] == "event_rejected"
|
||||
assert "unknown event kind" in frames[0]["detail"]
|
||||
@@ -552,10 +530,10 @@ def test_manager_urls_carry_valid_tokens(client: TestClient) -> None:
|
||||
accepts — mint/verify agree through the shared app.state instance."""
|
||||
from urllib.parse import parse_qs, urlparse
|
||||
|
||||
manager = client.app.state.sandbox_manager
|
||||
manager = client.app.state.sandbox_manager # type: ignore[attr-defined] # P5: TestClient.app is typed ASGIApp; runtime FastAPI
|
||||
env = manager._capture_env("sbx-tok-1", "learner-tok", "task-tok")
|
||||
parsed = urlparse(env["NC_INGEST_URL"])
|
||||
qs = parse_qs(parsed.query)
|
||||
assert qs["token"][0] == client.app.state.ingest_token.mint(
|
||||
assert qs["token"][0] == client.app.state.ingest_token.mint( # type: ignore[attr-defined] # P5: TestClient.app is typed ASGIApp; runtime FastAPI
|
||||
"learner-tok", "task-tok", "sbx-tok-1"
|
||||
)
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user