fix: harden Prisma schema foundation, resolve tsc error

This commit is contained in:
caelum0x 2026-08-25 03:09:57 +03:00
parent 043ea0bf9e
commit 9cbad2bde3
46 changed files with 5956 additions and 615 deletions

615
ARCHITECTURE.md Normal file
View File

@ -0,0 +1,615 @@
# GitGram — Deep Enterprise Architecture
> Planning document. Read-only analysis of the codebase as of 2026-08-25.
> Scope: the GitGram talent graph + social layer, and the AITimeMachine (AITM)
> substrate it rides on. This is the enterprise-target companion to
> [README.md](README.md), [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md),
> [NORTH_STAR_PRD_ARCHITECTURE_V1.md](NORTH_STAR_PRD_ARCHITECTURE_V1.md) and
> [INTEGRATION_PLAN.md](INTEGRATION_PLAN.md).
---
## 0. One-paragraph thesis
GitGram is an **evidence-based talent knowledge graph**: it connects an
organization's *need* to a *person* through that person's **real open-source
work** — repositories they demonstrably own or maintain, GitHub contribution
activity, and completed institutional pilots — never through a self-authored
résumé. On top of the graph sits an **"Instagram for repos"** social layer
(posts, reels, stories, feeds, follows, trending) that generates the engagement
and public proof surface. Underneath sits **AITimeMachine (AITM)**, an AI-native
version-control substrate that captures/restores agent coding workflows and, via
its **adoption-evidence** subsystem, turns checkpoints and restores into
privacy-preserving proof of real usage. The whole thing is a Zemin360 hackathon
product built as a TypeScript monorepo.
---
## 1. What it is + current state
### 1.1 The two products, honestly
| Product | What it actually is in the tree | Maturity |
|---|---|---|
| **GitGram** | GitHub-repos-as-social-profiles + an evidence-based **talent graph** (opportunities → matches → referrals → pilots → public proof). Express 5 + Prisma + Postgres + Redis backend; Next.js 14 web; Expo/React-Native mobile. | Feature-broad, build-clean, **not launched** (operational blockers). |
| **AITimeMachine (AITM)** | AI workflow capture + deterministic restore substrate. Express + Drizzle/Neon api-server, an MCP server (~127 tools), a CLI, 7 vendored first-party engines, and an **OSS adoption-evidence** API. | Deep, but CLI/MCP unpublished; heavy `any` debt. |
The North Star framing is "GitGram = new GitHub, AITM = new Git." The task's
framing — **talent graph + evidence matching + social proof** — is the layer
that monetizes GitGram, and it is real code, not a slide.
### 1.2 Stack (mostly TypeScript)
- **Language:** TypeScript across backend, web, mobile, AITM api-server/mcp/cli.
Vendored engines add **Go** (`beads`), **C** (real `git`), **Python** (`pal`).
- **GitGram backend** (`gitgram/backend`): Express 5, Prisma ORM → Postgres,
Redis (cache/queues/pubsub), Apollo GraphQL + tRPC + Socket.IO, Octokit REST
for all GitHub calls, node-cron jobs, Winston logging.
- **GitGram web** (`gitgram/web`): Next.js 14 / React 18, TanStack Query
conventions ported from Bluesky.
- **GitGram mobile** (`gitgram/mobile`): Expo 54 / React Native / expo-router.
- **AITM api-server** (`aitimemachine/api-server`): Express + Drizzle ORM,
dual driver (`@neondatabase/serverless` in prod, `pg` Pool local), ~54 tables.
- **AITM MCP** (`aitimemachine/mcp`): 16 tool groups, `tm_*`-prefixed.
- **Data of record:** Postgres is authoritative; Redis is cache/hot-path;
local `.aitimemachine/` is a performance cache only.
### 1.3 The real features that matter to the talent thesis
**A. Talent graph (evidence-first).**
`gitgram/backend/src/services/talentGraphService.ts` (520 LOC) is the core.
`getTalentGraph(userId, {publicView})` assembles a person's dossier from three
**evidence tiers**, ranked `verified > linked > recorded`:
- `verified` — repository ownership proven by confirmed GitHub write access at
claim time (`Repository.claimedBy/claimedAt`), or a completed institutional
pilot.
- `linked` — a project imported through the connected GitHub account.
- `recorded` — a self-entered project record with no external proof.
Each project carries a `TalentEvidence[]` list (`repository_claim`,
`github_sync`, `github_activity`, `project_record`, `institutional_pilot`) with
an `occurredAt` timestamp and a `sourceUrl` — i.e. **provenance is already
first-class on every fact.** The service is scrupulous about the
public/private boundary: public reads consume only a privacy-safe projection
(`TalentPublicProof`), never institution-authored free text.
**B. Evidence matching engine.**
`findTalentMatches(requiredSkills, limit)` (same file) is the matcher. Given an
org's required skills it: (1) pulls completed public pilot proofs whose
`evidenceSkills` overlap; (2) finds users whose interests, managed public-repo
topics/languages, or pilot participation intersect the skills; (3) scores each
`score = coverage*75 + min(verifiedProjects,2)*10 + min(projects,3)*5` capped at
100; (4) returns matched/missing skills, up to 4 evidence projects, and a
human-readable reason (currently Turkish-localized — Zemin360 artifact). The key
design property: **a match is only as strong as its verifiable evidence; interest
alone yields the weakest signal.**
**C. Org-need modeling + pilot lifecycle.**
Prisma models: `TalentOpportunity` (org need: `problem`, `requiredSkills[]`,
`successMetric`, `durationWeeks`, status `OPEN→MATCHING→PILOT→CLOSED`),
`TalentReferral` (`CONTACTED→ACCEPTED→DECLINED`), `TalentPilot`
(`PLANNED→ACTIVE→REVIEW→COMPLETED→CANCELLED`, with `milestones`,
`deliverableUrl`, `publicEvidenceConsent`), `TalentPilotStatusTransition` (an
append-only audit of every status change with actor + revision),
`TalentPublicProof` (the consented, privacy-scrubbed projection with a GIN index
on `evidenceSkills`), and `TalentMutationReceipt` (idempotency ledger).
All mutations go through `talentMutationService.ts` — **serializable-isolation,
idempotency-key-gated, replay-safe** writes with a 30-day receipt retention.
This is production-grade transactional discipline.
**D. The social / feed layer ("Instagram for repos").**
The engagement engine that produces public proof:
- **Ranking:** `trendingRankingService.ts` (1,294 LOC) — weighted signals,
time decay, activity velocity, engagement momentum, burst detection, spam/
new-account guards, Hot/Today/Week tiers, DB-overridable weights.
- **Feed assembly:** `feedService.ts` → `feedAlgorithm.ts` → `feedTuner.ts`
(697 LOC, author-run limiting + content interleaving + sponsored injection +
diversity penalty, ported from Bluesky's FeedTuner).
- **Content:** posts (`postController.ts`, 916), reels (`reelsController.ts`,
1,024), stories (`storiesController.ts`, 1,053), plus video transcoding
(1,083). Real-time via Socket.IO (`websocket/socket.ts`, 976).
- **GitHub ingestion:** inbound webhooks HMAC-verified
(`middleware/githubWebhookAuth.ts`) → `githubActivityService.ts` (893,
dedupe-by-delivery-id) → **`RepositoryActivity`** rows; read side aggregates
those into contribution grids (`contributionService.ts`) and repo insights
(`repoInsightsService.ts`). Social-graph import (`githubSyncService.ts`) maps
GitHub followers/stars → GitGram follows.
**E. The AITM adoption-evidence endpoint** (the "AITM adoption endpoint").
`aitimemachine/api-server/src/routes/adoption.ts` (688 LOC) is a
**privacy-preserving proof-of-real-usage** subsystem, deeply on-thesis for an
evidence product:
- `GET /v1/adoption/summary` — **public aggregate** evidence: active/lifetime
developers, projects, checkpoints, applied restores, plus an **OSS coverage
window** (external contributors, repeat contributors, maintainer first-response
load) and **case evidence** (applied-restore→checkpoint→project links). Emits
a `methodology` block and contains **no** account/repo/contributor identifiers.
- `POST /v1/adoption/oss-coverage/batches` and `POST /v1/adoption/case-evidence`
— idempotent, `Idempotency-Key`-gated ingestion from authenticated collectors,
using **opaque 64-hex keys** (`repositoryKey`, `contributorKey`,
`contributionKey`) so identities never leave the collector. Backed by Drizzle
tables `oss_coverage_batches`, `oss_contribution_records`, `oss_case_evidence`.
**F. Gitgram ↔ AITM bridge (both directions).**
- GitGram → AITM: `aitmService.ts` validates checkpoints
(`GET /v1/checkpoints/{id}`, graceful-degrade), and `POST /api/v1/posts/
from-checkpoint` turns a checkpoint into a post; per-repo AITM settings live at
`/api/v1/repositories/:owner/:name/aitm-settings`.
- AITM → GitGram: `gitgramBridgeService.ts` pushes commit/release/**restore**
events to GitGram `POST /api/v1/posts`; checkpoint creation calls
`POST /api/v1/change-stories/auto-generate` to draft a "Change Story" post.
- AITM also hosts a **full parallel Gitgram social API** at `/v1/gitgram/*`
writing to its own Drizzle tables (`posts`, `reactions`, `follows`,
`trend_scores`, …) — an alternative to the standalone GitGram backend. **This
duplication is an owner decision (see §5.4).**
### 1.4 Honest maturity assessment
- **Strong:** talent transactional integrity (serializable + idempotency +
status-transition audit), the evidence/provenance model, privacy boundaries on
public projections, the adoption-evidence privacy design, feed ranking depth.
- **Weak / risk:** the talent "graph" is computed **on the fly from relational
joins** — there is no graph store, no persisted edges, no multi-hop traversal,
no entity fusion/dedup. Matching is a single-pass scoring heuristic (no
structure-layer signal). Two separate social data planes (GitGram Prisma vs
AITM Drizzle) risk divergence. AITM carries ~839 `any` and an unpublished
CLI/MCP. Zero web/mobile tests. `drizzle.config.ts` points at a stale schema
path. Match reasons are hard-coded Turkish strings.
- **Not launched:** npm publish, production secrets, VPS/DNS remain open
([PLAN.md](PLAN.md) Phase 3).
---
## 2. Target enterprise structure
The current split (GitGram Prisma world + AITM Drizzle world, with a duplicated
social plane) should converge on **one talent-graph domain** with clear module
seams. Proposed enterprise layout — a rich decomposition, not a rename:
```
gitgram-ai/
├── apps/
│ ├── web/ # Next.js — social + talent-network + admin console
│ ├── mobile/ # Expo/RN
│ ├── aitm-website/ # marketing/docs
│ └── admin/ # (or web/app/admin) ops + moderation + evidence audit
│
├── services/
│ ├── gateway/ # edge: authN, rate-limit, request-id, GraphQL/tRPC/WS fan-in
│ │
│ ├── ingestion/ # GitHub → normalized events (source-typed extraction)
│ │ ├── github/
│ │ │ ├── octokitClient.ts # pooled, rate-limit-aware Octokit REST
│ │ │ ├── graphqlClient.ts # NEW: GitHub GraphQL for contributions/commits
│ │ │ ├── webhookReceiver.ts # HMAC verify + delivery-id dedupe
│ │ │ ├── webhookNormalizer.ts # payload → RepositoryActivity (typed)
│ │ │ ├── repoSync.ts # repos.get → upsert (stars/forks/lang/topics)
│ │ │ ├── socialGraphImport.ts # followers/stars → follows
│ │ │ └── contributionHarvester.ts # commit/PR/review history → Contribution
│ │ └── collectors/ # opaque-key OSS + case-evidence collectors (feed §1.3E)
│ │
│ ├── evidence/ # extraction → typed Evidence facts (the KG feed)
│ │ ├── extractors/
│ │ │ ├── repositoryClaimExtractor.ts # verified ownership
│ │ │ ├── githubActivityExtractor.ts # contribution events → evidence
│ │ │ ├── pilotEvidenceExtractor.ts # completed pilots → proof
│ │ │ └── skillInferencer.ts # repo lang/topics + activity → Skill demonstrations
│ │ ├── provenance.ts # source + timestamp + confidence on every fact
│ │ └── evidenceLedger.ts # append-only, immutable facts
│ │
│ ├── talent-graph/ # THE talent knowledge graph (persisted)
│ │ ├── ontology/
│ │ │ ├── ontology.yaml # single source of truth (§3)
│ │ │ └── competencyQuestions.md # spec + test suite
│ │ ├── store/
│ │ │ ├── graphRepository.ts # Repository-pattern facade over the store
│ │ │ ├── nodes/ edges/ # typed entity + edge writers
│ │ │ └── adapters/ # pg-recursive-CTE | Apache AGE | Kùzu (§4)
│ │ ├── fusion/
│ │ │ ├── blocking.ts # candidate grouping (never O(n²))
│ │ │ ├── matching.ts # string+attribute+STRUCTURE layers
│ │ │ ├── mergePolicy.ts # deterministic merge + merged_from undo
│ │ │ └── contradiction.ts # keep-both + prefer-newer at read
│ │ ├── matching-engine/
│ │ │ ├── needSkillResolver.ts # Need.requiredSkills → Skill nodes
│ │ │ ├── candidateRetrieval.ts # blocking over the graph
│ │ │ ├── scorer.ts # coverage + verified-evidence + structure
│ │ │ ├── explanation.ts # cited evidence paths (i18n)
│ │ │ └── ranker.ts
│ │ └── graphrag/ # subgraph serialize → LLM context (§3.5)
│ │
│ ├── org-need/ # opportunity modeling
│ │ ├── opportunityService.ts # TalentOpportunity CRUD + status machine
│ │ ├── needTaxonomy.ts # skill normalization/canonicalization
│ │ └── referralService.ts
│ │
│ ├── pilot/ # pilot lifecycle (the verification loop)
│ │ ├── pilotService.ts # PLANNED→…→COMPLETED state machine
│ │ ├── statusTransition.ts # append-only audit (exists today)
│ │ ├── milestoneService.ts
│ │ ├── proofPublisher.ts # consent-gated TalentPublicProof projection
│ │ └── mutationLedger.ts # idempotency receipts (exists today)
│ │
│ ├── social/ # the "Instagram for repos" plane (single source)
│ │ ├── feed/ # feedService/algorithm/tuner (exists)
│ │ ├── ranking/ # trending signals engine (exists)
│ │ ├── content/ # posts/reels/stories/snippets
│ │ ├── graph/ # follows/social graph
│ │ ├── notifications/ # dispatcher + adapters (slack/discord/push)
│ │ └── moderation/ # label taxonomy + enforcement
│ │
│ ├── profiles/ # Person/Repo public profiles + talent dossier read models
│ │
│ ├── aitm/ # the substrate subsystem
│ │ ├── api-server/ # checkpoints/restore/sessions/memory (Drizzle)
│ │ ├── mcp/ # 16 tool groups
│ │ ├── engines/ # beads · context7 · git · gitnexus · a2a · pal
│ │ ├── adoption/ # OSS coverage + case-evidence + /summary
│ │ └── bridge/ # gitgramBridgeService + change-story auto-gen
│ │
│ └── api/ # public REST/GraphQL contract + OpenAPI
│
├── packages/ # shared, versioned libs
│ ├── graph-core/ # entity/edge/provenance types + graph client iface
│ ├── evidence-schema/ # zod schemas for every evidence kind
│ ├── contracts/ # API envelope, error types, DTOs
│ ├── skills-taxonomy/ # canonical skill vocabulary + aliases
│ └── observability/ # logger, metrics, tracing
│
├── admin/ # evidence-audit console, pilot ops, moderation queue
├── infra/ # docker-compose, deploy, migrations, secrets contract
└── docs/
```
Key structural moves vs today: (1) promote **talent-graph** to a first-class
persisted domain with an ontology file and a Repository-pattern store; (2)
extract **ingestion** and **evidence** as explicit stages (they're currently
tangled inside `githubActivityService`/`talentGraphService`); (3) collapse the
**two social planes** into one `social/` service with a single store; (4) keep
**AITM** as a bounded subsystem exposing checkpoints, memory, and the
adoption-evidence API.
---
## 3. Graph engineering — GitGram *is* a talent knowledge graph
Applying the graph-engineering discipline (ontology → extraction → fusion →
serving). Today GitGram sits at the **"typed edges in SQL"** representation
(appropriate for <50K nodes, single app) — the ontology below is *latent* in the
Prisma schema and the `talentGraphService` joins. The plan makes it explicit and
gives it a persistence + fusion + traversal path.
### 3.1 Competency questions (the spec AND the test suite)
1. Which people demonstrate skill X with **verified** (not merely claimed)
evidence?
2. Which people match Need N, and *through what evidence path* (repo claim →
contribution → skill), ranked by verifiability?
3. Who has completed a pilot for an org in domain D, with a public deliverable?
4. Which repos does person P **own vs maintain vs merely record**, and since when?
5. Who are P's real collaborators (shared-maintainer edges), and on what repos?
6. What is P's contribution trajectory over time on repo R (velocity, recency)?
7. Which needs are currently unmatched because no person covers skill set S?
8. For a completed pilot, what is the immutable status history and who acted?
9. Which external OSS contributors show up repeatedly (repeat-contributor signal)
without leaking identity?
10. Given a checkpoint/restore, what real usage evidence supports an org's ROI?
Each must path through the schema on paper; any that can't = missing type/edge.
### 3.2 Entities (the ontology)
Canonical-form rule stated up front: **Person** keyed by GitHub identity
(`githubId`) when connected, else GitGram `username` (lowercased); **Repo** keyed
by lowercased `owner/name` (`fullName`); **Skill** keyed by normalized
lowercased token (matches `normalizeSkill()` today).
| Entity | Definition | Backing today | Key attributes |
|---|---|---|---|
| **Person** | A developer or manager | `User` | username, githubId, interests[], isPrivate |
| **Repo** | A GitHub repository as social+evidence object | `Repository` | fullName, language, topics[], stars, claimedBy, claimedAt |
| **Project** | A person-entered project record (weakest tier) | `Project` | fullName, githubId?, tags[] |
| **Org** | An organization posting needs | `Organization` / `TalentOpportunity.organizationName` | name |
| **Need** | An org's demand: problem + required skills + success metric | `TalentOpportunity` | requiredSkills[], successMetric, durationWeeks, status |
| **Skill** | A canonical capability token | *implicit* (strings in topics/interests/requiredSkills) | canonical name, aliases |
| **Contribution** | A single unit of demonstrated work (commit/PR/review/push) | `RepositoryActivity` | eventType, occurredAt, sha, actorLogin |
| **Evidence** | A typed, provenance-bearing fact linking Person→(Repo/Skill/Pilot) | `TalentEvidence` (computed) | kind, occurredAt, sourceUrl, verificationLevel |
| **Pilot** | A time-boxed engagement against a Need | `TalentPilot` | status, milestones, deliverableUrl, consent |
| **Referral** | A community intro of a Person to a Need | `TalentReferral` | status |
| **Proof** | Consented, privacy-scrubbed public projection of a Pilot | `TalentPublicProof` | evidenceSkills[], deliverableUrl, completedAt |
| **Checkpoint / RestoreEvent** | AITM usage-evidence events | AITM Drizzle | createdAt, status=applied |
Attributes-vs-entities call: **Skill must be promoted from an attribute (string)
to an entity** — it has its own relationships (`DEMONSTRATES_SKILL`,
`REQUIRES_SKILL`, alias edges) and is the join point of the whole matcher. This
is the single highest-value ontology change.
### 3.3 Relations (edges) — with domain/range, time + provenance
Every edge carries `{since, until?, source, extractedAt, confidence}` (already
true in spirit — `TalentEvidence.occurredAt/sourceUrl`).
| Edge | Domain → Range | Meaning | Provenance source today |
|---|---|---|---|
| `OWNS` | Person → Repo | verified write access at claim | `Repository.claimedBy/claimedAt` |
| `MAINTAINS` | Person → Repo | recorded maintainer role | `RepositoryManager.role` |
| `CONTRIBUTED_TO` | Person → Repo | a contribution event occurred | `RepositoryActivity` (actorLogin) |
| `DEMONSTRATES_SKILL` | Person → Skill | evidence supports a capability | derived from repo lang/topics + activity |
| `REQUIRES_SKILL` | Need → Skill | need's required skill | `TalentOpportunity.requiredSkills[]` |
| `POSTED` | Org → Need | org authored a need | `TalentOpportunity.createdById` |
| `MATCHES_NEED` | Person → Need | scored candidacy w/ evidence | computed by `findTalentMatches` |
| `REFERRED_TO` | Person → Need | community referral | `TalentReferral` |
| `PARTICIPATES_IN` | Person → Pilot | pilot participant | `TalentPilot.participantId` |
| `FULFILLS` | Pilot → Need | pilot addresses need | `TalentPilot.opportunityId` |
| `PROVES` | Proof → Person | public evidence of completion | `TalentPublicProof` |
| `COLLABORATES_WITH` | Person → Person | shared-maintainer structure edge | co-managers of a repo |
| `FOLLOWS` | Person → (Person\|Repo) | social edge | `Follow`/`RepositoryFollow` |
| `EVIDENCED_BY` | (any) → Evidence | reifies a fact + its provenance | `TalentEvidence` |
The `COLLABORATES_WITH` structure edge is what unlocks the **structure layer** of
fusion and matching that naive dedup misses (two "J. Smith" nodes sharing 3
co-maintainers are the same person).
### 3.4 Events (first-class, not flattened)
Dynamic domain → model events as nodes with typed argument schemas:
- **ContributionEvent** `{person, repo, type∈{push,pr,review,issue}, sha?, at}` —
from `RepositoryActivity`; the raw material of `DEMONSTRATES_SKILL`.
- **PilotStatusTransition** `{pilot, actor, from, to, revision, at}` — already an
append-only table; a textbook event-logic edge (`ACTIVE → COMPLETED`).
- **CheckpointCreated / RestoreApplied** `{project, checkpoint, at, status}` —
AITM adoption evidence; feeds `/v1/adoption/summary`.
These are *event-logic graph* candidates: "pilot completed → proof published →
match score rises" is exactly the "what leads to what" pattern.
### 3.5 Serving the graph (GraphRAG) — the matcher, upgraded
Today's matcher is a one-pass scan + heuristic score. The graph-engineering
upgrade, staged:
1. **Entity-link** the Need → resolve `requiredSkills` to canonical Skill nodes.
2. **Blocking** (not O(n²)): candidates = people sharing ≥1 Skill node or in a
pilot cluster (today's `interests.hasSome` + repo-topic filter is a crude
block — formalize it).
3. **Path retrieval:** for each candidate, retrieve the *evidence path*
`Person -CONTRIBUTED_TO-> Repo -DEMONSTRATES-> Skill <-REQUIRES- Need` rather
than a bag of attributes. The path **is** the explanation.
4. **Score on layered evidence** (string skill-match + attribute + **structure**
via collaborator overlap + verification tier), the way §1.3B already weights
verified evidence, plus a structure term.
5. **Serialize** the winning subgraph as compact `(head)-[REL{since,source}]->
(tail)` triples for an LLM to narrate the match reason (replaces the hard-coded
Turkish strings with cited, provable text).
### 3.6 Task graph — ingest → extract-evidence → match → pilot → verify
The product pipeline is a DAG; draw an arrow only where a job needs a prior job's
result (delete fake edges → parallelize):
```
┌─ repoSync ─────────┐
GitHub webhook / OAuth ──┼─ contributionHarvest┼─→ evidenceExtract ─→ fuse ─┐
└─ socialGraphImport ─┘ (per source type) │
▼
Need posted ───────────────────────────────────────────────→ MATCH (GraphRAG)
│
┌───────┴────────┐
referral direct match
└───────┬────────┘
▼
PILOT lifecycle (state machine)
│
┌── deliverable ──┬── status audit ──┐
▼ ▼ ▼
VERIFY (separate) consent gate proof publish
did it meet the (HUMAN GATE) (privacy scrub)
success metric? │
▼
AITM adoption evidence → /summary
```
Graph-engineering rules applied:
- **Fan-out** the three GitHub ingest jobs (they don't read each other) — the
"and then" between them is a *fake edge*.
- **Verify in a separate context:** pilot completion must be judged against the
`successMetric` by a node that is *not* the matcher — a matcher grading its own
candidate is the self-grading failure mode. Diverse skeptics: "did the
deliverable meet the metric?" ≠ "is the evidence real?".
- **Human gate on irreversible edges:** `publicEvidenceConsent` before any Proof
is published, and referral acceptance — placed exactly where a mistake is
expensive to undo (publishing someone's institution-linked work). This gate
**already exists** in the schema (`publicEvidenceConsent`, `TalentPublicProof`).
- **One writer per artifact:** talent mutations already funnel through a single
serializable, idempotent writer (`talentMutationService`) — extend that
invariant to graph writes.
- **Stop rule:** ingestion/extraction split cleanly → parallelize; the
match→pilot→verify chain is sequential (each step needs the full picture) →
keep it single-owner.
---
## 4. OSS foundations — fork / build-on
GitGram already vendors and adopts OSS deliberately (see
[docs/can be fork.md](docs/can%20be%20fork.md) and
[INTEGRATION_PLAN.md](INTEGRATION_PLAN.md)). This section covers the **graph +
search + feed** foundations the talent-graph target needs, with license and
reuse-vs-build calls. Verify every license at adoption time; flagged items are
copyleft/source-available and unsafe to vendor into a commercial product.
### 4.1 GitHub API tooling
| Option | License | Fit | Call |
|---|---|---|---|
| **Octokit** (`@octokit/rest`, `graphql`) | MIT | Already used everywhere for REST | **Keep.** Add `@octokit/graphql` for the contributions/commit-history harvest (GraphQL contributions collection) the evidence layer needs. |
| `@octokit/webhooks` | MIT | Typed webhook verify/parse | **Adopt** to replace hand-rolled HMAC + payload mapping in `githubActivityService`. |
| `octokit/plugin-throttling` + `plugin-retry` | MIT | Rate-limit correctness at scale | **Adopt** — ingestion is the scaling bottleneck. |
### 4.2 Graph store (the big decision)
| Option | License | Fit | Call |
|---|---|---|---|
| **Postgres + recursive CTEs** (status quo) | PostgreSQL (permissive) | Fine to ~50K nodes; no new infra | **Default now.** Formalize edges as tables; ontology in code. |
| **Apache AGE** (Postgres extension, openCypher) | **Apache-2.0** | Cypher on the *existing* Postgres; no second datastore | **Primary recommendation** when multi-hop queries get frequent/slow. Lowest-friction upgrade — keeps one source of truth. |
| **Kùzu** (embedded graph DB) | **MIT** | Fast analytical multi-hop, embeddable in Node | **Adopt for read-side analytics** (collaborator-overlap, path retrieval) as a projection; not system-of-record. |
| Neo4j Community | **GPL-3.0** ⚠️ | Mature Cypher/GDS | **FLAG** — GPL-3 core; GDS/enterprise proprietary. Avoid vendoring; only via network boundary if ever. |
| Memgraph | **BSL 1.1** ⚠️ | Fast in-mem | **FLAG** — source-available, not OSI; commercial-use limits. |
| pgvector | PostgreSQL (permissive) | Embedding similarity for blocking/GraphRAG | **Adopt** — already implied by AITM embeddings; use for the fusion blocking layer + skill-embedding matches. |
**Recommendation:** stay on Postgres now → **Apache AGE** for in-DB graph
queries → **Kùzu** as an embedded read projection for heavy traversal. This never
introduces a copyleft dependency and keeps Postgres authoritative.
### 4.3 Search / discovery
| Option | License | Fit | Call |
|---|---|---|---|
| **OpenSearch** | **Apache-2.0** | Full search + vector, enterprise-grade | **Primary** for talent/repo/skill search at scale. |
| **Meilisearch** | **MIT** | Fast, simple, typo-tolerant | **Adopt** for the near-term (lighter than OpenSearch, MIT-clean). |
| Typesense | **GPL-3.0** ⚠️ | Great DX | **FLAG** — GPL-3; avoid unless run purely as a separate service. |
| Elasticsearch | **AGPL/SSPL/Elastic** ⚠️ | Powerful | **FLAG** — SSPL/AGPL; do not vendor. |
### 4.4 Feed / social backends
GitGram already **ported** Bluesky's `FeedTuner`/merge logic (MIT) into
`feedTuner.ts`/`feedAlgorithm.ts` and gh-social's follow-cache pattern — the
right reuse posture. Remaining:
| Option | License | Fit | Call |
|---|---|---|---|
| `bluesky-social/social-app` | **MIT** | Feed merge, notification grouping, moderation taxonomy | **Continue porting** (already P0). |
| `amirfakhrullah/gh-social` | MIT-family (verify) | GitHub-follows→feed concept | Reference (already mined). |
| `karanpratapsingh/Proximity` | **GPL-3.0** ⚠️ | RN social + GraphQL subs | **FLAG — reference only, zero code copied** (already noted in INTEGRATION_PLAN). |
| Redis / BullMQ | BSD / MIT | Hot-path cache + queues | **Keep** (already used). |
### 4.5 The 7 AITM engines (already vendored) — license posture
| Engine | License | Note |
|---|---|---|
| `a2a-js` | **Apache-2.0** | Clean; adopted as contract layer. |
| `context7` | **MIT** | Clean; in-process SDK. |
| `beads` (Go/Dolt) | MIT (verify) | Adopted as *dependency/workflow*, not source-copied. |
| real `git` (vendored C) | **GPL-2.0** ⚠️ | Shipped as a **separate binary** invoked over a process boundary (not linked) — the correct way to use GPL git. Keep it a binary seam. |
| `pal-mcp-server` (Python) | Apache/permissive (verify) | Managed subprocess. |
| **`gitnexus`** | **PolyForm Noncommercial** ⚠️⚠️ | **Hard flag.** Non-OSI, **noncommercial** license. INTEGRATION_PLAN already says: do **not** vendor source into a commercial product until licensed. Treat as wrap/replace target. |
### 4.6 rithub (the separate Rust git forge) — future backend
GitGram's own [PLAN.md](PLAN.md)/North Star draw a boundary: **AITM is not a Git
reimplementation** — "a separate Rust Git Forge product owns the Rust Git
implementation and self-hostable forge boundary." **rithub** is that product.
Architecturally it is a **future backend GitGram integrates with over APIs**, not
a vendored dependency:
- **Seam:** the same `ingestion/github/*` abstraction (webhook receiver + repo
sync + Octokit client) should be interface-first so a **rithub forge adapter**
can be added alongside the GitHub adapter — GitGram then ingests contribution
evidence from a self-hosted rithub forge exactly as it does from GitHub.
- **Why it matters for the talent graph:** rithub-hosted repos become another
`CONTRIBUTED_TO`/`OWNS` provenance source; the evidence tiers and matcher are
source-agnostic by design.
- **Boundary discipline:** keep it an **API integration** (network/process seam),
mirroring how the vendored C `git` and GPL concerns are already isolated behind
binary/URL boundaries — do not couple GitGram's Prisma/Drizzle stores to
rithub's Rust internals.
### 4.7 Reuse-vs-build summary
- **Reuse (adopt/port):** Octokit stack, Bluesky feed logic, Apache AGE + Kùzu +
pgvector for graph/vectors, OpenSearch/Meilisearch for search, a2a-js +
context7. These are permissive and battle-tested.
- **Build (thin, owned):** the **ontology**, the **fusion pipeline** (blocking/
matching/merge — domain-specific, no OSS fits), the **evidence extractors**,
and the **GraphRAG match explanation**. These are GitGram's moat; keep them
first-party and small.
- **Never vendor:** gitnexus (PolyForm NC), Neo4j/Memgraph/Typesense/ES cores,
GPL git *source* (binary seam only).
---
## 5. Scale reality
### 5.1 Current size (TS/TSX, excludes node_modules/dist/.next)
| Area | Files | LOC |
|---|---:|---:|
| GitGram backend (`gitgram/backend/src`) | 339 | ~83.8K |
| GitGram web (`gitgram/web`) | 577 | ~128.9K |
| GitGram mobile (`gitgram/mobile`) | 542 | ~126.3K |
| AITM core (`aitimemachine/src`) | 197 | ~62.6K |
| AITM api-server (`api-server/src`) | 179 | ~80.4K |
| AITM MCP (`mcp/src`) | 50 | ~12.7K |
| **TS subtotal (these areas)** | **~1,884** | **~494.7K** |
Plus vendored engines (Go/C/Python — `beads`, `git`, `pal`, `gitnexus`,
`context7`, `a2a`) not counted above. Prisma schema: 2,320 LOC / ~70 models.
AITM Drizzle schema: ~1,521 LOC / ~54 tables. Backend: 55 controllers, ~95–102
services, 66 routes.
### 5.2 Talent-graph subsystem, per-module (today)
| File | LOC | Role |
|---|---:|---|
| `services/talentGraphService.ts` | 520 | dossier assembly + matcher |
| `controllers/talentGraphController.ts` | 511 | REST surface |
| `services/talentMutationService.ts` | 116 | serializable/idempotent writes |
| `routes/talentGraph.ts` | 41 | routing + CSRF-origin guard |
| Prisma talent models | ~150 | Opportunity/Referral/Pilot/Transition/Proof/Receipt |
| **Talent subtotal** | **~1,340** | — |
The talent graph is **~1.3K LOC riding on a 2.3K-line Prisma schema and the
~10K-LOC GitHub-ingestion + feed machinery** — small core, large substrate.
### 5.3 Enterprise-target incremental estimate
| New/expanded module | Est. LOC |
|---|---:|
| `packages/graph-core` + `evidence-schema` + ontology | 1.5–2.5K |
| `talent-graph/store` (AGE/Kùzu adapters + Repository facade) | 2–3K |
| `talent-graph/fusion` (blocking/matching/merge/contradiction) | 2–3K |
| `talent-graph/matching-engine` + GraphRAG serve | 2–3K |
| `ingestion` refactor (github adapters + contribution harvester + rithub seam) | 2–3K |
| `evidence` extractors + provenance | 1.5–2.5K |
| social-plane consolidation (dedupe GitGram/AITM) | -3 to +2K (net simplification) |
| tests to 80% (web/mobile currently ~0) | 8–15K |
| **Net new** | **~19–33K LOC** |
Target total lands GitGram+AITM around **~520–530K TS LOC** — mid-size
enterprise monorepo; the *risk* is not size but the **two-data-plane split** and
**test coverage**, not raw LOC.
### 5.4 Owner decisions (must resolve before enterprise build)
1. **One social plane or two?** GitGram Prisma social vs AITM Drizzle
`/v1/gitgram/*` are duplicate implementations. Pick one system-of-record.
2. **Graph store path:** stay pg-CTE now, or commit to **Apache AGE** + **Kùzu**
projection? (Recommendation: yes, in that order.)
3. **Promote Skill to a first-class entity** (highest-value ontology change) —
requires a canonical skills taxonomy package.
4. **gitnexus licensing:** wrap/replace or license — it is PolyForm
Noncommercial and cannot ship in a commercial product as-is.
5. **rithub integration seam:** make `ingestion` interface-first now so a rithub
forge adapter drops in later without a rewrite.
6. **Matcher explanation:** replace hard-coded Turkish reason strings with
GraphRAG-serialized, cited evidence paths (i18n).
### 5.5 Done-ladder
- **L0 — Compiles / feature-broad (DONE).** Both products build clean; talent
graph, evidence tiers, pilot lifecycle, feed ranking, adoption evidence all
exist and are transactionally sound.
- **L1 — Launchable (open, PLAN.md Phase 3).** Publish AITM CLI/MCP to npm;
production secrets; VPS + DNS; fix stale `drizzle.config.ts`; end-to-end smoke.
- **L2 — Trustworthy talent graph.** Promote Skill to an entity; persist edges;
add fusion (blocking/matching/merge) so no duplicate-person path breaks;
contribution harvester via GitHub GraphQL; structure-layer collaborator signal.
- **L3 — Explainable matching.** GraphRAG path retrieval + cited, i18n match
reasons; verify-in-separate-context pilot judging; unmatched-need gap analysis.
- **L4 — Enterprise.** Apache AGE/Kùzu store; OpenSearch; rithub adapter;
one consolidated social plane; 80% test coverage; SSO/SAML; retention/audit.
### 5.6 Zemin360 readiness
- **Demo-ready today:** the end-to-end evidence story is compelling and *real* —
post a Need → get evidence-ranked matches → start a pilot → complete it →
publish consented public proof → that proof raises future match scores, with
the AITM `/v1/adoption/summary` showing privacy-preserving real-usage evidence.
Turkish-localized match reasons suit a Zemin360 (Turkish hackathon) audience.
- **Demo risks to pre-empt:** needs seeded data (matcher returns nothing on an
empty graph); the "graph" is relational under the hood (fine for a demo, but
don't over-claim multi-hop traversal); the two social planes can confuse a live
walkthrough — demo the GitGram Prisma plane only.
- **Judge-facing framing:** lead with **evidence-based hiring** (people matched
by real OSS work, not résumés) + **privacy-preserving proof** (opaque-key
adoption evidence) + **the social proof loop** — three differentiators that are
all backed by shipped code.
```

View File

@ -1,11 +1,15 @@
# gitgram-ai
**Gitgram** is the new GitHub — every repository is a TikTok/Instagram-style social
profile. **AITimeMachine (AITM)** is the new Git — AI-native, deterministic version
control with a unified memory layer and built-in agent orchestration.
**GitGram** is a social layer for GitHub. It turns repositories into
Instagram-style accounts with posts, reels, stories, media, followers, feeds,
and publishing workflows. It connects to repositories through authenticated
APIs and webhooks; it does not replace GitHub's repository hosting or Git's
storage and protocol.
This monorepo ships both products together: a repository-first social network on top
of an AI-native version-control substrate.
**AITimeMachine (AITM)** captures and restores AI coding workflows, including
checkpoints, messages, context, tool calls, and agent orchestration. It uses Git
where useful but does not claim to replace Git. A separate Rust Git Forge
product owns the Rust Git implementation and self-hostable forge boundary.
---
@ -13,12 +17,12 @@ of an AI-native version-control substrate.
```
gitgram-ai/
├── gitgram/ # The social network (the "new GitHub")
├── gitgram/ # The GitHub repository social layer
│ ├── web/ # Next.js 14 + React 18 web app (:3000)
│ ├── backend/ # Express 5 + Prisma + GraphQL/tRPC/WS (:4000)
│ └── mobile/ # Expo 54 / React Native + expo-router
│
├── aitimemachine/ # The version-control substrate (the "new Git")
├── aitimemachine/ # AI workflow capture and deterministic restore
│ ├── api-server/ # HTTP API over the engines (Drizzle ORM) (:3001)
│ ├── mcp/ # Model Context Protocol server (stdio/HTTP :3003)
│ ├── cli/ (src/cli*) # `aitm` command-line client

View File

@ -8,12 +8,16 @@ Git is 20 years old. GitHub is a web UI bolted on top.
Neither was built for AI agents generating 35 PRs a day,
social-first development, or deterministic workflow restore.
**Gitgram = new GitHub.** Every repository is a social profile:
posts, reels, stories, team photos, product videos, screenshots —
code and community in one place, like Instagram/TikTok for devs.
**GitGram is the social layer for GitHub repositories.** Every repository can
become a social account with posts, reels, stories, team photos, product videos,
screenshots, followers, and publishing workflows. GitGram uses GitHub APIs and
webhooks; it does not replace Git hosting, repository permissions, object
storage, refs, packfiles, or the Git wire protocol.
**AITM = new Git.** AI-native, time-travel version control
that handles agents at scale and makes open source great again.
**AITM is deterministic workflow time travel for AI coding.** It captures and
restores agent actions, context, messages, tool calls, and checkpoints. It does
not claim to implement or replace Git. The separate Rust Git Forge product owns
the future Rust Git implementation and self-hostable forge boundary.
See `INTEGRATION_PLAN.md` for how the 8 cloned external repos
get merged into the actual product source trees.

View File

@ -29,6 +29,10 @@ WEBSITE_URL=http://localhost:3000
# ── Auth ─────────────────────────────────────────────────────────────────────
# Shared secret for website-to-API internal calls [PROD]
# INTERNAL_SECRET=your-internal-secret-here
# Dedicated adoption collector credential [PROD], at least 32 random characters.
# ADOPTION_INGESTION_SECRET=
# ADOPTION_INGESTION_SECRET_PREVIOUS=
OSS_COVERAGE_MAX_AGE_HOURS=168
# JWT signing secret for session tokens (auto-generated if not set)
# AITM_JWT_SECRET=
# Clerk webhook secret (for user sync)

View File

@ -113,6 +113,14 @@ curl -H "X-API-Key: YOUR_API_KEY" \
https://timemachine-api.gitgram.app/api/checkpoints
```
## Public adoption evidence
`GET /v1/adoption/summary` reports aggregate cloud adoption and maintainer evidence from first-party persisted records. Schema version 2 gives separate windows for product adoption and OSS coverage plus explicit `fresh`, `stale`, or `unmeasured` coverage health. A completed coverage batch can report zero; absent coverage returns `null` with `unmeasured`; query failures return HTTP 503 with `unavailable`.
Maintainers ingest external contribution coverage and linked restore cases through transactional, idempotent routes protected by a dedicated rotating collector secret. Public responses exclude account, repository, project, checkpoint, restore, contributor, and contribution identifiers. See [the methodology](api-server/docs/adoption-evidence.md) and [collector runbook](api-server/docs/maintainer-collector-runbook.md).
The public [`/maintainers`](https://timemachine.gitgram.app/maintainers) workflow reads the same aggregate through a same-origin, no-store proxy. It runtime-validates the response, separates loading and service failure from measured zero, preserves `unmeasured` nulls, labels stale coverage, and offers a manual refresh. It never sends `ADOPTION_INGESTION_SECRET` to the browser; collection remains a server-side operator task documented in the runbook.
## Quick Start
```bash

View File

@ -32,6 +32,11 @@ WEBSITE_URL=http://localhost:3000
# ── Auth ─────────────────────────────────────────────────────────────────────
# Shared secret for website-to-API internal calls
INTERNAL_SECRET=your-internal-secret-here
# Dedicated maintainer collector secret. Required in staging/production; use a
# random value of at least 32 characters. Set PREVIOUS only during rotation.
ADOPTION_INGESTION_SECRET=replace-with-a-random-32-plus-character-secret
# ADOPTION_INGESTION_SECRET_PREVIOUS=
OSS_COVERAGE_MAX_AGE_HOURS=168
# JWT signing secret (for session tokens)
# JWT_SECRET=
# Clerk webhook secret (for user sync from Clerk)

View File

@ -0,0 +1,74 @@
# Adoption evidence methodology
`GET /v1/adoption/summary` reports aggregate product adoption, OSS contribution, maintainer response, and restore case evidence.
## Evidence sources
- Product adoption comes from the first-party `projects`, `checkpoints`, and `restore_events` tables.
- OSS metrics come from the latest completed `oss_coverage_batches` row and its `oss_contribution_records` rows.
- Case evidence comes from `oss_case_evidence` rows that passed server-side project, checkpoint, and applied restore checks.
The OSS ingestion route accepts external contributions only. It requires `contributorType: "external"` on each record and the database enforces the same value.
## Status rules
- `measured` with `0` means a completed coverage batch found no matching records.
- `unmeasured` with `null` means no completed coverage batch exists.
- `unavailable` means a database query failed. The public route returns HTTP 503 and no metrics.
Restore case evidence has no separate coverage batch. Until at least one checkpoint-to-applied-restore case passes the server consistency checks, its status is `unmeasured` and its counts are `null`; an OSS coverage batch cannot turn missing case evidence into a measured zero.
The response states adoption and OSS window start, end, day count, and status. Product adoption uses a rolling 30-day window. OSS metrics use the latest completed ingestion window.
## Internal ingestion
Both write routes require `X-Internal-Secret`, validated against the dedicated
`ADOPTION_INGESTION_SECRET`. Staging and production fail startup when that
secret is absent or shorter than 32 characters. Development alone may fall
back to `INTERNAL_SECRET`.
Every write also requires an `Idempotency-Key` with 8–128 visible characters
and a bounded `collectorVersion` in the JSON body. The server stores only the
key hash. Repeating the same key and normalized body returns the original row;
reusing a key with a changed body returns HTTP 409. Evidence rows retain their
key hash, so collector keys must never be reused for another logical run.
The same coverage window and collector version are also unique; a corrected
window requires a collector-version bump. For the same window, the latest
completed corrected batch is the deterministic public source.
`POST /v1/adoption/oss-coverage/batches` accepts one bounded coverage window, a positive measured repository count, and up to 5,000 contribution records. Repository, contributor, and contribution keys must be lowercase, secret-keyed HMAC-SHA-256 digests. The ingestion system must keep the HMAC key outside this database. Contribution open times must fall inside the coverage window. First response times cannot precede the contribution open time.
The server creates the batch, inserts every contribution, and marks the batch
completed inside one PostgreSQL transaction. Failure rolls back the entire
batch; no partial `collecting` row becomes visible. A completed batch with an
empty contributions array records a measured zero.
`POST /v1/adoption/case-evidence` accepts an opaque repository key plus existing project, checkpoint, and restore event identifiers. The server records the case only when:
- the checkpoint belongs to the supplied project;
- the restore belongs to the same project;
- the restore has `applied` status;
- the restore target equals the supplied checkpoint.
Case writes are transactional and idempotent by both explicit key and restore
event. A second payload cannot relabel a restore that already has evidence.
## Freshness and health
`oss.freshness` reports `fresh`, `stale`, or `unmeasured`, the age of the latest
completed coverage window, and the configured threshold. The default threshold
is 168 hours and can be changed with `OSS_COVERAGE_MAX_AGE_HOURS`.
`GET /health/adoption` exposes the same check. `/health/ready` is degraded for
stale or unmeasured coverage and unhealthy when the evidence schema/query is
unavailable. A stale batch remains historical measured evidence; it is never
presented as current coverage.
## Public privacy boundary
The public response contains counts, statuses, windows, and aggregate response hours. It never returns account, repository, project, checkpoint, restore, contributor, contribution, path, email, or name fields. Opaque keys remain private.
The website's `/maintainers` route reads this response through `/api/adoption/summary`. That same-origin route does not attach `X-Internal-Secret`, does not cache the response, and rejects malformed response shapes before the browser renders metrics. Internal ingestion stays outside the browser.
Operational collection, credential rotation, replay recovery, and rollback are
documented in `maintainer-collector-runbook.md`.

View File

@ -0,0 +1,88 @@
# Maintainer evidence collector runbook
This runbook operates real adoption evidence. It does not authorize migration
or production deployment by itself.
## Inputs and privacy
Collector input must come from the repository host's real contribution records.
Hash repository, contributor, and contribution identifiers with a dedicated
HMAC-SHA-256 key before JSON reaches this API. Keep that HMAC key separate from
the database and from `ADOPTION_INGESTION_SECRET`. Never include login, name,
email, repository name, title, body, patch, or URL fields.
Each payload must include a version such as
`"collectorVersion": "github-coverage-1.0.0"`. Coverage payloads contain only
the bounded OSS window and opaque contribution rows. Case payloads contain an
opaque repository key plus existing AITimeMachine project, checkpoint, and
applied restore IDs.
## Preflight
1. Confirm migration `0009_add_oss_adoption_evidence` is approved, backed up,
and applied before the new API process starts.
2. Confirm `GET /health/schema` recognizes all three OSS evidence tables.
3. Confirm `GET /health/adoption` is `degraded/unmeasured` before the first batch,
not healthy and not a fabricated zero.
4. Set `ADOPTION_API_URL` to the exact API origin and
`ADOPTION_INGESTION_SECRET` through the operator secret manager.
5. Choose one random idempotency key per logical batch or case and record it
with the source run. Use the same key for every retry of that payload.
Validate the local file without sending it:
```sh
npm run collector:ingest -- coverage ./coverage.json --idempotency-key=coverage-2026-08-23T00:00Z --dry-run
```
## Ingest and verify
Send a coverage batch:
```sh
npm run collector:ingest -- coverage ./coverage.json --idempotency-key=coverage-2026-08-23T00:00Z
```
Send one verified restore case:
```sh
npm run collector:ingest -- case ./case.json --idempotency-key=case-restore-opaque-run-key
```
The first accepted request returns HTTP 201 and `replayed:false`. Repeating the
same key/body returns HTTP 200 and `replayed:true`. A changed body with the same
key must return 409. After coverage ingestion, confirm `/health/adoption` is
fresh and inspect `/v1/adoption/summary` for schema version 2, the intended
window, freshness, and aggregate-only fields.
Never retry a timeout with a new key. Retry the exact file with the original
key; the transaction receipt determines whether the first request committed.
## Secret rotation
1. Generate a new random secret of at least 32 characters in the secret manager.
2. Move the deployed current value to `ADOPTION_INGESTION_SECRET_PREVIOUS` and
deploy the new value as `ADOPTION_INGESTION_SECRET`.
3. Update collectors. A response header
`X-Collector-Key-Rotation: previous-key-accepted` means that operator still
uses the old credential.
4. Observe one complete scheduled collection interval plus retry margin, capped
at 24 hours.
5. Remove `ADOPTION_INGESTION_SECRET_PREVIOUS` and restart. Do not leave the
overlap configured indefinitely.
## Failure and rollback
- HTTP 400: fix the source payload; keep the logical run's key only if the
normalized body is unchanged.
- HTTP 401: stop and repair collector credentials. Do not print the secret.
- HTTP 409: compare the source run with the original request; never force a
second record with a new key until the conflict is understood.
- HTTP 503 or timeout: retain the payload and retry with the same key.
- Stale health: investigate the scheduler/source API before publishing new
claims. Historical aggregates remain labeled stale.
For rollback, stop collectors first. Roll back the API process, then follow the
approved database restore decision. Do not drop evidence tables merely to make
an older process start; retain source files, request IDs, and the backup until
the incident owner closes the review.

View File

@ -0,0 +1,93 @@
-- Privacy-safe, first-party evidence for OSS fellowship reporting.
-- Opaque keys must be secret-keyed HMAC-SHA-256 digests. Public routes expose aggregates only.
CREATE TABLE oss_coverage_batches (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
idempotency_key_hash TEXT NOT NULL,
request_hash TEXT NOT NULL,
request_id TEXT NOT NULL,
collector_version TEXT NOT NULL,
collector_key_slot TEXT NOT NULL,
window_started_at TIMESTAMP NOT NULL,
window_ended_at TIMESTAMP NOT NULL,
status TEXT NOT NULL DEFAULT 'collecting',
repositories_measured INTEGER NOT NULL,
contribution_count INTEGER NOT NULL,
completed_at TIMESTAMP,
created_at TIMESTAMP NOT NULL DEFAULT now(),
CONSTRAINT oss_coverage_window_order CHECK (window_ended_at > window_started_at),
CONSTRAINT oss_coverage_idempotency_hash CHECK (idempotency_key_hash ~ '^[0-9a-f]{64}$'),
CONSTRAINT oss_coverage_request_hash CHECK (request_hash ~ '^[0-9a-f]{64}$'),
CONSTRAINT oss_coverage_request_id CHECK (length(request_id) BETWEEN 1 AND 128),
CONSTRAINT oss_coverage_collector_version CHECK (collector_version ~ '^[A-Za-z0-9._-]{1,64}$'),
CONSTRAINT oss_coverage_collector_key_slot CHECK (collector_key_slot IN ('current', 'previous')),
CONSTRAINT oss_coverage_status CHECK (status IN ('collecting', 'completed', 'failed')),
CONSTRAINT oss_coverage_repository_count CHECK (repositories_measured > 0),
CONSTRAINT oss_coverage_contribution_count CHECK (contribution_count >= 0),
CONSTRAINT oss_coverage_completion CHECK (
(status = 'completed' AND completed_at IS NOT NULL) OR
(status <> 'completed' AND completed_at IS NULL)
)
);
CREATE INDEX idx_oss_coverage_status_window
ON oss_coverage_batches (status, window_ended_at);
CREATE UNIQUE INDEX idx_oss_coverage_idempotency
ON oss_coverage_batches (idempotency_key_hash);
CREATE UNIQUE INDEX idx_oss_coverage_window_version
ON oss_coverage_batches (window_started_at, window_ended_at, collector_version);
CREATE TABLE oss_contribution_records (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
batch_id UUID NOT NULL REFERENCES oss_coverage_batches(id) ON DELETE CASCADE,
repository_key TEXT NOT NULL,
contributor_key TEXT NOT NULL,
contributor_type TEXT NOT NULL DEFAULT 'external',
contribution_key TEXT NOT NULL,
opened_at TIMESTAMP NOT NULL,
first_maintainer_response_at TIMESTAMP,
created_at TIMESTAMP NOT NULL DEFAULT now(),
CONSTRAINT oss_contribution_repository_key CHECK (repository_key ~ '^[0-9a-f]{64}$'),
CONSTRAINT oss_contribution_contributor_key CHECK (contributor_key ~ '^[0-9a-f]{64}$'),
CONSTRAINT oss_contribution_external_only CHECK (contributor_type = 'external'),
CONSTRAINT oss_contribution_key CHECK (contribution_key ~ '^[0-9a-f]{64}$'),
CONSTRAINT oss_contribution_response_order CHECK (
first_maintainer_response_at IS NULL OR first_maintainer_response_at >= opened_at
)
);
CREATE INDEX idx_oss_contributions_batch
ON oss_contribution_records (batch_id);
CREATE INDEX idx_oss_contributions_batch_contributor
ON oss_contribution_records (batch_id, contributor_key);
CREATE UNIQUE INDEX idx_oss_contributions_batch_contribution
ON oss_contribution_records (batch_id, contribution_key);
CREATE TABLE oss_case_evidence (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
idempotency_key_hash TEXT NOT NULL,
request_hash TEXT NOT NULL,
request_id TEXT NOT NULL,
collector_version TEXT NOT NULL,
collector_key_slot TEXT NOT NULL,
repository_key TEXT NOT NULL,
project_id TEXT NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
checkpoint_id TEXT NOT NULL REFERENCES checkpoints(id) ON DELETE CASCADE,
restore_event_id UUID NOT NULL REFERENCES restore_events(id) ON DELETE CASCADE,
recorded_at TIMESTAMP NOT NULL DEFAULT now(),
CONSTRAINT oss_case_repository_key CHECK (repository_key ~ '^[0-9a-f]{64}$'),
CONSTRAINT oss_case_idempotency_hash CHECK (idempotency_key_hash ~ '^[0-9a-f]{64}$'),
CONSTRAINT oss_case_request_hash CHECK (request_hash ~ '^[0-9a-f]{64}$'),
CONSTRAINT oss_case_request_id CHECK (length(request_id) BETWEEN 1 AND 128),
CONSTRAINT oss_case_collector_version CHECK (collector_version ~ '^[A-Za-z0-9._-]{1,64}$'),
CONSTRAINT oss_case_collector_key_slot CHECK (collector_key_slot IN ('current', 'previous'))
);
CREATE INDEX idx_oss_case_evidence_repository
ON oss_case_evidence (repository_key);
CREATE UNIQUE INDEX idx_oss_case_evidence_idempotency
ON oss_case_evidence (idempotency_key_hash);
CREATE INDEX idx_oss_case_evidence_project
ON oss_case_evidence (project_id);
CREATE UNIQUE INDEX idx_oss_case_evidence_restore
ON oss_case_evidence (restore_event_id);

View File

@ -57,6 +57,13 @@
"when": 1771180300000,
"tag": "0008_add_checkpoint_test_status",
"breakpoints": true
},
{
"idx": 8,
"version": "7",
"when": 1787529600000,
"tag": "0009_add_oss_adoption_evidence",
"breakpoints": true
}
]
}

View File

@ -22,7 +22,8 @@
"test:integration:safe": "node scripts/run-integration-safe.mjs",
"eval:universal-search": "tsx scripts/universal-search-eval.ts",
"worker:delete-requests": "tsx scripts/process-delete-requests.ts",
"worker:retention": "tsx scripts/process-retention.ts"
"worker:retention": "tsx scripts/process-retention.ts",
"collector:ingest": "node scripts/ingest-adoption-evidence.mjs"
},
"dependencies": {
"@a2a-js/sdk": "^0.3.13",

View File

@ -0,0 +1,70 @@
#!/usr/bin/env node
import { readFile } from "node:fs/promises";
const MAX_PAYLOAD_BYTES = 5 * 1024 * 1024;
const [kind, inputPath, ...flags] = process.argv.slice(2);
const routes = {
coverage: "/v1/adoption/oss-coverage/batches",
case: "/v1/adoption/case-evidence",
};
function fail(message) {
process.stderr.write(`${message}\n`);
process.exitCode = 1;
}
if (!(kind in routes) || !inputPath) {
fail("Usage: ingest-adoption-evidence.mjs <coverage|case> <payload.json> --idempotency-key=<stable-key> [--dry-run]");
} else {
const idempotencyFlag = flags.find((flag) => flag.startsWith("--idempotency-key="));
const idempotencyKey = idempotencyFlag?.slice("--idempotency-key=".length) || "";
const dryRun = flags.includes("--dry-run");
const apiUrl = process.env.ADOPTION_API_URL || "";
const secret = process.env.ADOPTION_INGESTION_SECRET || "";
try {
const bytes = await readFile(inputPath);
if (bytes.byteLength > MAX_PAYLOAD_BYTES) throw new Error("Payload exceeds the 5 MiB operator limit");
const payload = JSON.parse(bytes.toString("utf8"));
if (!payload || typeof payload !== "object" || Array.isArray(payload)) throw new Error("Payload must be a JSON object");
if (typeof payload.collectorVersion !== "string" || payload.collectorVersion.length === 0) {
throw new Error("Payload must include collectorVersion");
}
if (idempotencyKey.length < 8 || idempotencyKey.length > 128 || !/^[\x21-\x7e]+$/.test(idempotencyKey)) {
throw new Error("Provide a stable 8-128 character --idempotency-key");
}
if (dryRun) {
process.stdout.write(JSON.stringify({ validJson: true, kind, bytes: bytes.byteLength, collectorVersion: payload.collectorVersion }) + "\n");
} else {
if (!apiUrl || !secret) throw new Error("ADOPTION_API_URL and ADOPTION_INGESTION_SECRET are required");
const base = new URL(apiUrl);
const local = base.hostname === "localhost" || base.hostname === "127.0.0.1" || base.hostname === "::1";
if (base.protocol !== "https:" && !(local && base.protocol === "http:")) {
throw new Error("ADOPTION_API_URL must use HTTPS outside localhost");
}
const response = await fetch(new URL(routes[kind], base), {
method: "POST",
redirect: "error",
signal: AbortSignal.timeout(20_000),
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"Idempotency-Key": idempotencyKey,
"X-Internal-Secret": secret,
},
body: JSON.stringify(payload),
});
const body = await response.text();
if (!response.ok) throw new Error(`Collector API returned HTTP ${response.status}: ${body.slice(0, 1000)}`);
if (response.headers.get("x-collector-key-rotation") === "previous-key-accepted") {
process.stderr.write("Warning: the previous collector key was accepted; update this operator environment to the current key.\n");
}
process.stdout.write(`${body}\n`);
}
} catch (error) {
fail(error instanceof Error ? error.message : "Adoption evidence ingestion failed");
}
}

View File

@ -55,6 +55,13 @@ const envSchema = z.object({
.string()
.optional()
.describe("Shared secret for website-to-API internal calls"),
ADOPTION_INGESTION_SECRET: z.string().min(32).optional()
.describe("Current dedicated secret for adoption evidence collectors"),
ADOPTION_INGESTION_SECRET_PREVIOUS: z.string().min(32).optional()
.describe("Previous collector secret accepted during a bounded rotation"),
OSS_COVERAGE_MAX_AGE_HOURS: z.string().default("168").transform(Number)
.pipe(z.number().int().min(1).max(8760))
.describe("Maximum age of the latest OSS coverage window before it is stale"),
JWT_SECRET: z
.string()
.optional()

View File

@ -36,4 +36,15 @@ if (isNeonUrl) {
export const db: Database = dbInstance;
// Adoption ingestion needs an interactive transaction. Neon HTTP is optimized
// for single/non-interactive requests, so keep the read path on HTTP while
// using one small node-postgres pool for atomic collector writes.
const transactionPool = new Pool({
connectionString,
max: 4,
idleTimeoutMillis: 30_000,
connectionTimeoutMillis: 5_000,
});
export const transactionDb = drizzlePg(transactionPool, { schema });
export { schema };

View File

@ -10,6 +10,7 @@ import {
numeric,
primaryKey,
index,
uniqueIndex,
} from "drizzle-orm/pg-core";
// ============================================
@ -1422,3 +1423,99 @@ export const a2aMessages = pgTable(
),
})
);
// ============================================
// OSS ADOPTION EVIDENCE
// ============================================
export const ossCoverageBatches = pgTable(
"oss_coverage_batches",
{
id: uuid("id").primaryKey().defaultRandom(),
idempotencyKeyHash: text("idempotency_key_hash").notNull(),
requestHash: text("request_hash").notNull(),
requestId: text("request_id").notNull(),
collectorVersion: text("collector_version").notNull(),
collectorKeySlot: text("collector_key_slot").notNull(),
windowStartedAt: timestamp("window_started_at").notNull(),
windowEndedAt: timestamp("window_ended_at").notNull(),
status: text("status").notNull().default("collecting"), // collecting | completed | failed
repositoriesMeasured: integer("repositories_measured").notNull(),
contributionCount: integer("contribution_count").notNull(),
completedAt: timestamp("completed_at"),
createdAt: timestamp("created_at").defaultNow().notNull(),
},
(table) => ({
idempotencyUnique: uniqueIndex("idx_oss_coverage_idempotency").on(
table.idempotencyKeyHash
),
windowVersionUnique: uniqueIndex("idx_oss_coverage_window_version").on(
table.windowStartedAt,
table.windowEndedAt,
table.collectorVersion
),
statusWindowIdx: index("idx_oss_coverage_status_window").on(
table.status,
table.windowEndedAt
),
})
);
export const ossContributionRecords = pgTable(
"oss_contribution_records",
{
id: uuid("id").primaryKey().defaultRandom(),
batchId: uuid("batch_id")
.references(() => ossCoverageBatches.id, { onDelete: "cascade" })
.notNull(),
repositoryKey: text("repository_key").notNull(),
contributorKey: text("contributor_key").notNull(),
contributorType: text("contributor_type").notNull().default("external"),
contributionKey: text("contribution_key").notNull(),
openedAt: timestamp("opened_at").notNull(),
firstMaintainerResponseAt: timestamp("first_maintainer_response_at"),
createdAt: timestamp("created_at").defaultNow().notNull(),
},
(table) => ({
batchIdx: index("idx_oss_contributions_batch").on(table.batchId),
batchContributorIdx: index("idx_oss_contributions_batch_contributor").on(
table.batchId,
table.contributorKey
),
batchContributionUnique: uniqueIndex("idx_oss_contributions_batch_contribution").on(
table.batchId,
table.contributionKey
),
})
);
export const ossCaseEvidence = pgTable(
"oss_case_evidence",
{
id: uuid("id").primaryKey().defaultRandom(),
idempotencyKeyHash: text("idempotency_key_hash").notNull(),
requestHash: text("request_hash").notNull(),
requestId: text("request_id").notNull(),
collectorVersion: text("collector_version").notNull(),
collectorKeySlot: text("collector_key_slot").notNull(),
repositoryKey: text("repository_key").notNull(),
projectId: text("project_id")
.references(() => projects.id, { onDelete: "cascade" })
.notNull(),
checkpointId: text("checkpoint_id")
.references(() => checkpoints.id, { onDelete: "cascade" })
.notNull(),
restoreEventId: uuid("restore_event_id")
.references(() => restoreEvents.id, { onDelete: "cascade" })
.notNull(),
recordedAt: timestamp("recorded_at").defaultNow().notNull(),
},
(table) => ({
idempotencyUnique: uniqueIndex("idx_oss_case_evidence_idempotency").on(
table.idempotencyKeyHash
),
repositoryIdx: index("idx_oss_case_evidence_repository").on(table.repositoryKey),
projectIdx: index("idx_oss_case_evidence_project").on(table.projectId),
restoreUnique: uniqueIndex("idx_oss_case_evidence_restore").on(table.restoreEventId),
})
);

View File

@ -819,6 +819,70 @@ export const EXPECTED_TABLES: Record<
],
indexes: ["trend_scores_pkey", "idx_trend_scores_repo_window"],
},
oss_coverage_batches: {
columns: [
"id",
"idempotency_key_hash",
"request_hash",
"request_id",
"collector_version",
"collector_key_slot",
"window_started_at",
"window_ended_at",
"status",
"repositories_measured",
"contribution_count",
"completed_at",
"created_at",
],
indexes: [
"oss_coverage_batches_pkey",
"idx_oss_coverage_idempotency",
"idx_oss_coverage_window_version",
"idx_oss_coverage_status_window",
],
},
oss_contribution_records: {
columns: [
"id",
"batch_id",
"repository_key",
"contributor_key",
"contributor_type",
"contribution_key",
"opened_at",
"first_maintainer_response_at",
"created_at",
],
indexes: [
"oss_contribution_records_pkey",
"idx_oss_contributions_batch",
"idx_oss_contributions_batch_contributor",
"idx_oss_contributions_batch_contribution",
],
},
oss_case_evidence: {
columns: [
"id",
"idempotency_key_hash",
"request_hash",
"request_id",
"collector_version",
"collector_key_slot",
"repository_key",
"project_id",
"checkpoint_id",
"restore_event_id",
"recorded_at",
],
indexes: [
"oss_case_evidence_pkey",
"idx_oss_case_evidence_idempotency",
"idx_oss_case_evidence_repository",
"idx_oss_case_evidence_project",
"idx_oss_case_evidence_restore",
],
},
};
/** Drizzle migration tags that should be present in the database */
@ -827,6 +891,11 @@ export const EXPECTED_MIGRATIONS = [
"0002_add_knowledge_base_tables",
"0003_add_canonical_time_context_governance",
"0004_add_gitgram_social_layer",
"0005_add_saved_context_source",
"0006_add_user_settings",
"0007_add_a2a_tables",
"0008_add_checkpoint_test_status",
"0009_add_oss_adoption_evidence",
];
// ============================================================================

View File

@ -48,6 +48,7 @@ import gitNexusRoutes from "./routes/gitnexus.js";
import context7Routes from "./routes/context7.js";
import sharingRoutes from "./routes/sharing.js";
import teamsRoutes from "./routes/teams.js";
import adoptionRoutes from "./routes/adoption.js";
import { errorHandler, notFoundHandler, wrapErrorMessage } from "./middleware/errors.js";
import { combinedRateLimit, rateLimits } from "./middleware/rate-limit.js";
import { requestLogger, logger, logError } from "./lib/monitoring.js";
@ -161,6 +162,7 @@ app.get("/v1", (req, res) => {
context7: "/v1/context7",
sharing: "/v1/shared",
teams: "/v1/teams",
adoption: "/v1/adoption/summary",
},
documentation: "/docs",
});
@ -227,6 +229,7 @@ app.use("/v1/gitnexus", gitNexusRoutes);
app.use("/v1/context7", context7Routes);
app.use("/v1", sharingRoutes);
app.use("/v1/teams", teamsRoutes);
app.use("/v1/adoption", adoptionRoutes);
// Versioned internal namespace. The internal endpoints (website-internal admin/
// pipeline/knowledge ops) are guarded by internalAuth. Exposed under /v1 as well
// as the legacy /api/internal so clients fully migrated to /v1 can reach them.

View File

@ -0,0 +1,45 @@
import crypto from "node:crypto";
import type { NextFunction, Request, Response } from "express";
import { logger } from "../lib/monitoring.js";
export interface AdoptionIngestionRequest extends Request {
collectorKeySlot?: "current" | "previous";
}
function matchesSecret(candidate: string, expected: string): boolean {
const candidateHash = crypto.createHash("sha256").update(candidate, "utf8").digest();
const expectedHash = crypto.createHash("sha256").update(expected, "utf8").digest();
return crypto.timingSafeEqual(candidateHash, expectedHash);
}
export function adoptionIngestionAuth(
req: AdoptionIngestionRequest,
res: Response,
next: NextFunction
) {
const supplied = req.get("x-internal-secret") || "";
const strictEnvironment = process.env.NODE_ENV === "production" || process.env.NODE_ENV === "staging";
const current = process.env.ADOPTION_INGESTION_SECRET
|| (!strictEnvironment ? process.env.INTERNAL_SECRET : undefined);
const previous = process.env.ADOPTION_INGESTION_SECRET_PREVIOUS;
res.setHeader("Cache-Control", "no-store");
if (!current) {
logger.error("ADOPTION_INGESTION_SECRET not configured", undefined, {
source: "adoption-ingestion-auth",
});
return res.status(503).json({ error: "Adoption ingestion is not configured" });
}
if (supplied && matchesSecret(supplied, current)) {
req.collectorKeySlot = "current";
return next();
}
if (supplied && previous && matchesSecret(supplied, previous)) {
req.collectorKeySlot = "previous";
res.setHeader("X-Collector-Key-Rotation", "previous-key-accepted");
return next();
}
return res.status(401).json({ error: "Invalid adoption ingestion credential" });
}

View File

@ -0,0 +1,688 @@
import crypto from "node:crypto";
import { Router, type Response } from "express";
import { and, count, countDistinct, desc, eq, gte, min } from "drizzle-orm";
import { z } from "zod";
import { db, schema, transactionDb } from "../db/index.js";
import { logger } from "../lib/monitoring.js";
import { evaluateCoverageFreshness } from "../services/adoptionEvidenceHealth.js";
import {
adoptionIngestionAuth,
type AdoptionIngestionRequest,
} from "../middleware/adoptionIngestionAuth.js";
const router = Router();
const DAY_MS = 24 * 60 * 60 * 1000;
const OPAQUE_KEY = /^[0-9a-f]{64}$/;
const coverageBatchSchema = z
.object({
collectorVersion: z.string().trim().min(1).max(64).regex(/^[a-zA-Z0-9._-]+$/),
windowStartedAt: z.coerce.date(),
windowEndedAt: z.coerce.date(),
repositoriesMeasured: z.number().int().positive().max(1_000_000),
contributions: z
.array(
z.object({
repositoryKey: z.string().regex(OPAQUE_KEY),
contributorKey: z.string().regex(OPAQUE_KEY),
contributorType: z.literal("external"),
contributionKey: z.string().regex(OPAQUE_KEY),
openedAt: z.coerce.date(),
firstMaintainerResponseAt: z.coerce.date().nullable().optional(),
}).strict()
)
.max(5000),
}).strict()
.superRefine((batch, context) => {
if (batch.windowEndedAt <= batch.windowStartedAt) {
context.addIssue({
code: z.ZodIssueCode.custom,
path: ["windowEndedAt"],
message: "windowEndedAt must be after windowStartedAt",
});
}
if (batch.windowEndedAt.getTime() > Date.now() + 5 * 60 * 1000) {
context.addIssue({
code: z.ZodIssueCode.custom,
path: ["windowEndedAt"],
message: "windowEndedAt cannot be more than five minutes in the future",
});
}
if (batch.windowEndedAt.getTime() - batch.windowStartedAt.getTime() > 366 * DAY_MS) {
context.addIssue({
code: z.ZodIssueCode.custom,
path: ["windowStartedAt"],
message: "coverage window cannot exceed 366 days",
});
}
const repositoryKeys = new Set<string>();
const contributionKeys = new Set<string>();
for (const [index, contribution] of batch.contributions.entries()) {
repositoryKeys.add(contribution.repositoryKey);
if (contributionKeys.has(contribution.contributionKey)) {
context.addIssue({
code: z.ZodIssueCode.custom,
path: ["contributions", index, "contributionKey"],
message: "contributionKey must be unique within a batch",
});
}
contributionKeys.add(contribution.contributionKey);
if (
contribution.openedAt < batch.windowStartedAt ||
contribution.openedAt > batch.windowEndedAt
) {
context.addIssue({
code: z.ZodIssueCode.custom,
path: ["contributions", index, "openedAt"],
message: "openedAt must fall inside the coverage window",
});
}
if (
contribution.firstMaintainerResponseAt &&
contribution.firstMaintainerResponseAt < contribution.openedAt
) {
context.addIssue({
code: z.ZodIssueCode.custom,
path: ["contributions", index, "firstMaintainerResponseAt"],
message: "firstMaintainerResponseAt cannot precede openedAt",
});
}
}
if (repositoryKeys.size > batch.repositoriesMeasured) {
context.addIssue({
code: z.ZodIssueCode.custom,
path: ["repositoriesMeasured"],
message: "repositoriesMeasured cannot be lower than the contributed repository count",
});
}
});
const caseEvidenceSchema = z.object({
collectorVersion: z.string().trim().min(1).max(64).regex(/^[a-zA-Z0-9._-]+$/),
repositoryKey: z.string().regex(OPAQUE_KEY),
projectId: z.string().min(1).max(255),
checkpointId: z.string().min(1).max(255),
restoreEventId: z.string().uuid(),
}).strict();
class IngestionConflict extends Error {}
function requireIdempotencyKey(req: AdoptionIngestionRequest): string {
const value = req.get("idempotency-key")?.trim() || "";
if (value.length < 8 || value.length > 128 || !/^[\x21-\x7e]+$/.test(value)) {
throw new z.ZodError([{
code: z.ZodIssueCode.custom,
path: ["Idempotency-Key"],
message: "Idempotency-Key must contain 8 to 128 visible characters",
}]);
}
return value;
}
function sha256(value: string): string {
return crypto.createHash("sha256").update(value, "utf8").digest("hex");
}
function requestId(res: Response): string {
return String(res.getHeader("X-Request-Id") || crypto.randomUUID()).slice(0, 128);
}
function coverageRequestHash(batch: z.infer<typeof coverageBatchSchema>): string {
return sha256(JSON.stringify({
collectorVersion: batch.collectorVersion,
windowStartedAt: batch.windowStartedAt.toISOString(),
windowEndedAt: batch.windowEndedAt.toISOString(),
repositoriesMeasured: batch.repositoriesMeasured,
contributions: batch.contributions.map((record) => ({
repositoryKey: record.repositoryKey,
contributorKey: record.contributorKey,
contributorType: record.contributorType,
contributionKey: record.contributionKey,
openedAt: record.openedAt.toISOString(),
firstMaintainerResponseAt: record.firstMaintainerResponseAt?.toISOString() ?? null,
})),
}));
}
function caseRequestHash(evidence: z.infer<typeof caseEvidenceSchema>): string {
return sha256(JSON.stringify({
collectorVersion: evidence.collectorVersion,
repositoryKey: evidence.repositoryKey,
projectId: evidence.projectId,
checkpointId: evidence.checkpointId,
restoreEventId: evidence.restoreEventId,
}));
}
function setReplayHeader(res: Response, replayed: boolean) {
res.setHeader("Idempotency-Replayed", String(replayed));
}
function isUniqueViolation(error: unknown): boolean {
if (typeof error !== "object" || error === null) return false;
if ("code" in error && (error as { code?: unknown }).code === "23505") return true;
return "cause" in error && isUniqueViolation((error as { cause?: unknown }).cause);
}
function asNumber(value: unknown): number {
const parsed = Number(value ?? 0);
return Number.isFinite(parsed) ? parsed : 0;
}
function windowDays(startsAt: Date, endsAt: Date): number {
return Math.max(1, Math.ceil((endsAt.getTime() - startsAt.getTime()) / DAY_MS));
}
/**
* Public aggregate evidence. The response contains no account, repository,
* project, checkpoint, restore, contributor, or contribution identifiers.
*/
router.get("/summary", async (_req, res: Response) => {
const generatedAt = new Date();
const adoptionDays = 30;
const adoptionStart = new Date(generatedAt.getTime() - adoptionDays * DAY_MS);
try {
const [
[activeDevelopers],
[lifetimeDevelopers],
[lifetimeProjects],
[lifetimeCheckpoints],
[recentCheckpoints],
[lifetimeRestores],
[recentRestores],
[firstCheckpoint],
[latestCoverage],
[caseCounts],
] = await Promise.all([
db
.select({ value: countDistinct(schema.checkpoints.userId) })
.from(schema.checkpoints)
.where(gte(schema.checkpoints.createdAt, adoptionStart)),
db.select({ value: countDistinct(schema.checkpoints.userId) }).from(schema.checkpoints),
db.select({ value: count() }).from(schema.projects),
db.select({ value: count() }).from(schema.checkpoints),
db
.select({ value: count() })
.from(schema.checkpoints)
.where(gte(schema.checkpoints.createdAt, adoptionStart)),
db
.select({ value: count() })
.from(schema.restoreEvents)
.where(eq(schema.restoreEvents.status, "applied")),
db
.select({ value: count() })
.from(schema.restoreEvents)
.where(
and(
eq(schema.restoreEvents.status, "applied"),
gte(schema.restoreEvents.createdAt, adoptionStart)
)
),
db.select({ value: min(schema.checkpoints.createdAt) }).from(schema.checkpoints),
db
.select({
id: schema.ossCoverageBatches.id,
startsAt: schema.ossCoverageBatches.windowStartedAt,
endsAt: schema.ossCoverageBatches.windowEndedAt,
completedAt: schema.ossCoverageBatches.completedAt,
repositoriesMeasured: schema.ossCoverageBatches.repositoriesMeasured,
contributionCount: schema.ossCoverageBatches.contributionCount,
})
.from(schema.ossCoverageBatches)
.where(eq(schema.ossCoverageBatches.status, "completed"))
.orderBy(
desc(schema.ossCoverageBatches.windowEndedAt),
desc(schema.ossCoverageBatches.completedAt)
)
.limit(1),
db
.select({
cases: count(),
repositories: countDistinct(schema.ossCaseEvidence.repositoryKey),
projects: countDistinct(schema.ossCaseEvidence.projectId),
})
.from(schema.ossCaseEvidence),
]);
let ossWindow: {
startsAt: string | null;
endsAt: string | null;
days: number | null;
status: "measured" | "unmeasured";
} = { startsAt: null, endsAt: null, days: null, status: "unmeasured" };
let externalContributors: number | null = null;
let repeatContributors: number | null = null;
let contributionsReceived: number | null = null;
let responsesSent: number | null = null;
let awaitingResponse: number | null = null;
let averageFirstResponseHours: number | null = null;
let repositoriesMeasured: number | null = null;
if (latestCoverage) {
const records = await db
.select({
contributorKey: schema.ossContributionRecords.contributorKey,
openedAt: schema.ossContributionRecords.openedAt,
respondedAt: schema.ossContributionRecords.firstMaintainerResponseAt,
})
.from(schema.ossContributionRecords)
.where(
and(
eq(schema.ossContributionRecords.batchId, latestCoverage.id),
eq(schema.ossContributionRecords.contributorType, "external")
)
);
if (records.length !== latestCoverage.contributionCount) {
throw new Error("Completed OSS coverage batch record count does not match its receipt");
}
const contributorCounts = new Map<string, number>();
let responseHours = 0;
responsesSent = 0;
for (const record of records) {
contributorCounts.set(
record.contributorKey,
(contributorCounts.get(record.contributorKey) ?? 0) + 1
);
if (record.respondedAt) {
responsesSent += 1;
responseHours +=
(record.respondedAt.getTime() - record.openedAt.getTime()) / (60 * 60 * 1000);
}
}
ossWindow = {
startsAt: latestCoverage.startsAt.toISOString(),
endsAt: latestCoverage.endsAt.toISOString(),
days: windowDays(latestCoverage.startsAt, latestCoverage.endsAt),
status: "measured",
};
repositoriesMeasured = latestCoverage.repositoriesMeasured;
externalContributors = contributorCounts.size;
repeatContributors = [...contributorCounts.values()].filter((value) => value > 1).length;
contributionsReceived = records.length;
awaitingResponse = records.length - responsesSent;
averageFirstResponseHours =
responsesSent > 0 ? Math.round((responseHours / responsesSent) * 10) / 10 : null;
}
res.setHeader("Cache-Control", "public, max-age=300, stale-while-revalidate=3600");
res.setHeader("X-Adoption-Evidence-Schema", "2");
const coverageFreshness = evaluateCoverageFreshness(
latestCoverage
? { windowEndedAt: latestCoverage.endsAt, completedAt: latestCoverage.completedAt }
: undefined,
generatedAt
);
return res.json({
schemaVersion: 2,
status: "measured",
generatedAt: generatedAt.toISOString(),
period: {
days: adoptionDays,
startsAt: adoptionStart.toISOString(),
endsAt: generatedAt.toISOString(),
status: "measured",
},
windows: {
adoption: {
startsAt: adoptionStart.toISOString(),
endsAt: generatedAt.toISOString(),
days: adoptionDays,
status: "measured",
},
oss: ossWindow,
},
activeDevelopers: asNumber(activeDevelopers?.value),
lifetimeDevelopers: asNumber(lifetimeDevelopers?.value),
projects: asNumber(lifetimeProjects?.value),
checkpoints: {
lifetime: asNumber(lifetimeCheckpoints?.value),
period: asNumber(recentCheckpoints?.value),
},
appliedRestores: {
lifetime: asNumber(lifetimeRestores?.value),
period: asNumber(recentRestores?.value),
},
firstCheckpointAt: firstCheckpoint?.value?.toISOString() ?? null,
oss: {
status: ossWindow.status,
freshness: coverageFreshness,
repositoriesMeasured,
externalContributors,
repeatContributors,
maintainerResponseLoad: {
contributionsReceived,
responsesSent,
awaitingResponse,
averageFirstResponseHours,
},
},
caseEvidence: (() => {
const cases = asNumber(caseCounts?.cases);
const status = cases > 0 ? "measured" : "unmeasured";
return {
status,
cases: status === "measured" ? cases : null,
repositoriesCovered:
status === "measured" ? asNumber(caseCounts?.repositories) : null,
projectsCovered: status === "measured" ? asNumber(caseCounts?.projects) : null,
};
})(),
methodology: {
source: "AITimeMachine cloud sync and maintainer evidence database",
activeDeveloper: "Distinct account with at least one checkpoint in the adoption window",
externalContributor: "Distinct opaque contributor key in the latest completed OSS coverage batch",
repeatContributor: "Opaque contributor key with two or more contribution records in that batch",
maintainerResponse: "First maintainer response time for external contributions opened in that batch",
caseEvidence: "Applied restore linked to a checkpoint and project after server-side consistency checks; no rows is unmeasured, not zero",
restore: "Restore event whose status is applied",
privacy:
"Aggregate counts only; no account, repository, project, checkpoint, restore, contributor, or contribution identifiers",
},
});
} catch (error) {
logger.error(
"Public adoption summary failed",
error instanceof Error ? error : undefined,
{ details: String(error) }
);
return res.status(503).json({
status: "unavailable",
error: {
message: "Adoption evidence is temporarily unavailable",
type: "service_unavailable",
},
});
}
});
router.post("/oss-coverage/batches", adoptionIngestionAuth, async (req: AdoptionIngestionRequest, res) => {
let replayFingerprint: { idempotencyKeyHash: string; requestHash: string } | null = null;
try {
const idempotencyKeyHash = sha256(requireIdempotencyKey(req));
const batch = coverageBatchSchema.parse(req.body);
const requestHash = coverageRequestHash(batch);
replayFingerprint = { idempotencyKeyHash, requestHash };
const [existing] = await db
.select({
id: schema.ossCoverageBatches.id,
requestHash: schema.ossCoverageBatches.requestHash,
status: schema.ossCoverageBatches.status,
completedAt: schema.ossCoverageBatches.completedAt,
contributionCount: schema.ossCoverageBatches.contributionCount,
})
.from(schema.ossCoverageBatches)
.where(eq(schema.ossCoverageBatches.idempotencyKeyHash, idempotencyKeyHash))
.limit(1);
if (existing) {
if (existing.requestHash !== requestHash) throw new IngestionConflict("Idempotency-Key was already used with a different coverage batch");
if (existing.status !== "completed" || !existing.completedAt) throw new IngestionConflict("Coverage batch is not in a replayable state");
setReplayHeader(res, true);
return res.status(200).json({
recorded: true,
replayed: true,
batchId: existing.id,
contributionCount: existing.contributionCount,
completedAt: existing.completedAt.toISOString(),
});
}
const result = await transactionDb.transaction(async (tx) => {
const [duplicate] = await tx
.select({
id: schema.ossCoverageBatches.id,
requestHash: schema.ossCoverageBatches.requestHash,
status: schema.ossCoverageBatches.status,
completedAt: schema.ossCoverageBatches.completedAt,
contributionCount: schema.ossCoverageBatches.contributionCount,
})
.from(schema.ossCoverageBatches)
.where(eq(schema.ossCoverageBatches.idempotencyKeyHash, idempotencyKeyHash))
.limit(1);
if (duplicate) {
if (duplicate.requestHash !== requestHash) throw new IngestionConflict("Idempotency-Key was already used with a different coverage batch");
if (duplicate.status !== "completed" || !duplicate.completedAt) throw new IngestionConflict("Coverage batch is not in a replayable state");
return { ...duplicate, replayed: true };
}
const [createdBatch] = await tx
.insert(schema.ossCoverageBatches)
.values({
idempotencyKeyHash,
requestHash,
requestId: requestId(res),
collectorVersion: batch.collectorVersion,
collectorKeySlot: req.collectorKeySlot || "current",
windowStartedAt: batch.windowStartedAt,
windowEndedAt: batch.windowEndedAt,
status: "collecting",
repositoriesMeasured: batch.repositoriesMeasured,
contributionCount: batch.contributions.length,
})
.returning({ id: schema.ossCoverageBatches.id });
if (batch.contributions.length > 0) {
await tx.insert(schema.ossContributionRecords).values(
batch.contributions.map((contribution) => ({
batchId: createdBatch.id,
repositoryKey: contribution.repositoryKey,
contributorKey: contribution.contributorKey,
contributorType: contribution.contributorType,
contributionKey: contribution.contributionKey,
openedAt: contribution.openedAt,
firstMaintainerResponseAt: contribution.firstMaintainerResponseAt ?? null,
}))
);
}
const completedAt = new Date();
await tx
.update(schema.ossCoverageBatches)
.set({ status: "completed", completedAt })
.where(eq(schema.ossCoverageBatches.id, createdBatch.id));
return {
id: createdBatch.id,
contributionCount: batch.contributions.length,
completedAt,
replayed: false,
};
});
setReplayHeader(res, result.replayed);
return res.status(result.replayed ? 200 : 201).json({
recorded: true,
replayed: result.replayed,
batchId: result.id,
contributionCount: result.contributionCount,
completedAt: result.completedAt.toISOString(),
});
} catch (error) {
if (error instanceof z.ZodError) {
return res.status(400).json({ error: "Invalid OSS coverage batch", details: error.issues });
}
if (error instanceof IngestionConflict) {
return res.status(409).json({ error: error.message });
}
if (isUniqueViolation(error)) {
if (replayFingerprint) {
try {
const [winner] = await db
.select({
id: schema.ossCoverageBatches.id,
requestHash: schema.ossCoverageBatches.requestHash,
status: schema.ossCoverageBatches.status,
completedAt: schema.ossCoverageBatches.completedAt,
contributionCount: schema.ossCoverageBatches.contributionCount,
})
.from(schema.ossCoverageBatches)
.where(eq(schema.ossCoverageBatches.idempotencyKeyHash, replayFingerprint.idempotencyKeyHash))
.limit(1);
if (winner?.requestHash === replayFingerprint.requestHash && winner.status === "completed" && winner.completedAt) {
setReplayHeader(res, true);
return res.status(200).json({
recorded: true,
replayed: true,
batchId: winner.id,
contributionCount: winner.contributionCount,
completedAt: winner.completedAt.toISOString(),
});
}
} catch {
return res.status(503).json({ error: "Coverage replay could not be resolved" });
}
}
return res.status(409).json({ error: "Concurrent coverage ingestion conflicted; retry with the same Idempotency-Key" });
}
logger.error(
"OSS coverage ingestion failed",
error instanceof Error ? error : undefined,
{ details: String(error) }
);
return res.status(503).json({ error: "OSS coverage batch was not completed" });
}
});
router.post("/case-evidence", adoptionIngestionAuth, async (req: AdoptionIngestionRequest, res) => {
let replayFingerprint: { idempotencyKeyHash: string; requestHash: string; restoreEventId: string } | null = null;
try {
const idempotencyKeyHash = sha256(requireIdempotencyKey(req));
const evidence = caseEvidenceSchema.parse(req.body);
const requestHash = caseRequestHash(evidence);
replayFingerprint = { idempotencyKeyHash, requestHash, restoreEventId: evidence.restoreEventId };
const result = await transactionDb.transaction(async (tx) => {
const [receipt] = await tx
.select({
id: schema.ossCaseEvidence.id,
requestHash: schema.ossCaseEvidence.requestHash,
recordedAt: schema.ossCaseEvidence.recordedAt,
})
.from(schema.ossCaseEvidence)
.where(eq(schema.ossCaseEvidence.idempotencyKeyHash, idempotencyKeyHash))
.limit(1);
if (receipt) {
if (receipt.requestHash !== requestHash) throw new IngestionConflict("Idempotency-Key was already used with different case evidence");
return { ...receipt, replayed: true };
}
const [[project], [checkpoint], [restore]] = await Promise.all([
tx
.select({ id: schema.projects.id })
.from(schema.projects)
.where(eq(schema.projects.id, evidence.projectId))
.limit(1),
tx
.select({ projectId: schema.checkpoints.projectId })
.from(schema.checkpoints)
.where(eq(schema.checkpoints.id, evidence.checkpointId))
.limit(1),
tx
.select({
projectId: schema.restoreEvents.projectId,
toCheckpointId: schema.restoreEvents.toCheckpointId,
status: schema.restoreEvents.status,
})
.from(schema.restoreEvents)
.where(eq(schema.restoreEvents.id, evidence.restoreEventId))
.limit(1),
]);
const linksMatch =
project &&
checkpoint &&
restore &&
checkpoint.projectId === project.id &&
restore.projectId === project.id &&
restore.status === "applied" &&
restore.toCheckpointId === evidence.checkpointId;
if (!linksMatch) throw new IngestionConflict("Case evidence links are inconsistent");
const [sameRestore] = await tx
.select({
id: schema.ossCaseEvidence.id,
requestHash: schema.ossCaseEvidence.requestHash,
recordedAt: schema.ossCaseEvidence.recordedAt,
})
.from(schema.ossCaseEvidence)
.where(eq(schema.ossCaseEvidence.restoreEventId, evidence.restoreEventId))
.limit(1);
if (sameRestore) {
if (sameRestore.requestHash !== requestHash) throw new IngestionConflict("Restore event already has different case evidence");
return { ...sameRestore, replayed: true };
}
const [created] = await tx
.insert(schema.ossCaseEvidence)
.values({
...evidence,
idempotencyKeyHash,
requestHash,
requestId: requestId(res),
collectorKeySlot: req.collectorKeySlot || "current",
})
.returning({
id: schema.ossCaseEvidence.id,
recordedAt: schema.ossCaseEvidence.recordedAt,
});
return { ...created, replayed: false };
});
setReplayHeader(res, result.replayed);
return res.status(result.replayed ? 200 : 201).json({
recorded: true,
replayed: result.replayed,
evidenceId: result.id,
recordedAt: result.recordedAt.toISOString(),
});
} catch (error) {
if (error instanceof z.ZodError) {
return res.status(400).json({ error: "Invalid case evidence", details: error.issues });
}
if (error instanceof IngestionConflict) {
return res.status(409).json({ error: error.message });
}
if (isUniqueViolation(error)) {
if (replayFingerprint) {
try {
const [winner] = await db
.select({
id: schema.ossCaseEvidence.id,
requestHash: schema.ossCaseEvidence.requestHash,
recordedAt: schema.ossCaseEvidence.recordedAt,
})
.from(schema.ossCaseEvidence)
.where(eq(schema.ossCaseEvidence.restoreEventId, replayFingerprint.restoreEventId))
.limit(1);
if (winner?.requestHash === replayFingerprint.requestHash) {
setReplayHeader(res, true);
return res.status(200).json({
recorded: true,
replayed: true,
evidenceId: winner.id,
recordedAt: winner.recordedAt.toISOString(),
});
}
} catch {
return res.status(503).json({ error: "Case evidence replay could not be resolved" });
}
}
return res.status(409).json({ error: "Concurrent case ingestion conflicted; retry with the same Idempotency-Key" });
}
logger.error(
"OSS case evidence ingestion failed",
error instanceof Error ? error : undefined,
{ details: String(error) }
);
return res.status(503).json({ error: "Case evidence was not recorded" });
}
});
export default router;

View File

@ -15,6 +15,7 @@ import {
getCachedHealth,
} from "../services/providerHealthService.js";
import { enginePaths, ENGINE_DIRS } from "../services/engineManager.js";
import { getCoverageFreshness } from "../services/adoptionEvidenceHealth.js";
const router = Router();
@ -137,6 +138,30 @@ router.get("/ready", async (req: Request, res: Response) => {
overallStatus = "unhealthy";
}
try {
const freshness = await getCoverageFreshness();
if (freshness.status === "fresh") {
checks.adoptionEvidence = {
status: "pass",
message: `Latest OSS coverage is ${freshness.ageHours}h old`,
};
} else {
checks.adoptionEvidence = {
status: "warn",
message: freshness.status === "stale"
? `Latest OSS coverage is ${freshness.ageHours}h old; limit is ${freshness.maxAgeHours}h`
: "No completed OSS coverage batch exists",
};
if (overallStatus === "healthy") overallStatus = "degraded";
}
} catch (error) {
checks.adoptionEvidence = {
status: "fail",
message: "Adoption evidence health query failed",
};
overallStatus = "unhealthy";
}
// Check memory usage
const memoryUsage = process.memoryUsage();
const heapUsedMB = Math.round(memoryUsage.heapUsed / 1024 / 1024);
@ -202,6 +227,39 @@ router.get("/db", async (req: Request, res: Response) => {
});
});
router.get("/adoption", async (_req: Request, res: Response) => {
try {
const freshness = await getCoverageFreshness();
const status = freshness.status === "fresh" ? "healthy" : "degraded";
return res.status(200).json({
status,
timestamp: new Date().toISOString(),
checks: {
coverageFreshness: {
status: freshness.status === "fresh" ? "pass" : "warn",
message: freshness.status === "fresh"
? `Latest OSS coverage is ${freshness.ageHours}h old`
: freshness.status === "stale"
? `Latest OSS coverage is ${freshness.ageHours}h old; limit is ${freshness.maxAgeHours}h`
: "No completed OSS coverage batch exists",
freshness,
},
},
});
} catch (error) {
return res.status(503).json({
status: "unhealthy",
timestamp: new Date().toISOString(),
checks: {
coverageFreshness: {
status: "fail",
message: "Adoption evidence health query failed",
},
},
});
}
});
/**
* GET /health/schema - Schema verification results
* Checks all expected tables, columns, indexes, and migration drift.

View File

@ -0,0 +1,66 @@
import { desc, eq } from "drizzle-orm";
import { db, schema } from "../db/index.js";
const DEFAULT_MAX_AGE_HOURS = 168;
export type CoverageFreshness = {
status: "fresh" | "stale" | "unmeasured";
checkedAt: string;
latestWindowEndedAt: string | null;
latestBatchCompletedAt: string | null;
ageHours: number | null;
maxAgeHours: number;
};
export function coverageMaxAgeHours(): number {
const configured = Number(process.env.OSS_COVERAGE_MAX_AGE_HOURS || DEFAULT_MAX_AGE_HOURS);
return Number.isInteger(configured) && configured >= 1 && configured <= 8_760
? configured
: DEFAULT_MAX_AGE_HOURS;
}
export function evaluateCoverageFreshness(
batch: { windowEndedAt: Date; completedAt: Date | null } | undefined,
checkedAt = new Date()
): CoverageFreshness {
const maxAgeHours = coverageMaxAgeHours();
if (!batch) {
return {
status: "unmeasured",
checkedAt: checkedAt.toISOString(),
latestWindowEndedAt: null,
latestBatchCompletedAt: null,
ageHours: null,
maxAgeHours,
};
}
const ageHours = Math.max(
0,
Math.round(((checkedAt.getTime() - batch.windowEndedAt.getTime()) / (60 * 60 * 1000)) * 10) / 10
);
return {
status: ageHours <= maxAgeHours ? "fresh" : "stale",
checkedAt: checkedAt.toISOString(),
latestWindowEndedAt: batch.windowEndedAt.toISOString(),
latestBatchCompletedAt: batch.completedAt?.toISOString() ?? null,
ageHours,
maxAgeHours,
};
}
export async function getCoverageFreshness(checkedAt = new Date()): Promise<CoverageFreshness> {
const [latest] = await db
.select({
windowEndedAt: schema.ossCoverageBatches.windowEndedAt,
completedAt: schema.ossCoverageBatches.completedAt,
})
.from(schema.ossCoverageBatches)
.where(eq(schema.ossCoverageBatches.status, "completed"))
.orderBy(
desc(schema.ossCoverageBatches.windowEndedAt),
desc(schema.ossCoverageBatches.completedAt)
)
.limit(1);
return evaluateCoverageFreshness(latest, checkedAt);
}

View File

@ -29,6 +29,9 @@ services:
CONTEXT7_API_KEY: ${CONTEXT7_API_KEY:-}
JWT_SECRET: ${JWT_SECRET:-}
INTERNAL_SECRET: ${INTERNAL_SECRET:-}
ADOPTION_INGESTION_SECRET: ${ADOPTION_INGESTION_SECRET:?set a dedicated 32+ character collector secret}
ADOPTION_INGESTION_SECRET_PREVIOUS: ${ADOPTION_INGESTION_SECRET_PREVIOUS:-}
OSS_COVERAGE_MAX_AGE_HOURS: ${OSS_COVERAGE_MAX_AGE_HOURS:-168}
depends_on:
postgres:
condition: service_healthy
@ -39,7 +42,7 @@ services:
- CMD
- node
- -e
- "require('http').get('http://127.0.0.1:3001/health/providers',r=>process.exit(r.statusCode===200?0:1)).on('error',()=>process.exit(1))"
- "require('http').get('http://127.0.0.1:3001/health/ready',r=>process.exit(r.statusCode===200?0:1)).on('error',()=>process.exit(1))"
interval: 30s
timeout: 5s
retries: 3

View File

@ -0,0 +1,35 @@
import { NextResponse } from 'next/server';
import { parseAdoptionSummary } from '@/lib/adoption-evidence';
const API_URL = process.env.API_URL || process.env.NEXT_PUBLIC_API_URL || 'https://timemachine-api.gitgram.app';
export async function GET() {
try {
const response = await fetch(`${API_URL}/v1/adoption/summary`, {
cache: 'no-store',
headers: { Accept: 'application/json' },
});
if (!response.ok) {
return NextResponse.json(
{ status: 'unavailable', error: `Public evidence API returned HTTP ${response.status}` },
{ status: response.status, headers: { 'Cache-Control': 'no-store' } },
);
}
const summary = parseAdoptionSummary(await response.json() as unknown);
if (!summary) {
return NextResponse.json(
{ status: 'unavailable', error: 'Public evidence API returned an invalid summary' },
{ status: 502, headers: { 'Cache-Control': 'no-store' } },
);
}
return NextResponse.json(summary, { headers: { 'Cache-Control': 'no-store' } });
} catch {
return NextResponse.json(
{ status: 'unavailable', error: 'Public evidence API could not be reached' },
{ status: 503, headers: { 'Cache-Control': 'no-store' } },
);
}
}

View File

@ -1,386 +1,249 @@
import Link from 'next/link';
import {
ArrowRight,
Users,
Database,
Shield,
TrendingUp,
Mail,
ExternalLink,
Quote,
} from 'lucide-react';
import { ArrowRight } from 'lucide-react';
import { Navbar } from '@/components/Navbar';
import { Footer } from '@/components/Footer';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent } from '@/components/ui/card';
import {
parseAdoptionSummary,
type AdoptionSummary,
type EvidenceStatus,
type EvidenceWindow,
} from '@/lib/adoption-evidence';
interface FundingRound {
round: string
amount: string
date: string
description: string
accentColor: string
dotColor: string
interface Metric {
label: string;
value: string;
detail: string;
}
interface KeyMetric {
icon: React.ComponentType<{ className?: string }>
value: string
label: string
sublabel: string
accentColor: string
bgColor: string
const API_BASE = process.env.API_URL || process.env.NEXT_PUBLIC_API_URL || 'https://timemachine-api.gitgram.app';
async function getAdoptionSummary(): Promise<AdoptionSummary | null> {
try {
const response = await fetch(`${API_BASE}/v1/adoption/summary`, {
next: { revalidate: 300 },
});
if (!response.ok) return null;
return parseAdoptionSummary(await response.json() as unknown);
} catch {
return null;
}
}
interface InvestorLogo {
name: string
tier: 'lead' | 'strategic'
function countValue(number: number | null | undefined, status: EvidenceStatus | 'unavailable'): string {
if (status === 'unavailable') return 'Unavailable';
if (status === 'unmeasured') return 'Unmeasured';
return typeof number === 'number' ? new Intl.NumberFormat('en-US').format(number) : 'Not applicable';
}
interface PressQuote {
publication: string
quote: string
author: string
date: string
url: string
function windowLabel(window: EvidenceWindow | undefined): string {
if (!window || window.status === 'unmeasured' || !window.startsAt || !window.endsAt) {
return 'No completed coverage window';
}
const formatter = new Intl.DateTimeFormat('en-US', {
day: 'numeric',
month: 'short',
year: 'numeric',
timeZone: 'UTC',
});
return `${formatter.format(new Date(window.startsAt))} to ${formatter.format(new Date(window.endsAt))} UTC`;
}
const fundingRounds: FundingRound[] = [
{
round: 'Pre-Seed',
amount: '$1.2M',
date: 'Q4 2025',
description: 'Initial funding to build the checkpoint engine and validate the core thesis with early developer users.',
accentColor: 'text-blue-400',
dotColor: 'bg-blue-500',
},
{
round: 'Seed',
amount: '$4.8M',
date: 'Q2 2026',
description: 'Scaling the team, launching the cloud sync product, and expanding integrations with Claude, Cursor, and Windsurf.',
accentColor: 'text-purple-400',
dotColor: 'bg-purple-500',
},
];
function freshnessLabel(summary: AdoptionSummary): string {
const freshness = summary.oss.freshness;
if (freshness.status === 'unmeasured' || freshness.ageHours === null) return 'Freshness unmeasured';
return `${freshness.status} / ${freshness.ageHours} h old`;
}
const keyMetrics: KeyMetric[] = [
{
icon: Users,
value: '12,400+',
label: 'Active Developers',
sublabel: 'Monthly active users across CLI and dashboard',
accentColor: 'text-blue-400',
bgColor: 'bg-blue-500/10',
},
{
icon: Database,
value: '3.2M',
label: 'Sessions Saved',
sublabel: 'Checkpoints created since launch',
accentColor: 'text-purple-400',
bgColor: 'bg-purple-500/10',
},
{
icon: Shield,
value: '847 TB',
label: 'Data Protected',
sublabel: 'Workspace state secured in cloud sync',
accentColor: 'text-green-400',
bgColor: 'bg-green-500/10',
},
{
icon: TrendingUp,
value: '38%',
label: 'MoM Growth',
sublabel: 'New user growth over the past 90 days',
accentColor: 'text-orange-400',
bgColor: 'bg-orange-500/10',
},
];
const investorLogos: InvestorLogo[] = [
{ name: 'Accel', tier: 'lead' },
{ name: 'Pioneer Fund', tier: 'lead' },
{ name: 'Gradient Ventures', tier: 'strategic' },
{ name: 'Dev Collective', tier: 'strategic' },
{ name: 'Horizon VC', tier: 'strategic' },
{ name: 'OSS Capital', tier: 'strategic' },
];
const pressQuotes: PressQuote[] = [
{
publication: 'The Verge',
quote: 'AITimeMachine is quietly becoming essential infrastructure for teams that take AI-assisted development seriously.',
author: 'Sarah Chen, Staff Writer',
date: 'May 2026',
url: 'https://theverge.com',
},
{
publication: 'Hacker News',
quote: 'Finally a tool that treats AI agents like the non-deterministic systems they are. AITM\'s restore is genuinely sub-second on a 2GB workspace.',
author: 'Thread top comment (1,240 points)',
date: 'April 2026',
url: 'https://news.ycombinator.com',
},
{
publication: 'Developer Weekly',
quote: 'If you\'re running Claude Code or Cursor in an agentic workflow, not using AITM is a liability, not a choice.',
author: 'Marcus Toll, Editor',
date: 'March 2026',
url: 'https://developerweekly.com',
},
{
publication: 'TechCrunch',
quote: 'The startup solving a problem every AI developer has — but most haven\'t yet found the words to describe.',
author: 'Priya Anand, Reporter',
date: 'February 2026',
url: 'https://techcrunch.com',
},
];
export default function InvestorsPage() {
function EvidenceRail({ number, title, window, metrics }: {
number: string;
title: string;
window: string;
metrics: Metric[];
}) {
return (
<div className="min-h-screen bg-gray-950 text-white">
<section className="border-t border-[#171713] py-10 sm:py-14">
<div className="mb-8 grid gap-3 sm:grid-cols-[6rem_1fr] sm:items-end">
<p className="font-serif text-7xl leading-none tracking-[-0.08em]" aria-hidden="true">{number}</p>
<div>
<h2 className="font-serif text-3xl tracking-[-0.035em] sm:text-4xl">{title}</h2>
<p className="mt-2 font-mono text-xs uppercase tracking-[0.16em]">{window}</p>
</div>
</div>
<div className="grid border-l border-t border-[#171713] sm:grid-cols-2 lg:grid-cols-4">
{metrics.map((metric) => (
<article key={metric.label} className="min-h-56 border-b border-r border-[#171713] p-6">
<p className="font-serif text-4xl tracking-[-0.05em] sm:text-5xl">{metric.value}</p>
<h3 className="mt-5 font-mono text-xs uppercase tracking-[0.16em]">{metric.label}</h3>
<p className="mt-4 text-sm leading-6 text-[#4d4c44]">{metric.detail}</p>
</article>
))}
</div>
</section>
);
}
export default async function InvestorsPage() {
const adoption = await getAdoptionSummary();
const endpointStatus = adoption ? 'measured' : 'unavailable';
const ossStatus = adoption?.oss.status ?? 'unavailable';
const caseStatus = adoption?.caseEvidence.status ?? 'unavailable';
const adoptionMetrics: Metric[] = [
{
label: 'Active developers',
value: countValue(adoption?.activeDevelopers, endpointStatus),
detail: 'Distinct cloud-sync accounts with a checkpoint in the adoption window.',
},
{
label: 'Projects protected',
value: countValue(adoption?.projects, endpointStatus),
detail: 'Projects registered with the cloud checkpoint service.',
},
{
label: 'Checkpoints created',
value: countValue(adoption?.checkpoints.lifetime, endpointStatus),
detail: adoption ? `${countValue(adoption.checkpoints.period, 'measured')} created in this window.` : 'The live query failed.',
},
{
label: 'Restores applied',
value: countValue(adoption?.appliedRestores.lifetime, endpointStatus),
detail: adoption ? `${countValue(adoption.appliedRestores.period, 'measured')} applied in this window.` : 'The live query failed.',
},
];
const contributionMetrics: Metric[] = [
{
label: 'External contributors',
value: countValue(adoption?.oss.externalContributors, ossStatus),
detail: ossStatus === 'unmeasured' ? 'No completed OSS coverage batch.' : 'Distinct opaque contributor keys in the measured batch.',
},
{
label: 'Repeat contributors',
value: countValue(adoption?.oss.repeatContributors, ossStatus),
detail: ossStatus === 'unmeasured' ? 'No completed OSS coverage batch.' : 'Contributors with two or more recorded contributions.',
},
{
label: 'Repositories measured',
value: countValue(adoption?.oss.repositoriesMeasured, ossStatus),
detail: ossStatus === 'unmeasured' ? 'No completed OSS coverage batch.' : 'Repositories included in the batch coverage boundary.',
},
{
label: 'Applied restore cases',
value: countValue(adoption?.caseEvidence.cases, caseStatus),
detail: caseStatus === 'unmeasured'
? 'No server-validated checkpoint-to-restore case has been recorded.'
: adoption
? `${countValue(adoption.caseEvidence.repositoriesCovered, 'measured')} opaque repository keys covered.`
: 'The live query failed.',
},
];
const responseMetrics: Metric[] = [
{
label: 'Contributions received',
value: countValue(adoption?.oss.maintainerResponseLoad.contributionsReceived, ossStatus),
detail: 'External contribution records opened in the OSS window.',
},
{
label: 'First responses sent',
value: countValue(adoption?.oss.maintainerResponseLoad.responsesSent, ossStatus),
detail: 'Contribution records with a first maintainer response timestamp.',
},
{
label: 'Awaiting first response',
value: countValue(adoption?.oss.maintainerResponseLoad.awaitingResponse, ossStatus),
detail: 'Measured contributions without a first response timestamp.',
},
{
label: 'Average first response',
value: adoption?.oss.maintainerResponseLoad.averageFirstResponseHours == null
? countValue(null, ossStatus)
: `${adoption.oss.maintainerResponseLoad.averageFirstResponseHours} h`,
detail: 'Mean elapsed time from contribution open to first maintainer response.',
},
];
return (
<div className="min-h-screen bg-[#EDE4CF] text-[#171713]">
<Navbar />
{/* Hero */}
<section className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-20 sm:py-28">
<Badge className="mb-6 bg-blue-500/10 text-blue-400 border-blue-500/20">Investors & Press</Badge>
<h1 className="text-4xl sm:text-6xl font-bold mb-8 leading-tight">
Backed by developers,
<br />
<span className="bg-clip-text text-transparent bg-gradient-to-r from-blue-400 to-purple-400">
for developers
</span>
</h1>
<p className="text-xl text-gray-400 max-w-3xl leading-relaxed">
AITimeMachine is backed by investors who understand that the AI development tooling
layer is one of the most important infrastructure categories of the next decade.
Every dollar we've raised has gone toward making developers safer and faster.
</p>
</section>
{/* Funding Timeline */}
<section className="py-16 pb-24">
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div className="mb-14">
<Badge className="mb-4 bg-purple-500/10 text-purple-400 border-purple-500/20">Funding History</Badge>
<h2 className="text-3xl font-bold mb-4">Our funding journey</h2>
<p className="text-gray-400 text-lg max-w-xl">
From a weekend prototype to category-defining infrastructure — all in under a year.
</p>
<main>
<section className="border-b border-[#171713] px-5 py-20 sm:px-8 lg:px-14 lg:py-28">
<div className="mx-auto max-w-7xl">
<p className="mb-8 font-mono text-xs uppercase tracking-[0.2em]">Open source evidence record</p>
<h1 className="max-w-5xl font-serif text-5xl leading-[0.95] tracking-[-0.045em] sm:text-7xl lg:text-8xl">
Product use, contribution, and maintainer load.
</h1>
<div className="mt-12 grid gap-8 border-t border-[#171713] pt-8 lg:grid-cols-[1.5fr_1fr]">
<p className="max-w-3xl text-xl leading-relaxed sm:text-2xl">
AITimeMachine records reversible work. These counts come from cloud-sync records and completed maintainer coverage batches.
</p>
<div className="font-mono text-sm leading-6">
<p>Source: {adoption?.methodology.source ?? 'Live endpoint unavailable'}</p>
<p>Updated: {adoption ? `${new Date(adoption.generatedAt).toLocaleString('en-US', { timeZone: 'UTC' })} UTC` : 'Unavailable'}</p>
<a className="underline underline-offset-4" href={`${API_BASE}/v1/adoption/summary`}>Inspect JSON evidence</a>
</div>
</div>
</div>
<div className="relative">
{/* Timeline line */}
<div className="absolute left-6 top-0 bottom-0 w-px bg-gradient-to-b from-blue-500 via-purple-500 to-transparent hidden sm:block" />
<div className="space-y-10">
{fundingRounds.map((round, index) => (
<div key={round.round} className="sm:pl-16 relative">
{/* Timeline dot */}
<div className={`absolute left-4 top-5 w-4 h-4 rounded-full ${round.dotColor} border-4 border-gray-950 hidden sm:block`} />
<Card className="bg-gray-900 border-gray-800">
<CardContent className="p-8">
<div className="flex flex-wrap items-start justify-between gap-4 mb-4">
<div className="flex items-center gap-4">
<div>
<div className="flex items-center gap-3 mb-1">
<h3 className="text-xl font-bold">{round.round}</h3>
<Badge
className={`${index === 0 ? 'bg-blue-500/10 text-blue-400 border-blue-500/20' : 'bg-purple-500/10 text-purple-400 border-purple-500/20'}`}
>
{round.date}
</Badge>
</div>
<p className={`text-3xl font-bold ${round.accentColor}`}>{round.amount}</p>
</div>
</div>
</div>
<p className="text-gray-400 text-base leading-relaxed">{round.description}</p>
</CardContent>
</Card>
</section>
<div className="mx-auto max-w-7xl px-5 sm:px-8 lg:px-14">
<EvidenceRail
number="01"
title="Product adoption"
window={adoption ? windowLabel(adoption.windows.adoption) : 'Live query unavailable'}
metrics={adoptionMetrics}
/>
<EvidenceRail
number="02"
title="External contribution return"
window={adoption ? `${windowLabel(adoption.windows.oss)} · ${freshnessLabel(adoption)}` : 'Live query unavailable'}
metrics={contributionMetrics}
/>
<EvidenceRail
number="03"
title="Maintainer response load"
window={adoption ? `${windowLabel(adoption.windows.oss)} · ${freshnessLabel(adoption)}` : 'Live query unavailable'}
metrics={responseMetrics}
/>
</div>
<section className="bg-[#171713] px-5 py-20 text-[#EDE4CF] sm:px-8 lg:px-14">
<div className="mx-auto grid max-w-7xl gap-14 lg:grid-cols-2">
<div>
<p className="font-mono text-xs uppercase tracking-[0.18em]">Measurement rules</p>
<h2 className="mt-7 font-serif text-5xl leading-none tracking-[-0.04em]">Definitions for each count.</h2>
</div>
<dl className="divide-y divide-[#817b6c] border-y border-[#817b6c] text-sm leading-6">
{[
['Active developer', adoption?.methodology.activeDeveloper ?? 'Distinct account with a checkpoint in the adoption window.'],
['External contributor', adoption?.methodology.externalContributor ?? 'Distinct opaque contributor key in a completed coverage batch.'],
['Repeat contributor', adoption?.methodology.repeatContributor ?? 'Opaque contributor key with two or more records in the batch.'],
['Maintainer response', adoption?.methodology.maintainerResponse ?? 'Elapsed time to the first maintainer response.'],
['Case evidence', adoption?.methodology.caseEvidence ?? 'Applied restore linked to its project and checkpoint.'],
['Privacy boundary', adoption?.methodology.privacy ?? 'The public record contains aggregate counts only.'],
].map(([term, definition]) => (
<div className="py-5" key={term}>
<dt className="font-mono uppercase tracking-wider">{term}</dt>
<dd className="mt-2 text-[#cfc6b2]">{definition}</dd>
</div>
))}
{/* Future indicator */}
<div className="sm:pl-16 relative">
<div className="absolute left-4 top-5 w-4 h-4 rounded-full bg-gray-700 border-4 border-gray-950 hidden sm:block" />
<div className="bg-gray-900/50 border border-gray-800 border-dashed rounded-2xl p-8">
<p className="text-gray-500 text-sm font-medium uppercase tracking-wider mb-1">Next round</p>
<p className="text-gray-400 text-base">
We're building sustainably and focused on growth metrics. Interested in participating
in our next round?{' '}
<a
href="mailto:investors@aitimemachine.dev"
className="text-blue-400 hover:text-blue-300 transition-colors underline"
>
Reach out.
</a>
</p>
</div>
</div>
</dl>
</div>
</section>
<section className="px-5 py-20 sm:px-8 lg:px-14">
<div className="mx-auto flex max-w-7xl flex-col justify-between gap-8 border-t border-[#171713] pt-8 sm:flex-row sm:items-end">
<div>
<p className="font-mono text-xs uppercase tracking-[0.18em]">Review</p>
<p className="mt-4 max-w-2xl text-2xl leading-snug">Check the implementation, definitions, and privacy boundary.</p>
</div>
<Link href="/contact" className="inline-flex items-center gap-3 border border-[#171713] px-6 py-4 font-mono text-sm uppercase tracking-wider transition-colors hover:bg-[#171713] hover:text-[#EDE4CF]">
Start a review <ArrowRight className="h-4 w-4" />
</Link>
</div>
</div>
</section>
{/* Key Metrics */}
<section className="bg-gray-900/50 py-24">
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div className="text-center mb-14">
<Badge className="mb-4 bg-green-500/10 text-green-400 border-green-500/20">Key Metrics</Badge>
<h2 className="text-3xl font-bold mb-4">Traction speaks for itself</h2>
<p className="text-gray-400 text-lg max-w-xl mx-auto">
Numbers from June 2026. Growing every week.
</p>
</div>
<div className="grid sm:grid-cols-2 lg:grid-cols-4 gap-6">
{keyMetrics.map((metric) => (
<div
key={metric.label}
className="bg-gray-900 border border-gray-800 rounded-2xl p-7 hover:border-gray-700 transition-colors"
>
<div className={`w-12 h-12 ${metric.bgColor} rounded-xl flex items-center justify-center mb-5`}>
<metric.icon className={`w-6 h-6 ${metric.accentColor}`} />
</div>
<p className={`text-3xl font-bold ${metric.accentColor} mb-1`}>{metric.value}</p>
<p className="font-semibold text-white mb-1">{metric.label}</p>
<p className="text-gray-500 text-sm leading-relaxed">{metric.sublabel}</p>
</div>
))}
</div>
</div>
</section>
{/* Investor Logos */}
<section className="py-24">
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div className="text-center mb-14">
<Badge className="mb-4 bg-blue-500/10 text-blue-400 border-blue-500/20">Our Investors</Badge>
<h2 className="text-3xl font-bold mb-4">Supported by the best</h2>
<p className="text-gray-400 text-lg max-w-xl mx-auto">
We're backed by funds that have a track record of building developer-first companies.
</p>
</div>
<div className="mb-8">
<p className="text-sm text-gray-500 uppercase tracking-wider font-medium text-center mb-6">Lead Investors</p>
<div className="flex flex-wrap justify-center gap-5 mb-10">
{investorLogos
.filter((inv) => inv.tier === 'lead')
.map((investor) => (
<div
key={investor.name}
className="w-44 h-20 bg-gray-900 border border-gray-700 rounded-2xl flex items-center justify-center"
>
<span className="text-gray-300 font-semibold text-lg">{investor.name}</span>
</div>
))}
</div>
<p className="text-sm text-gray-500 uppercase tracking-wider font-medium text-center mb-6">Strategic Investors</p>
<div className="flex flex-wrap justify-center gap-4">
{investorLogos
.filter((inv) => inv.tier === 'strategic')
.map((investor) => (
<div
key={investor.name}
className="w-36 h-16 bg-gray-900 border border-gray-800 rounded-xl flex items-center justify-center"
>
<span className="text-gray-400 font-medium text-sm">{investor.name}</span>
</div>
))}
</div>
</div>
</div>
</section>
{/* Press Mentions */}
<section className="bg-gray-900/50 py-24">
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div className="text-center mb-14">
<Badge className="mb-4 bg-orange-500/10 text-orange-400 border-orange-500/20">Press</Badge>
<h2 className="text-3xl font-bold mb-4">What people are saying</h2>
<p className="text-gray-400 text-lg max-w-xl mx-auto">
Coverage from developers, journalists, and the communities that shape how
engineers work with AI tools.
</p>
</div>
<div className="grid sm:grid-cols-2 gap-6">
{pressQuotes.map((item) => (
<Card
key={item.publication}
className="bg-gray-900 border-gray-800 hover:border-gray-700 transition-colors"
>
<CardContent className="p-8">
<div className="flex items-start justify-between mb-5">
<div>
<p className="font-bold text-white text-lg">{item.publication}</p>
<p className="text-gray-500 text-sm">{item.date}</p>
</div>
<a
href={item.url}
target="_blank"
rel="noopener noreferrer"
className="w-8 h-8 bg-gray-800 hover:bg-gray-700 rounded-lg flex items-center justify-center transition-colors flex-shrink-0"
aria-label={`Read on ${item.publication}`}
>
<ExternalLink className="w-4 h-4 text-gray-400" />
</a>
</div>
<div className="relative pl-5 border-l-2 border-blue-500/40 mb-5">
<Quote className="w-4 h-4 text-blue-500/40 absolute -left-2.5 -top-1" />
<p className="text-gray-300 text-base leading-relaxed italic">{item.quote}</p>
</div>
<p className="text-gray-500 text-sm">{item.author}</p>
</CardContent>
</Card>
))}
</div>
</div>
</section>
{/* Press Contact */}
<section className="py-24">
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<Card className="bg-gradient-to-r from-blue-900/30 to-purple-900/30 border border-gray-800">
<CardContent className="py-16 text-center">
<div className="w-14 h-14 bg-blue-500/10 rounded-2xl flex items-center justify-center mx-auto mb-6">
<Mail className="w-7 h-7 text-blue-400" />
</div>
<h2 className="text-3xl font-bold mb-4">Press inquiries</h2>
<p className="text-gray-400 text-lg mb-3 max-w-xl mx-auto leading-relaxed">
Writing about AI development tooling, the future of human-AI workflows, or
the developer infrastructure layer? We'd love to talk.
</p>
<p className="text-gray-500 text-base mb-10">
We typically respond to press inquiries within one business day.
</p>
<div className="flex flex-wrap justify-center gap-4">
<Button size="lg" asChild>
<a href="mailto:press@aitimemachine.dev">
<Mail className="w-4 h-4 mr-2" />
press@aitimemachine.dev
</a>
</Button>
<Button size="lg" variant="outline" asChild className="border-gray-700 hover:border-gray-600">
<Link href="/about">
Read Our Story
<ArrowRight className="w-4 h-4 ml-2" />
</Link>
</Button>
</div>
<p className="text-gray-600 text-sm mt-8">
For investor inquiries:{' '}
<a
href="mailto:investors@aitimemachine.dev"
className="text-gray-500 hover:text-gray-400 transition-colors underline"
>
investors@aitimemachine.dev
</a>
</p>
</CardContent>
</Card>
</div>
</section>
</section>
</main>
<Footer />
</div>

View File

@ -0,0 +1,10 @@
import type { Metadata } from 'next';
export const metadata: Metadata = {
title: 'Maintainer evidence',
description: 'Live AITimeMachine adoption, external contribution, response-load, and restore-case evidence.',
};
export default function MaintainersLayout({ children }: { children: React.ReactNode }) {
return children;
}

View File

@ -0,0 +1 @@
.shell{min-height:100vh;background:#eee4cd;color:#191812}.shell :global(nav){position:relative}.hero{padding:5rem max(1.25rem,5vw) 6rem;border-bottom:1px solid #191812;background:#d95632}.eyebrow{margin:0;font:700 .72rem/1.2 ui-monospace,SFMono-Regular,Menlo,monospace;letter-spacing:.18em;text-transform:uppercase}.hero h1{max-width:72rem;margin:2rem 0 0;font:500 clamp(3.6rem,9vw,8.5rem)/.84 Georgia,serif;letter-spacing:-.065em}.intro{max-width:52rem;margin:3rem 0 0;font-size:clamp(1.15rem,2vw,1.55rem);line-height:1.45}.heroActions,.methodLinks{display:flex;flex-wrap:wrap;gap:1rem;margin-top:2rem}.heroActions button,.heroActions a,.statePanel button,.methodLinks a{padding:.85rem 1rem;border:1px solid #191812;background:transparent;color:inherit;font:700 .74rem ui-monospace,SFMono-Regular,Menlo,monospace;letter-spacing:.08em;text-transform:uppercase;cursor:pointer}.heroActions button{background:#191812;color:#eee4cd}.heroActions button:disabled{opacity:.6;cursor:wait}.statePanel{padding:5rem max(1.25rem,5vw);border-bottom:1px solid #191812}.statePanel span{font:700 .72rem ui-monospace,SFMono-Regular,Menlo,monospace;letter-spacing:.16em}.statePanel h2,.recordHeader h2,.operatorPath h2{max-width:64rem;margin:1.4rem 0;font:500 clamp(2.7rem,6vw,6rem)/.9 Georgia,serif;letter-spacing:-.055em}.statePanel p{max-width:48rem;font-size:1.1rem;line-height:1.55}.errorPanel{background:#191812;color:#eee4cd}.errorPanel button{border-color:#eee4cd;color:#eee4cd}.record{padding:5rem max(1.25rem,5vw)}.recordHeader{display:grid;gap:3rem;padding-bottom:3rem;border-bottom:1px solid #191812}.recordHeader dl{margin:0;border-top:1px solid #191812}.recordHeader dl div{display:grid;grid-template-columns:10rem 1fr;gap:1rem;padding:.8rem 0;border-bottom:1px solid #191812}.recordHeader dt,.recordHeader dd{font:.72rem/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}.recordHeader dt{text-transform:uppercase}.recordHeader dd{margin:0;overflow-wrap:anywhere}.zeroNotice{margin:2rem 0 0;padding:1rem;border:1px solid #191812;background:#f5e933;font-weight:700}.rails{display:grid;margin-top:3rem;border-left:1px solid #191812;border-top:1px solid #191812}.rail{border-right:1px solid #191812;border-bottom:1px solid #191812}.rail>header{display:flex;justify-content:space-between;gap:1rem;padding:1rem;background:#191812;color:#eee4cd}.rail>header h3{margin:0;font:700 .78rem ui-monospace,SFMono-Regular,Menlo,monospace;letter-spacing:.08em;text-transform:uppercase}.rail>header span{font:.7rem ui-monospace,SFMono-Regular,Menlo,monospace;text-transform:uppercase}.rail[data-status="unmeasured"]>header{background:#786f60}.rail dl{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));margin:0}.rail dl div{min-height:9rem;padding:1.2rem;border-right:1px solid #191812;border-bottom:1px solid #191812}.rail dt{font:.7rem/1.4 ui-monospace,SFMono-Regular,Menlo,monospace;letter-spacing:.07em;text-transform:uppercase}.rail dd{margin:1.4rem 0 0;font:500 clamp(1.7rem,4vw,3.5rem)/.9 Georgia,serif;letter-spacing:-.04em;overflow-wrap:anywhere}.unmeasured{margin:0;padding:1rem;border-bottom:1px solid #191812;background:#d8cfba;font-size:.9rem}.operatorPath{padding:5rem max(1.25rem,5vw);border-top:1px solid #191812;background:#191812;color:#eee4cd}.operatorPath>header{max-width:68rem}.operatorPath ol{display:grid;margin:3rem 0 0;padding:0;border-left:1px solid #7f7869;border-top:1px solid #7f7869;list-style:none}.operatorPath li{padding:1.4rem;border-right:1px solid #7f7869;border-bottom:1px solid #7f7869}.operatorPath li span{font:700 .72rem ui-monospace,SFMono-Regular,Menlo,monospace;color:#d95632}.operatorPath li h3{margin:2.5rem 0 .8rem;font:500 1.8rem Georgia,serif}.operatorPath li p{margin:0;color:#c9c0ad;line-height:1.55}.methodLinks a{border-color:#eee4cd}.secretNote{margin:1.5rem 0 0;color:#c9c0ad;font:.78rem/1.5 ui-monospace,SFMono-Regular,Menlo,monospace}.shell :where(button,a):focus-visible{outline:3px solid #f5e933;outline-offset:4px}@media(min-width:760px){.recordHeader{grid-template-columns:1.2fr 1fr}.rails{grid-template-columns:repeat(3,minmax(0,1fr))}.rail dl{grid-template-columns:1fr}.operatorPath ol{grid-template-columns:repeat(2,minmax(0,1fr))}}@media(min-width:1100px){.operatorPath ol{grid-template-columns:repeat(4,minmax(0,1fr))}}@media(max-width:560px){.hero h1{font-size:3.5rem}.recordHeader dl div{grid-template-columns:1fr}.rail dl{grid-template-columns:1fr}}

View File

@ -0,0 +1,208 @@
'use client';
import Link from 'next/link';
import { useCallback, useEffect, useState } from 'react';
import { Footer } from '@/components/Footer';
import { Navbar } from '@/components/Navbar';
import {
parseAdoptionSummary,
type AdoptionSummary,
type EvidenceStatus,
} from '@/lib/adoption-evidence';
import styles from './maintainers.module.css';
type ViewState =
| { kind: 'loading' }
| { kind: 'error'; message: string }
| { kind: 'ready'; summary: AdoptionSummary };
const JSON_ENDPOINT = '/api/adoption/summary';
const METHODOLOGY_URL = 'https://github.com/gitgram/timemachine/blob/main/api-server/docs/adoption-evidence.md';
export default function MaintainersPage() {
const [view, setView] = useState<ViewState>({ kind: 'loading' });
const load = useCallback(async () => {
setView({ kind: 'loading' });
try {
const response = await fetch(JSON_ENDPOINT, {
cache: 'no-store',
headers: { Accept: 'application/json' },
});
const body = await response.json().catch(() => null) as unknown;
if (!response.ok) {
setView({ kind: 'error', message: readError(body) || `Evidence API returned HTTP ${response.status}.` });
return;
}
const summary = parseAdoptionSummary(body);
if (!summary) {
setView({ kind: 'error', message: 'Evidence API returned an invalid summary. No values were displayed.' });
return;
}
setView({ kind: 'ready', summary });
} catch {
setView({ kind: 'error', message: 'Evidence API could not be reached. No values were displayed.' });
}
}, []);
useEffect(() => {
void load();
}, [load]);
return (
<div className={styles.shell}>
<Navbar />
<main>
<section className={styles.hero}>
<p className={styles.eyebrow}>Maintainer evidence desk</p>
<h1>Measure the project<br />without inventing traction.</h1>
<p className={styles.intro}>
This route reads AITimeMachine’s public aggregate. Collection stays server-side;
account, repository, contributor, checkpoint, and restore identifiers stay private.
</p>
<div className={styles.heroActions}>
<button type="button" onClick={() => void load()} disabled={view.kind === 'loading'}>
{view.kind === 'loading' ? 'Reading evidence…' : 'Refresh evidence'}
</button>
<a href={JSON_ENDPOINT}>Inspect JSON</a>
</div>
</section>
{view.kind === 'loading' && (
<section className={styles.statePanel} aria-live="polite" aria-busy="true">
<span>LIVE READ / PENDING</span>
<h2>Waiting for the evidence service.</h2>
<p>No cached or example counts are shown while the request is unresolved.</p>
</section>
)}
{view.kind === 'error' && (
<section className={`${styles.statePanel} ${styles.errorPanel}`} role="alert">
<span>LIVE READ / UNAVAILABLE</span>
<h2>Evidence is unavailable.</h2>
<p>{view.message}</p>
<button type="button" onClick={() => void load()}>Retry the same endpoint</button>
</section>
)}
{view.kind === 'ready' && <EvidenceRecord summary={view.summary} />}
<section className={styles.operatorPath} aria-labelledby="operator-title">
<header>
<p className={styles.eyebrow}>Real collection path</p>
<h2 id="operator-title">What reaches this page.</h2>
</header>
<ol>
<li><span>01</span><h3>Cloud events</h3><p>Persisted projects, checkpoints, and applied restores define the rolling adoption window.</p></li>
<li><span>02</span><h3>Coverage batch</h3><p>A server-side maintainer job submits only external contributions using secret-keyed opaque identifiers.</p></li>
<li><span>03</span><h3>Validated cases</h3><p>A restore case counts only when its project, checkpoint, applied restore, and restore target agree.</p></li>
<li><span>04</span><h3>Public aggregate</h3><p>The browser receives counts, windows, statuses, and definitions—not the source identifiers.</p></li>
</ol>
<div className={styles.methodLinks}>
<a href={METHODOLOGY_URL} target="_blank" rel="noreferrer">Open ingestion and privacy methodology</a>
<Link href="/privacy">Read the public-data boundary</Link>
</div>
<p className={styles.secretNote}>Internal ingestion credentials are intentionally absent from this browser workflow.</p>
</section>
</main>
<Footer />
</div>
);
}
function EvidenceRecord({ summary }: { summary: AdoptionSummary }) {
const noProductRecords = summary.activeDevelopers === 0 && summary.projects === 0 &&
summary.checkpoints.lifetime === 0 && summary.appliedRestores.lifetime === 0;
const response = summary.oss.maintainerResponseLoad;
return (
<section className={styles.record} aria-labelledby="record-title">
<header className={styles.recordHeader}>
<div>
<p className={styles.eyebrow}>Validated public response</p>
<h2 id="record-title">Current evidence record.</h2>
</div>
<dl>
<div><dt>Generated</dt><dd>{formatTimestamp(summary.generatedAt)}</dd></div>
<div><dt>Adoption window</dt><dd>{formatWindow(summary.windows.adoption)}</dd></div>
<div><dt>OSS window</dt><dd>{formatWindow(summary.windows.oss)}</dd></div>
<div><dt>OSS freshness</dt><dd>{formatFreshness(summary)}</dd></div>
</dl>
</header>
{noProductRecords && (
<p className={styles.zeroNotice}>The adoption query completed and measured zero product records. Zero is not a service error.</p>
)}
{summary.oss.freshness.status === 'stale' && (
<p className={styles.zeroNotice}>The latest OSS collector window is stale. Counts remain historical evidence, not a current operational reading.</p>
)}
<div className={styles.rails}>
<MetricRail title="Product adoption" status="measured" metrics={[
['Active developers', formatNumber(summary.activeDevelopers)],
['Projects protected', formatNumber(summary.projects)],
['Checkpoints / window', formatNumber(summary.checkpoints.period)],
['Applied restores / window', formatNumber(summary.appliedRestores.period)],
]} />
<MetricRail title="External contribution return" status={summary.oss.status} metrics={[
['Repositories measured', evidenceValue(summary.oss.repositoriesMeasured, summary.oss.status)],
['External contributors', evidenceValue(summary.oss.externalContributors, summary.oss.status)],
['Repeat contributors', evidenceValue(summary.oss.repeatContributors, summary.oss.status)],
['Contributions received', evidenceValue(response.contributionsReceived, summary.oss.status)],
]} />
<MetricRail title="Maintainer response load" status={summary.oss.status} metrics={[
['First responses sent', evidenceValue(response.responsesSent, summary.oss.status)],
['Awaiting response', evidenceValue(response.awaitingResponse, summary.oss.status)],
['Average first response', response.averageFirstResponseHours === null
? summary.oss.status === 'unmeasured' ? 'UNMEASURED' : 'NOT APPLICABLE'
: `${response.averageFirstResponseHours} h`],
['Validated restore cases', evidenceValue(summary.caseEvidence.cases, summary.caseEvidence.status)],
]} />
</div>
</section>
);
}
function MetricRail({ title, status, metrics }: {
title: string;
status: EvidenceStatus;
metrics: [string, string][];
}) {
return (
<article className={styles.rail} data-status={status}>
<header><h3>{title}</h3><span>{status}</span></header>
{status === 'unmeasured' && <p className={styles.unmeasured}>No completed coverage exists. Null values remain unmeasured.</p>}
<dl>{metrics.map(([label, value]) => <div key={label}><dt>{label}</dt><dd>{value}</dd></div>)}</dl>
</article>
);
}
function evidenceValue(value: number | null, status: EvidenceStatus): string {
return status === 'unmeasured' ? 'UNMEASURED' : value === null ? 'NOT APPLICABLE' : formatNumber(value);
}
function formatNumber(value: number): string {
return new Intl.NumberFormat('en-US').format(value);
}
function formatTimestamp(value: string): string {
const date = new Date(value);
return Number.isNaN(date.getTime()) ? 'INVALID' : `${date.toISOString().slice(0, 16).replace('T', ' ')} UTC`;
}
function formatWindow(window: AdoptionSummary['windows']['adoption']): string {
if (window.status === 'unmeasured' || !window.startsAt || !window.endsAt) return 'UNMEASURED';
return `${formatTimestamp(window.startsAt)} — ${formatTimestamp(window.endsAt)} / ${window.days} days`;
}
function formatFreshness(summary: AdoptionSummary): string {
const freshness = summary.oss.freshness;
if (freshness.status === 'unmeasured' || freshness.ageHours === null) return 'UNMEASURED';
return `${freshness.status.toUpperCase()} · ${freshness.ageHours} h old / ${freshness.maxAgeHours} h limit`;
}
function readError(value: unknown): string {
if (typeof value !== 'object' || value === null || !('error' in value)) return '';
return typeof value.error === 'string' ? value.error : '';
}

View File

@ -10,7 +10,7 @@ export default function PrivacyPage() {
<article className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-16 sm:py-24">
<Badge className="mb-4">Legal</Badge>
<h1 className="text-4xl font-bold mb-4">Privacy Policy</h1>
<p className="text-gray-400 mb-8">Last updated: February 17, 2026</p>
<p className="text-gray-400 mb-8">Last updated: August 23, 2026</p>
<div className="prose prose-invert prose-gray max-w-none">
<section className="mb-12">
@ -57,6 +57,16 @@ export default function PrivacyPage() {
<strong>Important:</strong> Free tier users' data stays entirely local on their machines.
We only store checkpoint data for Pro and Team users who opt into cloud sync.
</p>
<h3 className="text-xl font-medium mb-3 mt-6">Open Source Evidence</h3>
<p className="text-gray-300 mb-4">
Maintainers can submit bounded coverage batches for external contributions and first response times.
The service stores repository, contributor, and contribution references as opaque, secret-keyed HMAC-SHA-256 keys.
</p>
<p className="text-gray-300">
Public adoption reports contain aggregate counts, measurement windows, and status labels. They do not
include account, repository, project, checkpoint, restore, contributor, or contribution identifiers.
</p>
</section>
<section className="mb-12">

View File

@ -11,6 +11,7 @@ const footerLinks = {
],
resources: [
{ name: 'Documentation', href: '/docs' },
{ name: 'Maintainer Evidence', href: '/maintainers' },
{ name: 'Knowledge Base', href: '/knowledge' },
{ name: 'API Reference', href: '/docs#api' },
{ name: 'CLI Guide', href: '/docs#cli' },

View File

@ -18,6 +18,7 @@ const productLinks = [
const navigation = [
{ name: 'Docs', href: '/docs' },
{ name: 'Evidence', href: '/maintainers' },
{ name: 'Pricing', href: '/pricing' },
{ name: 'Blog', href: '/blog' },
];

View File

@ -0,0 +1,61 @@
# Talent Graph production release
This release candidate hardens the existing GitGram opportunity → referral →
pilot → public proof workflow. It does not authorize a database migration or
deployment.
## Wire contract
- Every Talent Graph `POST` and `PATCH` requires an `Idempotency-Key` containing
8–128 visible ASCII characters.
- The key is scoped to authenticated actor and operation. Reusing it with the
same JSON body replays the stored response; reuse with a different body
returns `409`.
- Successful mutations return `Idempotency-Replayed` and
`Idempotency-Key-Expires-In`. Receipts are retained for 30 days.
- Referral and pilot updates require the current positive `expectedRevision`.
Concurrent writes from one revision produce one success and one `409`.
- Cookie-authenticated browser mutations require an exact `CORS_ORIGIN` match.
Bearer-authenticated non-browser clients do not require an Origin header.
## Persistence and public boundary
`20260823000000_add_talent_opportunities` creates the domain tables, optimistic
revision columns, status-transition audit rows, durable mutation receipts, and
`TalentPublicProof`.
`TalentPublicProof` is the only pilot source used by public profile and matching
reads. It exposes an opaque public ID while retaining the internal pilot ID only
as a private projection key. It contains participant ID, normalized evidence
skills, completed time, and a validated public deliverable URL. Organization name, opportunity title,
problem, success metric, feedback, referral identity, and milestones remain in
private operational tables. The projection is inserted, updated, or deleted in
the same transaction as the pilot mutation that changes eligibility.
Public opportunity reads redact the creator identifier and all referral/pilot
operation counts. Authenticated opportunity owners receive those counts through
a private, non-cacheable response. If an institution changes a deliverable URL,
prior participant publication consent is reset and must be granted again.
## Required verification before release
1. Review and apply the Prisma migration to an empty temporary PostgreSQL
database, then generate the Prisma client.
2. Confirm `CORS_ORIGIN` lists exact production web origins and the reverse
proxy strips untrusted forwarding headers.
3. Exercise two accounts: institution creates an opportunity and referral;
participant accepts; institution starts and completes; participant grants
publication consent.
4. Replay every mutation with the same key/body and confirm one domain row plus
one receipt. Reuse the key with a changed body and confirm `409`.
5. Race two referral decisions and two pilot updates from the same revision;
confirm one write wins and the other returns `409`.
6. Confirm revoking consent, clearing the deliverable, cancelling, or leaving a
pilot incomplete removes/withholds `TalentPublicProof`.
7. Inspect public profile and match responses for absence of institution-authored
free text and private workflow identifiers.
8. Verify rollback from backup and document the migration rollback decision.
Build, typecheck, lint, tests, migration execution, server startup, and deploy
were not run while authoring this candidate. The repository-required
`before_action` and `after_action` hooks were unavailable in this environment.

View File

@ -0,0 +1,139 @@
CREATE TYPE "TalentOpportunityStatus" AS ENUM ('OPEN', 'MATCHING', 'PILOT', 'CLOSED');
CREATE TYPE "TalentPilotStatus" AS ENUM ('PLANNED', 'ACTIVE', 'REVIEW', 'COMPLETED', 'CANCELLED');
CREATE TYPE "TalentReferralStatus" AS ENUM ('CONTACTED', 'ACCEPTED', 'DECLINED');
CREATE TABLE "TalentOpportunity" (
"id" TEXT NOT NULL,
"organizationName" TEXT NOT NULL,
"title" TEXT NOT NULL,
"problem" TEXT NOT NULL,
"requiredSkills" TEXT[] NOT NULL,
"successMetric" TEXT NOT NULL,
"durationWeeks" INTEGER NOT NULL DEFAULT 4,
"sourceChannel" TEXT NOT NULL DEFAULT 'direct',
"communityReferralConsent" BOOLEAN NOT NULL DEFAULT false,
"createdById" TEXT NOT NULL,
"status" "TalentOpportunityStatus" NOT NULL DEFAULT 'OPEN',
"revision" INTEGER NOT NULL DEFAULT 1,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "TalentOpportunity_pkey" PRIMARY KEY ("id"),
CONSTRAINT "TalentOpportunity_revision_check" CHECK ("revision" > 0),
CONSTRAINT "TalentOpportunity_durationWeeks_check" CHECK ("durationWeeks" BETWEEN 1 AND 16)
);
CREATE TABLE "TalentPilot" (
"id" TEXT NOT NULL,
"opportunityId" TEXT NOT NULL,
"referralId" TEXT,
"participantId" TEXT NOT NULL,
"status" "TalentPilotStatus" NOT NULL DEFAULT 'PLANNED',
"revision" INTEGER NOT NULL DEFAULT 1,
"milestones" JSONB NOT NULL DEFAULT '[]',
"deliverableUrl" TEXT,
"feedback" TEXT,
"publicEvidenceConsent" BOOLEAN NOT NULL DEFAULT false,
"startedAt" TIMESTAMP(3),
"completedAt" TIMESTAMP(3),
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "TalentPilot_pkey" PRIMARY KEY ("id"),
CONSTRAINT "TalentPilot_revision_check" CHECK ("revision" > 0)
);
CREATE TABLE "TalentReferral" (
"id" TEXT NOT NULL,
"opportunityId" TEXT NOT NULL,
"participantId" TEXT NOT NULL,
"referredById" TEXT NOT NULL,
"status" "TalentReferralStatus" NOT NULL DEFAULT 'CONTACTED',
"revision" INTEGER NOT NULL DEFAULT 1,
"respondedAt" TIMESTAMP(3),
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "TalentReferral_pkey" PRIMARY KEY ("id"),
CONSTRAINT "TalentReferral_revision_check" CHECK ("revision" > 0)
);
CREATE TABLE "TalentPilotStatusTransition" (
"id" TEXT NOT NULL,
"pilotId" TEXT NOT NULL,
"actorId" TEXT NOT NULL,
"previousStatus" "TalentPilotStatus" NOT NULL,
"nextStatus" "TalentPilotStatus" NOT NULL,
"revision" INTEGER NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "TalentPilotStatusTransition_pkey" PRIMARY KEY ("id"),
CONSTRAINT "TalentPilotStatusTransition_revision_check" CHECK ("revision" > 0)
);
CREATE TABLE "TalentPublicProof" (
"pilotId" TEXT NOT NULL,
"publicId" TEXT NOT NULL,
"participantId" TEXT NOT NULL,
"deliverableUrl" TEXT NOT NULL,
"evidenceSkills" TEXT[] NOT NULL,
"completedAt" TIMESTAMP(3) NOT NULL,
"schemaVersion" INTEGER NOT NULL DEFAULT 1,
"publishedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "TalentPublicProof_pkey" PRIMARY KEY ("pilotId"),
CONSTRAINT "TalentPublicProof_schemaVersion_check" CHECK ("schemaVersion" = 1)
);
CREATE TABLE "TalentMutationReceipt" (
"id" TEXT NOT NULL,
"requestFingerprint" TEXT NOT NULL,
"requestHash" TEXT NOT NULL,
"actorId" TEXT NOT NULL,
"operation" TEXT NOT NULL,
"resourceType" TEXT NOT NULL,
"resourceId" TEXT NOT NULL,
"requestId" TEXT NOT NULL,
"response" JSONB NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "TalentMutationReceipt_pkey" PRIMARY KEY ("id")
);
CREATE INDEX "TalentOpportunity_createdById_idx" ON "TalentOpportunity"("createdById");
CREATE INDEX "TalentOpportunity_status_createdAt_idx" ON "TalentOpportunity"("status", "createdAt");
CREATE UNIQUE INDEX "TalentPilot_opportunityId_participantId_key" ON "TalentPilot"("opportunityId", "participantId");
CREATE UNIQUE INDEX "TalentPilot_referralId_key" ON "TalentPilot"("referralId");
CREATE INDEX "TalentPilot_participantId_status_idx" ON "TalentPilot"("participantId", "status");
CREATE UNIQUE INDEX "TalentReferral_opportunityId_participantId_key" ON "TalentReferral"("opportunityId", "participantId");
CREATE INDEX "TalentReferral_participantId_status_idx" ON "TalentReferral"("participantId", "status");
CREATE INDEX "TalentReferral_opportunityId_status_idx" ON "TalentReferral"("opportunityId", "status");
CREATE INDEX "TalentPilotStatusTransition_pilotId_createdAt_idx" ON "TalentPilotStatusTransition"("pilotId", "createdAt");
CREATE INDEX "TalentPilotStatusTransition_actorId_createdAt_idx" ON "TalentPilotStatusTransition"("actorId", "createdAt");
CREATE UNIQUE INDEX "TalentPilotStatusTransition_pilotId_revision_key" ON "TalentPilotStatusTransition"("pilotId", "revision");
CREATE UNIQUE INDEX "TalentPublicProof_publicId_key" ON "TalentPublicProof"("publicId");
CREATE INDEX "TalentPublicProof_participantId_completedAt_idx" ON "TalentPublicProof"("participantId", "completedAt");
CREATE INDEX "TalentPublicProof_evidenceSkills_idx" ON "TalentPublicProof" USING GIN ("evidenceSkills");
CREATE UNIQUE INDEX "TalentMutationReceipt_requestFingerprint_key" ON "TalentMutationReceipt"("requestFingerprint");
CREATE INDEX "TalentMutationReceipt_actorId_createdAt_idx" ON "TalentMutationReceipt"("actorId", "createdAt");
CREATE INDEX "TalentMutationReceipt_resourceType_resourceId_createdAt_idx" ON "TalentMutationReceipt"("resourceType", "resourceId", "createdAt");
ALTER TABLE "TalentPilot"
ADD CONSTRAINT "TalentPilot_opportunityId_fkey"
FOREIGN KEY ("opportunityId") REFERENCES "TalentOpportunity"("id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "TalentReferral"
ADD CONSTRAINT "TalentReferral_opportunityId_fkey"
FOREIGN KEY ("opportunityId") REFERENCES "TalentOpportunity"("id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "TalentPilot"
ADD CONSTRAINT "TalentPilot_referralId_fkey"
FOREIGN KEY ("referralId") REFERENCES "TalentReferral"("id")
ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE "TalentPilotStatusTransition"
ADD CONSTRAINT "TalentPilotStatusTransition_pilotId_fkey"
FOREIGN KEY ("pilotId") REFERENCES "TalentPilot"("id")
ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "TalentPublicProof"
ADD CONSTRAINT "TalentPublicProof_pilotId_fkey"
FOREIGN KEY ("pilotId") REFERENCES "TalentPilot"("id")
ON DELETE CASCADE ON UPDATE CASCADE;

View File

@ -1034,6 +1034,155 @@ model Project {
@@index([owner])
}
enum TalentOpportunityStatus {
OPEN
MATCHING
PILOT
CLOSED
}
enum TalentPilotStatus {
PLANNED
ACTIVE
REVIEW
COMPLETED
CANCELLED
}
enum TalentReferralStatus {
CONTACTED
ACCEPTED
DECLINED
}
/// A structured institution problem that can be matched against public,
/// repository-backed talent evidence. User ids stay scalar so this feature can
/// be extracted into the Zemin360 open-source service without coupling its
/// lifecycle to Gitgram accounts.
model TalentOpportunity {
id String @id @default(cuid())
organizationName String
title String
problem String @db.Text
requiredSkills String[]
successMetric String
durationWeeks Int @default(4)
sourceChannel String @default("direct")
communityReferralConsent Boolean @default(false)
createdById String
status TalentOpportunityStatus @default(OPEN)
revision Int @default(1)
pilots TalentPilot[]
referrals TalentReferral[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@index([createdById])
@@index([status, createdAt])
}
/// Consent-gated community introduction. The participant controls the outcome;
/// public opportunity responses expose aggregate counts rather than identities.
model TalentReferral {
id String @id @default(cuid())
opportunityId String
participantId String
referredById String
status TalentReferralStatus @default(CONTACTED)
revision Int @default(1)
respondedAt DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
opportunity TalentOpportunity @relation(fields: [opportunityId], references: [id], onDelete: Cascade)
pilot TalentPilot?
@@unique([opportunityId, participantId])
@@index([participantId, status])
@@index([opportunityId, status])
}
model TalentPilot {
id String @id @default(cuid())
opportunityId String
referralId String? @unique
participantId String
status TalentPilotStatus @default(PLANNED)
milestones Json @default("[]")
deliverableUrl String?
feedback String? @db.Text
publicEvidenceConsent Boolean @default(false)
revision Int @default(1)
startedAt DateTime?
completedAt DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
opportunity TalentOpportunity @relation(fields: [opportunityId], references: [id], onDelete: Cascade)
referral TalentReferral? @relation(fields: [referralId], references: [id], onDelete: Restrict)
statusTransitions TalentPilotStatusTransition[]
publicProof TalentPublicProof?
@@unique([opportunityId, participantId])
@@index([participantId, status])
}
/// Append-only provenance for every persisted pilot status change. Actor ids
/// remain scalar to preserve the Talent Graph service extraction boundary.
model TalentPilotStatusTransition {
id String @id @default(cuid())
pilotId String
actorId String
previousStatus TalentPilotStatus
nextStatus TalentPilotStatus
revision Int
createdAt DateTime @default(now())
pilot TalentPilot @relation(fields: [pilotId], references: [id], onDelete: Cascade)
@@index([pilotId, createdAt])
@@index([actorId, createdAt])
@@unique([pilotId, revision])
}
/// Privacy-safe projection consumed by public Talent Graph and matching reads.
/// Institution-authored free text never enters this table.
model TalentPublicProof {
pilotId String @id
publicId String @unique @default(cuid())
participantId String
deliverableUrl String
evidenceSkills String[]
completedAt DateTime
schemaVersion Int @default(1)
publishedAt DateTime @default(now())
updatedAt DateTime @updatedAt
pilot TalentPilot @relation(fields: [pilotId], references: [id], onDelete: Cascade)
@@index([participantId, completedAt])
@@index([evidenceSkills], type: Gin)
}
/// Durable idempotency receipt for every Talent Graph mutation. The unique
/// fingerprint scopes a client key to actor + operation; requestHash rejects
/// key reuse with a different body and response provides exact replay.
model TalentMutationReceipt {
id String @id @default(cuid())
requestFingerprint String @unique
requestHash String
actorId String
operation String
resourceType String
resourceId String
requestId String
response Json
createdAt DateTime @default(now())
@@index([actorId, createdAt])
@@index([resourceType, resourceId, createdAt])
}
model Analytics {
id String @id @default(cuid())
accountId String?

View File

@ -0,0 +1,512 @@
import type { Response } from 'express';
import type { AuthRequest } from '../middleware/auth';
import { asyncHandler, Errors } from '../middleware/errorHandler';
import { findTalentMatches, getTalentGraph } from '../services/talentGraphService';
import prisma from '../utils/prisma';
import { normalizePublicHttpUrl } from '../utils/publicHttpUrl';
import { runTalentMutation, type TalentMutationResult } from '../services/talentMutationService';
const PILOT_STATUSES = ['PLANNED', 'ACTIVE', 'REVIEW', 'COMPLETED', 'CANCELLED'] as const;
type PilotStatus = (typeof PILOT_STATUSES)[number];
const PILOT_STATUS_TRANSITIONS: Record<PilotStatus, readonly PilotStatus[]> = {
PLANNED: ['ACTIVE', 'CANCELLED'],
ACTIVE: ['REVIEW', 'COMPLETED', 'CANCELLED'],
REVIEW: ['ACTIVE', 'COMPLETED', 'CANCELLED'],
COMPLETED: [],
CANCELLED: [],
};
const pilotProvenanceInclude = {
opportunity: true,
referral: true,
statusTransitions: { orderBy: { createdAt: 'asc' as const } },
};
function publicHttpUrl(value: unknown) {
const normalized = String(value || '').trim();
if (!normalized) return null;
const url = normalizePublicHttpUrl(normalized);
if (!url) throw Errors.badRequest('Deliverable URL must be a public HTTP or HTTPS URL');
return url;
}
function boundedText(value: unknown, field: string, max: number) {
const text = typeof value === 'string' ? value.trim() : '';
if (!text || text.length > max) throw Errors.invalidField(field, `${field} must contain 1 to ${max} characters`);
return text;
}
function expectedRevision(value: unknown) {
if (!Number.isSafeInteger(value) || Number(value) < 1) {
throw Errors.invalidField('expectedRevision', 'expectedRevision must be a positive integer');
}
return Number(value);
}
function sendMutation<T>(res: Response, result: TalentMutationResult<T>, created = false) {
res.setHeader('Cache-Control', 'no-store');
res.setHeader('Idempotency-Replayed', String(result.replayed));
res.setHeader('Idempotency-Key-Expires-In', String(30 * 24 * 60 * 60));
res.status(created && !result.replayed ? 201 : 200).json({ data: result.value });
}
function publicOpportunity<T extends { createdById: string }>(opportunity: T, viewerId?: string) {
const { createdById, ...publicFields } = opportunity;
return {
...publicFields,
viewerRole: createdById === viewerId ? 'institution' as const : 'public' as const,
};
}
function setViewerAwareReadCache(res: Response, viewerId?: string) {
res.setHeader('Vary', 'Authorization, Cookie');
res.setHeader(
'Cache-Control',
viewerId ? 'no-store, private' : 'public, max-age=30, stale-while-revalidate=60',
);
}
export const talentGraphController = {
getMine: asyncHandler(async (req: AuthRequest, res: Response) => {
const graph = await getTalentGraph(req.userId!);
if (!graph) throw Errors.userNotFound(req.userId);
res.setHeader('Cache-Control', 'no-store, private');
res.json({ data: graph });
}),
getPublic: asyncHandler(async (req: AuthRequest, res: Response) => {
const user = await prisma.user.findUnique({
where: { username: req.params.username },
select: { id: true, isPrivate: true },
});
if (!user || user.isPrivate) throw Errors.userNotFound(req.params.username);
const graph = await getTalentGraph(user.id, { publicView: true });
if (!graph) throw Errors.userNotFound(req.params.username);
res.setHeader('Cache-Control', 'public, max-age=60, stale-while-revalidate=120');
res.setHeader('X-Talent-Proof-Schema', '1');
res.json({ data: graph, meta: { proofSchemaVersion: 1 } });
}),
listOpportunities: asyncHandler(async (req: AuthRequest, res: Response) => {
const opportunities = await prisma.talentOpportunity.findMany({
where: { status: { in: ['OPEN', 'MATCHING', 'PILOT'] } },
include: {
pilots: { select: { status: true } },
referrals: { select: { status: true } },
},
orderBy: { createdAt: 'desc' },
take: 50,
});
setViewerAwareReadCache(res, req.userId);
res.json({
data: opportunities.map(({ pilots, referrals, ...opportunity }) => {
const visible = publicOpportunity(opportunity, req.userId);
if (visible.viewerRole !== 'institution') return visible;
return {
...visible,
pilotSummary: {
total: pilots.length,
active: pilots.filter((pilot) => pilot.status === 'ACTIVE' || pilot.status === 'REVIEW').length,
completed: pilots.filter((pilot) => pilot.status === 'COMPLETED').length,
},
referralSummary: {
total: referrals.length,
contacted: referrals.filter((referral) => referral.status === 'CONTACTED').length,
accepted: referrals.filter((referral) => referral.status === 'ACCEPTED').length,
declined: referrals.filter((referral) => referral.status === 'DECLINED').length,
},
};
}),
});
}),
createOpportunity: asyncHandler(async (req: AuthRequest, res: Response) => {
const organizationName = boundedText(req.body.organizationName, 'organizationName', 160);
const title = boundedText(req.body.title, 'title', 160);
const problem = boundedText(req.body.problem, 'problem', 4000);
const successMetric = boundedText(req.body.successMetric, 'successMetric', 500);
if (!Array.isArray(req.body.requiredSkills) || req.body.requiredSkills.length > 12) {
throw Errors.invalidField('requiredSkills', 'requiredSkills must contain 1 to 12 entries');
}
const normalizedSkills = req.body.requiredSkills.map((skill: unknown, index: number) =>
boundedText(skill, `requiredSkills[${index}]`, 64).toLowerCase());
const requiredSkills = Array.from(new Set(normalizedSkills));
const durationWeeks = req.body.durationWeeks === undefined ? 4 : Number(req.body.durationWeeks);
if (!Number.isInteger(durationWeeks) || durationWeeks < 1 || durationWeeks > 16) {
throw Errors.invalidField('durationWeeks', 'durationWeeks must be an integer from 1 to 16');
}
const allowedSourceChannels = new Set(['direct', 'gitgram', 'zemin360', 'zen-talent']);
const requestedSourceChannel = String(req.body.sourceChannel || 'direct').trim().toLowerCase();
if (!allowedSourceChannels.has(requestedSourceChannel)) {
throw Errors.invalidField('sourceChannel', 'Unknown opportunity source channel');
}
const sourceChannel = requestedSourceChannel;
const communityReferralConsent = req.body.communityReferralConsent === true;
if (requiredSkills.length === 0) throw Errors.missingField('requiredSkills');
const result = await runTalentMutation(req, 'opportunity.create', async (tx) => {
const opportunity = await tx.talentOpportunity.create({
data: {
organizationName,
title,
problem,
successMetric,
requiredSkills,
durationWeeks,
sourceChannel,
communityReferralConsent,
createdById: req.userId!,
revision: 1,
},
});
return {
value: { ...publicOpportunity(opportunity, req.userId), pilotSummary: emptyPilotSummary(), referralSummary: emptyReferralSummary() },
resourceType: 'opportunity' as const,
resourceId: opportunity.id,
};
});
sendMutation(res, result, true);
}),
getOpportunityMatches: asyncHandler(async (req: AuthRequest, res: Response) => {
const opportunity = await prisma.talentOpportunity.findUnique({ where: { id: req.params.id } });
if (!opportunity) throw Errors.notFound('Talent opportunity', req.params.id);
const matches = await findTalentMatches(opportunity.requiredSkills, 12);
setViewerAwareReadCache(res, req.userId);
res.json({ data: { opportunity: publicOpportunity(opportunity, req.userId), matches } });
}),
startPilot: asyncHandler(async (req: AuthRequest, res: Response) => {
const participantId = boundedText(req.body.participantId, 'participantId', 160);
if (participantId === req.userId) throw Errors.badRequest('Opportunity owners cannot verify their own pilot evidence');
const milestones = normalizeStartingMilestones(req.body.milestones);
const startedAt = new Date();
const result = await runTalentMutation(req, `pilot.start:${req.params.id}`, async (tx) => {
const opportunity = await tx.talentOpportunity.findUnique({ where: { id: req.params.id } });
if (!opportunity) throw Errors.notFound('Talent opportunity', req.params.id);
if (opportunity.createdById !== req.userId) throw Errors.forbidden('Only the opportunity owner can start a pilot');
const participant = await tx.user.findFirst({
where: { id: participantId, isPrivate: false, isBanned: false, isSuspended: false },
select: { id: true },
});
if (!participant) throw Errors.userNotFound(participantId);
const referral = opportunity.sourceChannel === 'zen-talent'
? await tx.talentReferral.findUnique({
where: { opportunityId_participantId: { opportunityId: opportunity.id, participantId } },
})
: null;
if (opportunity.sourceChannel === 'zen-talent' && referral?.status !== 'ACCEPTED') {
throw Errors.conflict('The participant must accept the Zen Talent referral before the institution can start a pilot');
}
const created = await tx.talentPilot.create({
data: {
opportunityId: opportunity.id,
referralId: referral?.id,
participantId,
status: 'ACTIVE',
revision: 1,
startedAt,
milestones,
statusTransitions: {
create: {
actorId: req.userId!,
previousStatus: 'PLANNED',
nextStatus: 'ACTIVE',
revision: 1,
createdAt: startedAt,
},
},
},
include: pilotProvenanceInclude,
});
await tx.talentOpportunity.update({
where: { id: opportunity.id },
data: { status: 'PILOT', revision: { increment: 1 } },
});
const value = { ...created, viewerRole: 'institution' as const };
return { value, resourceType: 'pilot' as const, resourceId: created.id };
});
sendMutation(res, result, true);
}),
createReferral: asyncHandler(async (req: AuthRequest, res: Response) => {
const participantId = boundedText(req.body.participantId, 'participantId', 160);
if (participantId === req.userId) throw Errors.badRequest('Opportunity owners cannot refer themselves');
const result = await runTalentMutation(req, `referral.create:${req.params.id}`, async (tx) => {
const currentOpportunity = await tx.talentOpportunity.findUnique({ where: { id: req.params.id } });
if (!currentOpportunity) throw Errors.notFound('Talent opportunity', req.params.id);
if (currentOpportunity.createdById !== req.userId) throw Errors.forbidden('Only the opportunity owner can create a referral');
if (currentOpportunity.sourceChannel !== 'zen-talent' || !currentOpportunity.communityReferralConsent) {
throw Errors.forbidden('Zen Talent referrals require an explicit community referral consent');
}
const participant = await tx.user.findFirst({
where: { id: participantId, isPrivate: false, isBanned: false, isSuspended: false },
select: { id: true },
});
if (!participant) throw Errors.userNotFound(participantId);
const matches = await findTalentMatches(currentOpportunity.requiredSkills, 25, tx);
const participantMatch = matches.find((match) => match.profile.id === participantId);
if (!participantMatch || participantMatch.projects.length === 0) {
throw Errors.badRequest('Participant must have public repository or completed-pilot evidence matching this opportunity');
}
const referral = await tx.talentReferral.upsert({
where: { opportunityId_participantId: { opportunityId: currentOpportunity.id, participantId } },
create: { opportunityId: currentOpportunity.id, participantId, referredById: req.userId!, revision: 1 },
update: {},
include: { opportunity: true },
});
const value = { ...referral, viewerRole: 'institution' as const };
return { value, resourceType: 'referral' as const, resourceId: referral.id };
});
sendMutation(res, result, true);
}),
listMyReferrals: asyncHandler(async (req: AuthRequest, res: Response) => {
const referrals = await prisma.talentReferral.findMany({
where: {
OR: [
{ participantId: req.userId! },
{ opportunity: { createdById: req.userId! } },
],
},
include: { opportunity: true },
orderBy: { updatedAt: 'desc' },
take: 100,
});
res.setHeader('Cache-Control', 'no-store, private');
res.json({
data: referrals.map((referral) => ({
...referral,
viewerRole: referral.participantId === req.userId ? 'participant' : 'institution',
})),
});
}),
updateReferral: asyncHandler(async (req: AuthRequest, res: Response) => {
if (req.body.status !== 'ACCEPTED' && req.body.status !== 'DECLINED') {
throw Errors.badRequest('Referral status must be ACCEPTED or DECLINED');
}
const revision = expectedRevision(req.body.expectedRevision);
const result = await runTalentMutation(req, `referral.respond:${req.params.referralId}`, async (tx) => {
const referral = await tx.talentReferral.findUnique({
where: { id: req.params.referralId },
include: { opportunity: true },
});
if (!referral) throw Errors.notFound('Talent referral', req.params.referralId);
if (referral.participantId !== req.userId) throw Errors.forbidden('Only the referred participant can respond');
if (referral.status !== 'CONTACTED') throw Errors.conflict('A referral decision cannot be changed after the participant responds');
if (referral.revision !== revision) throw Errors.conflict(`Referral changed after revision ${revision}`);
const updatedCount = await tx.talentReferral.updateMany({
where: { id: referral.id, revision, status: 'CONTACTED' },
data: { status: req.body.status, respondedAt: new Date(), revision: { increment: 1 } },
});
if (updatedCount.count !== 1) throw Errors.conflict('Referral changed while the decision was being saved');
const updated = await tx.talentReferral.findUnique({
where: { id: referral.id },
include: { opportunity: true },
});
if (!updated) throw Errors.notFound('Talent referral', referral.id);
const value = { ...updated, viewerRole: 'participant' as const };
return { value, resourceType: 'referral' as const, resourceId: updated.id };
});
sendMutation(res, result);
}),
listMyPilots: asyncHandler(async (req: AuthRequest, res: Response) => {
const pilots = await prisma.talentPilot.findMany({
where: {
OR: [
{ participantId: req.userId! },
{ opportunity: { createdById: req.userId! } },
],
},
include: pilotProvenanceInclude,
orderBy: { updatedAt: 'desc' },
take: 100,
});
res.setHeader('Cache-Control', 'no-store, private');
res.json({
data: pilots.map((pilot) => ({
...pilot,
viewerRole: pilot.participantId === req.userId ? 'participant' : 'institution',
})),
});
}),
updatePilot: asyncHandler(async (req: AuthRequest, res: Response) => {
const revision = expectedRevision(req.body.expectedRevision);
const result = await runTalentMutation(req, `pilot.update:${req.params.pilotId}`, async (tx) => {
const pilot = await tx.talentPilot.findUnique({
where: { id: req.params.pilotId },
include: { opportunity: true },
});
if (!pilot) throw Errors.notFound('Talent pilot', req.params.pilotId);
const isInstitution = pilot.opportunity.createdById === req.userId;
const isParticipant = pilot.participantId === req.userId;
if (!isInstitution && !isParticipant) {
throw Errors.forbidden('Only the institution or participant can update this pilot');
}
if (pilot.revision !== revision) throw Errors.conflict(`Pilot changed after revision ${revision}`);
const requestedStatus = req.body.status as PilotStatus | undefined;
if (requestedStatus !== undefined && !PILOT_STATUSES.includes(requestedStatus)) {
throw Errors.badRequest('Unknown pilot status');
}
if (requestedStatus !== undefined && !isInstitution) {
throw Errors.forbidden('Only the institution can change pilot status');
}
const currentStatus = pilot.status as PilotStatus;
const status = requestedStatus || currentStatus;
if (status !== currentStatus && !PILOT_STATUS_TRANSITIONS[currentStatus].includes(status)) {
throw Errors.conflict(`Pilot status cannot move from ${currentStatus} to ${status}`);
}
const transitionedAt = status !== pilot.status ? new Date() : null;
if (!isInstitution && req.body.milestones !== undefined) {
throw Errors.forbidden('Only the institution can change pilot milestones');
}
const milestones = req.body.milestones === undefined
? pilot.milestones
: normalizeMilestones(req.body.milestones);
const deliverableUrl = req.body.deliverableUrl === undefined
? pilot.deliverableUrl
: publicHttpUrl(req.body.deliverableUrl);
const institutionChangedDeliverable = isInstitution
&& req.body.deliverableUrl !== undefined
&& deliverableUrl !== pilot.deliverableUrl;
const publicEvidenceConsent = institutionChangedDeliverable
? false
: isParticipant && typeof req.body.publicEvidenceConsent === 'boolean'
? req.body.publicEvidenceConsent
: pilot.publicEvidenceConsent;
const feedback = !isInstitution || req.body.feedback === undefined
? pilot.feedback
: optionalBoundedText(req.body.feedback, 'feedback', 4000);
const nextRevision = revision + 1;
const updatedCount = await tx.talentPilot.updateMany({
where: { id: pilot.id, revision },
data: {
status,
milestones,
deliverableUrl,
feedback,
publicEvidenceConsent,
revision: nextRevision,
startedAt: status === 'ACTIVE' ? pilot.startedAt || transitionedAt || new Date() : pilot.startedAt,
completedAt: status === 'COMPLETED' ? pilot.completedAt || transitionedAt || new Date() : pilot.completedAt,
},
});
if (updatedCount.count !== 1) throw Errors.conflict('Pilot changed while the update was being saved');
if (transitionedAt) {
await tx.talentPilotStatusTransition.create({
data: {
pilotId: pilot.id,
actorId: req.userId!,
previousStatus: pilot.status,
nextStatus: status,
revision: nextRevision,
createdAt: transitionedAt,
},
});
}
const current = await tx.talentPilot.findUnique({
where: { id: pilot.id },
include: pilotProvenanceInclude,
});
if (!current) throw Errors.notFound('Talent pilot', pilot.id);
await syncPublicProof(tx, current);
const value = {
...current,
viewerRole: isParticipant ? 'participant' as const : 'institution' as const,
};
return { value, resourceType: 'pilot' as const, resourceId: current.id };
});
sendMutation(res, result);
}),
};
function normalizeMilestones(value: unknown) {
if (!Array.isArray(value)) throw Errors.invalidField('milestones', 'milestones must be an array');
if (value.length > 12) throw Errors.invalidField('milestones', 'milestones must contain at most 12 entries');
return value.map((item, index) => {
if (typeof item !== 'object' || item === null || Array.isArray(item)) {
throw Errors.invalidField('milestones', `milestones[${index}] must be an object`);
}
const row = item as Record<string, unknown>;
return {
title: boundedText(row.title, `milestones[${index}].title`, 160),
completed: row.completed === true,
};
});
}
function normalizeStartingMilestones(value: unknown) {
if (value === undefined) return [];
if (!Array.isArray(value)) throw Errors.invalidField('milestones', 'milestones must be an array');
if (value.length > 12) throw Errors.invalidField('milestones', 'milestones must contain at most 12 entries');
return value.map((item, index) => ({
title: boundedText(item, `milestones[${index}]`, 160),
completed: false,
}));
}
function emptyPilotSummary() {
return { total: 0, active: 0, completed: 0 };
}
function emptyReferralSummary() {
return { total: 0, contacted: 0, accepted: 0, declined: 0 };
}
function optionalBoundedText(value: unknown, field: string, max: number) {
if (value === null || value === '') return null;
return boundedText(value, field, max);
}
async function syncPublicProof(tx: any, pilot: any) {
const deliverableUrl = normalizePublicHttpUrl(pilot.deliverableUrl);
const eligible = pilot.status === 'COMPLETED'
&& pilot.publicEvidenceConsent === true
&& deliverableUrl !== null
&& pilot.completedAt instanceof Date;
if (!eligible) {
await tx.talentPublicProof.deleteMany({ where: { pilotId: pilot.id } });
return;
}
const evidenceSkills = Array.from(new Set(
pilot.opportunity.requiredSkills
.map((skill: string) => skill.trim().toLowerCase())
.filter((skill: string) => skill.length > 0 && skill.length <= 64),
)).slice(0, 12);
await tx.talentPublicProof.upsert({
where: { pilotId: pilot.id },
create: {
pilotId: pilot.id,
participantId: pilot.participantId,
deliverableUrl,
evidenceSkills,
completedAt: pilot.completedAt,
schemaVersion: 1,
},
update: {
participantId: pilot.participantId,
deliverableUrl,
evidenceSkills,
completedAt: pilot.completedAt,
schemaVersion: 1,
},
});
}

View File

@ -92,6 +92,7 @@ import storeRoutes from './routes/store';
import momentsRoutes from './routes/moments';
import feedbackRoutes from './routes/feedback';
import locationRoutes from './routes/location';
import talentGraphRoutes from './routes/talentGraph';
import { trpcMiddleware } from './trpc/adapter';
import { initializeJobs } from './jobs/scheduler';
import logger from './utils/logger';
@ -154,7 +155,7 @@ const corsOptions = {
credentials: true,
optionsSuccessStatus: 200,
methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With'],
allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With', 'Idempotency-Key', 'X-Request-Id'],
};
app.use(cors(corsOptions));
@ -362,6 +363,9 @@ app.use('/api/v1/feedback', feedbackRoutes);
// Location / map discovery (nearby projects/posts/users, geocode, trending)
app.use('/api/v1/location', locationRoutes);
// Verifiable project and collaborator evidence for the Talent Graph dossier
app.use('/api/v1/talent-graph', talentGraphRoutes);
// tRPC API layer (additive — REST routes unchanged, ported from t3-base patterns)
app.use('/trpc', trpcMiddleware);
@ -457,4 +461,3 @@ if (require.main === module) {
}
export { io, app };

View File

@ -0,0 +1,41 @@
import { Router, type NextFunction, type Request, type Response } from 'express';
import { authenticate, optionalAuth } from '../middleware/auth';
import { talentGraphController } from '../controllers/talentGraphController';
import { interactionLimiter } from '../middleware/rateLimiter';
import { Errors } from '../middleware/errorHandler';
const router = Router();
function requireMutationOrigin(req: Request, _res: Response, next: NextFunction) {
if (req.headers.authorization?.startsWith('Bearer ')) return next();
const origin = req.get('origin');
const configured = (process.env.CORS_ORIGIN || '').split(',').map((value) => value.trim()).filter(Boolean);
const allowed = new Set(configured);
if (process.env.NODE_ENV !== 'production') {
allowed.add('http://localhost:3000');
allowed.add('http://localhost:3001');
allowed.add('http://127.0.0.1:3000');
allowed.add('http://127.0.0.1:3001');
}
if (allowed.size === 0) return next(Errors.serviceUnavailable('Talent Graph origin policy'));
if (!origin || !allowed.has(origin)) return next(Errors.forbidden('Cross-origin Talent Graph mutation refused'));
const fetchSite = req.get('sec-fetch-site');
if (fetchSite && fetchSite !== 'same-origin' && fetchSite !== 'same-site') {
return next(Errors.forbidden('Cross-site Talent Graph mutation refused'));
}
return next();
}
router.get('/me', authenticate, talentGraphController.getMine);
router.get('/public/:username', talentGraphController.getPublic);
router.get('/opportunities', optionalAuth, talentGraphController.listOpportunities);
router.post('/opportunities', authenticate, requireMutationOrigin, interactionLimiter, talentGraphController.createOpportunity);
router.get('/opportunities/:id/matches', optionalAuth, talentGraphController.getOpportunityMatches);
router.post('/opportunities/:id/pilots', authenticate, requireMutationOrigin, interactionLimiter, talentGraphController.startPilot);
router.post('/opportunities/:id/referrals', authenticate, requireMutationOrigin, interactionLimiter, talentGraphController.createReferral);
router.get('/referrals/mine', authenticate, talentGraphController.listMyReferrals);
router.patch('/referrals/:referralId', authenticate, requireMutationOrigin, interactionLimiter, talentGraphController.updateReferral);
router.get('/pilots/mine', authenticate, talentGraphController.listMyPilots);
router.patch('/pilots/:pilotId', authenticate, requireMutationOrigin, interactionLimiter, talentGraphController.updatePilot);
export default router;

View File

@ -0,0 +1,520 @@
import prisma from '../utils/prisma';
import { normalizePublicHttpUrl } from '../utils/publicHttpUrl';
import type { PrismaClient } from '@prisma/client';
type EvidenceLevel = 'verified' | 'linked' | 'recorded';
interface TalentEvidence {
id: string;
kind: 'repository_claim' | 'github_sync' | 'github_activity' | 'project_record' | 'institutional_pilot';
label: string;
detail: string;
occurredAt: Date;
sourceUrl: string | null;
}
interface TalentProject {
id: string;
source: 'repository' | 'project';
name: string;
fullName: string;
description: string | null;
url: string | null;
language: string | null;
topics: string[];
stars: number;
forks: number;
role: string;
verificationLevel: EvidenceLevel;
lastVerifiedAt: Date;
evidence: TalentEvidence[];
}
interface TalentMatchProject {
id: string;
fullName: string;
url: string;
matchedSkills: string[];
verificationLevel: EvidenceLevel;
}
interface CompletedPilotEvidence {
id: string;
deliverableUrl: string;
occurredAt: Date;
title: string | null;
organizationName: string | null;
problem: string | null;
requiredSkills: string[];
successMetric: string | null;
}
type TalentMatchDb = Pick<PrismaClient, 'talentPublicProof' | 'user'>;
function normalizeSkill(value: string) {
return value.trim().toLowerCase();
}
function projectKey(owner: string | null, name: string, fullName: string | null) {
return (fullName || (owner ? `${owner}/${name}` : name)).toLowerCase();
}
export async function getTalentGraph(userId: string, options: { publicView?: boolean } = {}) {
const [user, syncedProjects, managedRepositories] = await Promise.all([
prisma.user.findUnique({
where: { id: userId },
select: {
id: true,
username: true,
displayName: true,
avatar: true,
avatarUrl: true,
bio: true,
githubId: true,
githubUsername: true,
createdAt: true,
},
}),
prisma.project.findMany({
where: { userId },
orderBy: [{ stars: 'desc' }, { updatedAt: 'desc' }],
}),
prisma.repositoryManager.findMany({
where: { userId },
include: {
repository: {
include: {
managers: {
include: {
user: {
select: {
id: true,
username: true,
displayName: true,
avatar: true,
avatarUrl: true,
githubUsername: true,
isPrivate: true,
},
},
},
},
},
},
},
orderBy: { createdAt: 'asc' },
}),
]);
if (!user) return null;
// Public reads consume the privacy-safe projection only. Owner reads retain
// institution context from the private pilot record.
const completedPilots: CompletedPilotEvidence[] = options.publicView
? (await prisma.talentPublicProof.findMany({
where: { participantId: userId, schemaVersion: 1 },
orderBy: { completedAt: 'desc' },
})).flatMap((proof) => {
const deliverableUrl = normalizePublicHttpUrl(proof.deliverableUrl);
return deliverableUrl ? [{
id: proof.publicId,
deliverableUrl,
occurredAt: proof.completedAt,
title: null,
organizationName: null,
problem: null,
requiredSkills: [],
successMetric: null,
}] : [];
})
: (await prisma.talentPilot.findMany({
where: {
participantId: userId,
status: 'COMPLETED',
publicEvidenceConsent: true,
deliverableUrl: { not: null },
},
include: { opportunity: true },
orderBy: { completedAt: 'desc' },
})).flatMap((pilot) => {
const deliverableUrl = normalizePublicHttpUrl(pilot.deliverableUrl);
return deliverableUrl ? [{
id: pilot.id,
deliverableUrl,
occurredAt: pilot.completedAt || pilot.updatedAt,
title: pilot.opportunity.title,
organizationName: pilot.opportunity.organizationName,
problem: pilot.opportunity.problem,
requiredSkills: pilot.opportunity.requiredSkills,
successMetric: pilot.opportunity.successMetric,
}] : [];
});
const visibleManagedRepositories = options.publicView
? managedRepositories.filter((manager) => !manager.repository.isPrivate)
: managedRepositories;
const repositoryIds = visibleManagedRepositories.map((manager) => manager.repositoryId);
const githubActivity = user.githubUsername && repositoryIds.length > 0
? await prisma.repositoryActivity.findMany({
where: {
repositoryId: { in: repositoryIds },
actorLogin: user.githubUsername,
},
select: {
id: true,
repositoryId: true,
eventType: true,
action: true,
title: true,
url: true,
occurredAt: true,
},
orderBy: { occurredAt: 'desc' },
})
: [];
const activityByRepository = new Map<string, typeof githubActivity>();
for (const activity of githubActivity) {
const activities = activityByRepository.get(activity.repositoryId) || [];
activities.push(activity);
activityByRepository.set(activity.repositoryId, activities);
}
const projects = new Map<string, TalentProject>();
// Project does not store repository visibility. Keep these owner-only rather
// than risk publishing a private repository imported from GitHub.
for (const project of options.publicView ? [] : syncedProjects) {
const fullName = project.fullName || (project.owner ? `${project.owner}/${project.name}` : project.name);
const linked = Boolean(project.githubId && user.githubId);
const evidence: TalentEvidence = linked
? {
id: `github-sync:${project.id}`,
kind: 'github_sync',
label: 'Linked GitHub project',
detail: 'Imported through the connected GitHub account.',
occurredAt: project.updatedAt,
sourceUrl: project.url || project.repoUrl,
}
: {
id: `project-record:${project.id}`,
kind: 'project_record',
label: 'Gitgram project record',
detail: 'Project details saved by this Gitgram account.',
occurredAt: project.updatedAt,
sourceUrl: project.url || project.repoUrl,
};
projects.set(projectKey(project.owner, project.name, project.fullName), {
id: project.id,
source: 'project',
name: project.name,
fullName,
description: project.description,
url: project.url || project.repoUrl,
language: project.language,
topics: project.tags,
stars: project.stars,
forks: project.forks,
role: 'OWNER',
verificationLevel: linked ? 'linked' : 'recorded',
lastVerifiedAt: project.updatedAt,
evidence: [evidence],
});
}
for (const manager of visibleManagedRepositories) {
const repository = manager.repository;
const activityEvidence: TalentEvidence[] = (activityByRepository.get(repository.id) || [])
.slice(0, 8)
.map((activity) => ({
id: activity.id,
kind: 'github_activity',
label: activity.eventType.split('_').join(' '),
detail: activity.title || activity.action || `GitHub ${activity.eventType.toLowerCase().split('_').join(' ')} event`,
occurredAt: activity.occurredAt,
sourceUrl: activity.url,
}));
const claimedByUser = repository.claimedBy === userId;
const claimEvidence: TalentEvidence = claimedByUser && repository.claimedAt
? {
id: `repository-claim:${repository.id}`,
kind: 'repository_claim',
label: 'Repository ownership verified',
detail: 'GitHub write access was confirmed when this repository was claimed.',
occurredAt: repository.claimedAt,
sourceUrl: repository.htmlUrl,
}
: {
id: `repository-manager:${manager.id}`,
kind: 'project_record',
label: `${manager.role.toLowerCase()} access recorded`,
detail: 'Maintainer access is recorded in Gitgram for this repository.',
occurredAt: manager.createdAt,
sourceUrl: repository.htmlUrl,
};
const key = repository.fullName.toLowerCase();
const existing = projects.get(key);
projects.set(key, {
id: repository.id,
source: 'repository',
name: repository.name,
fullName: repository.fullName,
description: repository.description || existing?.description || null,
url: repository.htmlUrl,
language: repository.language || existing?.language || null,
topics: repository.topics.length > 0 ? repository.topics : existing?.topics || [],
stars: repository.stars || existing?.stars || 0,
forks: repository.forks || existing?.forks || 0,
role: manager.role,
verificationLevel: claimedByUser ? 'verified' : existing?.verificationLevel || 'recorded',
lastVerifiedAt: repository.lastFetched || repository.lastSynced || claimEvidence.occurredAt,
evidence: [claimEvidence, ...activityEvidence, ...(existing?.evidence || [])],
});
}
for (const pilot of completedPilots) {
if (!pilot.deliverableUrl) continue;
const occurredAt = pilot.occurredAt;
const publicPilot = options.publicView === true;
projects.set(`institutional-pilot:${pilot.id}`, {
id: pilot.id,
source: 'project',
name: publicPilot ? 'Institutional pilot' : pilot.title || 'Institutional pilot',
fullName: publicPilot
? 'Completed institutional pilot'
: `${pilot.organizationName || 'Institution'} / ${pilot.title || 'Pilot'}`,
description: publicPilot ? null : pilot.problem,
url: pilot.deliverableUrl,
language: null,
// Required skills are institution-authored strings. Keep them out of the
// public dossier because they can contain names or other free text.
topics: publicPilot ? [] : pilot.requiredSkills,
stars: 0,
forks: 0,
role: 'PILOT PARTICIPANT',
verificationLevel: 'verified',
lastVerifiedAt: occurredAt,
evidence: [{
id: `institutional-pilot:${pilot.id}`,
kind: 'institutional_pilot',
label: 'Completed institutional pilot',
detail: publicPilot
? 'Completion was recorded by the institution and publication was approved by the participant.'
: `Completed against the institution's published success metric: ${pilot.successMetric || 'recorded outcome'}`,
occurredAt,
sourceUrl: pilot.deliverableUrl,
}],
});
}
const collaborators = new Map<string, {
id: string;
username: string | null;
displayName: string | null;
avatarUrl: string | null;
githubUsername: string | null;
sharedProjects: Array<{
id: string;
fullName: string;
url: string;
theirRole: string;
yourRole: string;
}>;
}>();
for (const manager of visibleManagedRepositories) {
for (const peer of manager.repository.managers) {
if (peer.userId === userId) continue;
if (options.publicView && peer.user.isPrivate) continue;
const collaborator = collaborators.get(peer.userId) || {
id: peer.user.id,
username: peer.user.username,
displayName: peer.user.displayName,
avatarUrl: peer.user.avatarUrl || peer.user.avatar,
githubUsername: peer.user.githubUsername,
sharedProjects: [],
};
collaborator.sharedProjects.push({
id: manager.repository.id,
fullName: manager.repository.fullName,
url: manager.repository.htmlUrl,
theirRole: peer.role,
yourRole: manager.role,
});
collaborators.set(peer.userId, collaborator);
}
}
const talentProjects = Array.from(projects.values()).sort((a, b) => {
const levelOrder: Record<EvidenceLevel, number> = { verified: 0, linked: 1, recorded: 2 };
return levelOrder[a.verificationLevel] - levelOrder[b.verificationLevel]
|| b.lastVerifiedAt.getTime() - a.lastVerifiedAt.getTime();
});
const talentCollaborators = Array.from(collaborators.values()).sort(
(a, b) => b.sharedProjects.length - a.sharedProjects.length,
);
return {
profile: {
id: user.id,
username: user.username,
displayName: user.displayName,
avatarUrl: user.avatarUrl || user.avatar,
bio: user.bio,
githubUsername: user.githubUsername,
githubConnected: Boolean(user.githubId),
memberSince: user.createdAt,
},
summary: {
projectCount: talentProjects.length,
verifiedProjectCount: talentProjects.filter((project) => project.verificationLevel === 'verified').length,
recordedActivityCount: githubActivity.length,
collaboratorCount: talentCollaborators.length,
},
projects: talentProjects,
collaborators: talentCollaborators,
generatedAt: new Date(),
};
}
export async function findTalentMatches(requiredSkills: string[], limit = 12, db: TalentMatchDb = prisma) {
const skills = Array.from(new Set(requiredSkills.map(normalizeSkill).filter(Boolean))).slice(0, 12);
if (skills.length === 0) return [];
const completedPilots = await db.talentPublicProof.findMany({
where: {
schemaVersion: 1,
evidenceSkills: { hasSome: skills },
},
orderBy: { completedAt: 'desc' },
take: 200,
});
const pilotParticipantIds = Array.from(new Set(completedPilots.map((pilot) => pilot.participantId)));
const pilotsByParticipant = new Map<string, typeof completedPilots>();
for (const pilot of completedPilots) {
const participantPilots = pilotsByParticipant.get(pilot.participantId) || [];
participantPilots.push(pilot);
pilotsByParticipant.set(pilot.participantId, participantPilots);
}
const users = await db.user.findMany({
where: {
isPrivate: false,
isBanned: false,
isSuspended: false,
username: { not: null },
OR: [
{ interests: { hasSome: skills } },
...(pilotParticipantIds.length > 0 ? [{ id: { in: pilotParticipantIds } }] : []),
{
managedRepos: {
some: {
repository: {
isPrivate: false,
OR: [
{ topics: { hasSome: skills } },
{ language: { in: skills, mode: 'insensitive' } },
],
},
},
},
},
],
},
select: {
id: true,
username: true,
displayName: true,
avatar: true,
avatarUrl: true,
bio: true,
githubUsername: true,
interests: true,
managedRepos: {
where: { repository: { isPrivate: false } },
select: {
role: true,
repository: {
select: {
id: true,
fullName: true,
htmlUrl: true,
language: true,
topics: true,
claimedBy: true,
lastFetched: true,
lastSynced: true,
},
},
},
},
},
take: Math.min(100, limit * 6),
});
return users
.map((user) => {
const interestMatches = user.interests.map(normalizeSkill).filter((skill) => skills.includes(skill));
const repositoryProjects: TalentMatchProject[] = user.managedRepos.flatMap((manager) => {
const repositorySkills = [manager.repository.language || '', ...manager.repository.topics].map(normalizeSkill);
const matchedSkills = skills.filter((skill) => repositorySkills.includes(skill));
if (matchedSkills.length === 0) return [];
return [{
id: manager.repository.id,
fullName: manager.repository.fullName,
url: manager.repository.htmlUrl,
matchedSkills,
verificationLevel: manager.repository.claimedBy === user.id ? 'verified' : 'recorded',
} satisfies TalentMatchProject];
});
const pilotProjects: TalentMatchProject[] = (pilotsByParticipant.get(user.id) || []).flatMap((pilot) => {
const deliverableUrl = normalizePublicHttpUrl(pilot.deliverableUrl);
if (!deliverableUrl) return [];
const matchedSkills = skills.filter((skill) => pilot.evidenceSkills.map(normalizeSkill).includes(skill));
if (matchedSkills.length === 0) return [];
return [{
id: pilot.publicId,
// Match responses are public. Never disclose institution-authored
// organization, title, problem, or success-metric text through proof.
fullName: 'Completed institutional pilot',
url: deliverableUrl,
matchedSkills,
verificationLevel: 'verified',
} satisfies TalentMatchProject];
});
const projects = [...pilotProjects, ...repositoryProjects];
const evidenceSkills = Array.from(new Set(projects.flatMap((project) => project.matchedSkills)));
const matchedSkills = Array.from(new Set([...evidenceSkills, ...interestMatches]));
const verifiedProjects = projects.filter((project) => project.verificationLevel === 'verified').length;
const coverage = matchedSkills.length / skills.length;
const score = Math.min(100, Math.round(coverage * 75 + Math.min(verifiedProjects, 2) * 10 + Math.min(projects.length, 3) * 5));
return {
profile: {
id: user.id,
username: user.username!,
displayName: user.displayName,
avatarUrl: user.avatarUrl || user.avatar,
bio: user.bio,
githubUsername: user.githubUsername,
},
score,
matchedSkills,
missingSkills: skills.filter((skill) => !matchedSkills.includes(skill)),
projects: projects.slice(0, 4),
reason: pilotProjects.length > 0
? `${evidenceSkills.length} aranan beceri tamamlanmış kurum pilotu veya açık depo kanıtıyla eşleşiyor.`
: evidenceSkills.length > 0
? `${evidenceSkills.length} aranan beceri herkese açık depo kanıtıyla eşleşiyor.`
: `${interestMatches.length} aranan beceri profil ilgi alanıyla eşleşiyor; depo kanıtı henüz yok.`,
};
})
.filter((match) => match.matchedSkills.length > 0)
.sort((a, b) => b.score - a.score || b.projects.length - a.projects.length)
.slice(0, Math.max(1, Math.min(limit, 25)));
}

View File

@ -0,0 +1,116 @@
import { createHash, randomUUID } from 'node:crypto';
import type { AuthRequest } from '../middleware/auth';
import { Errors } from '../middleware/errorHandler';
import prisma from '../utils/prisma';
interface MutationResource<T> {
value: T;
resourceType: 'opportunity' | 'referral' | 'pilot';
resourceId: string;
}
export interface TalentMutationResult<T> {
value: T;
replayed: boolean;
}
const RECEIPT_RETENTION_DAYS = 30;
export function requireIdempotencyKey(req: AuthRequest): string {
const raw = req.get('idempotency-key')?.trim() || '';
if (raw.length < 8 || raw.length > 128 || !/^[\x21-\x7e]+$/.test(raw)) {
throw Errors.invalidField('Idempotency-Key', 'Idempotency-Key must contain 8 to 128 visible characters');
}
return raw;
}
export async function runTalentMutation<T>(
req: AuthRequest,
operation: string,
execute: (tx: any) => Promise<MutationResource<T>>,
): Promise<TalentMutationResult<T>> {
const actorId = req.userId!;
const idempotencyKey = requireIdempotencyKey(req);
const requestFingerprint = sha256(`${actorId}\n${operation}\n${idempotencyKey}`);
const requestHash = sha256(canonicalJson(req.body ?? {}));
const requestId = String((req as AuthRequest & { requestId?: string }).requestId || req.get('x-request-id') || randomUUID()).slice(0, 128);
for (let attempt = 0; attempt < 3; attempt += 1) {
try {
return await prisma.$transaction(async (tx: any) => {
const receipt = await tx.talentMutationReceipt.findUnique({
where: { requestFingerprint },
select: { requestHash: true, response: true },
});
if (receipt) return replayReceipt<T>(receipt, requestHash);
const resource = await execute(tx);
const response = toJson(resource.value);
await tx.talentMutationReceipt.create({
data: {
requestFingerprint,
requestHash,
actorId,
operation,
resourceType: resource.resourceType,
resourceId: resource.resourceId,
requestId,
response,
},
});
await tx.talentMutationReceipt.deleteMany({
where: { createdAt: { lt: new Date(Date.now() - RECEIPT_RETENTION_DAYS * 24 * 60 * 60 * 1000) } },
});
return { value: resource.value, replayed: false };
}, { isolationLevel: 'Serializable', maxWait: 5_000, timeout: 15_000 });
} catch (error) {
if (isPrismaCode(error, 'P2034') && attempt < 2) continue;
if (isPrismaCode(error, 'P2002')) {
const receipt = await prisma.talentMutationReceipt.findUnique({
where: { requestFingerprint },
select: { requestHash: true, response: true },
});
if (receipt) return replayReceipt<T>(receipt, requestHash);
throw Errors.conflict('A conflicting Talent Graph record already exists');
}
throw error;
}
}
throw Errors.conflict('The mutation could not be serialized. Retry with the same Idempotency-Key');
}
function replayReceipt<T>(
receipt: { requestHash: string; response: unknown },
requestHash: string,
): TalentMutationResult<T> {
if (receipt.requestHash !== requestHash) {
throw Errors.conflict('This Idempotency-Key was already used with a different request');
}
return { value: receipt.response as T, replayed: true };
}
function toJson<T>(value: T): T {
return JSON.parse(JSON.stringify(value)) as T;
}
function canonicalJson(value: unknown): string {
if (value === null) return 'null';
if (typeof value === 'string' || typeof value === 'boolean') return JSON.stringify(value);
if (typeof value === 'number') return Number.isFinite(value) ? JSON.stringify(value) : 'null';
if (typeof value !== 'object') return 'null';
if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`;
const record = value as Record<string, unknown>;
return `{${Object.keys(record)
.filter((key) => record[key] !== undefined)
.sort()
.map((key) => `${JSON.stringify(key)}:${canonicalJson(record[key])}`)
.join(',')}}`;
}
function sha256(value: string): string {
return createHash('sha256').update(value, 'utf8').digest('hex');
}
function isPrismaCode(error: unknown, code: string): boolean {
return typeof error === 'object' && error !== null && 'code' in error && (error as { code?: unknown }).code === code;
}

View File

@ -0,0 +1,61 @@
import { isIP } from 'node:net';
function isPrivateIpv4(hostname: string) {
const octets = hostname.split('.').map(Number);
const [first, second, third] = octets;
return first === 0
|| first === 10
|| first === 127
|| (first === 169 && second === 254)
|| (first === 172 && second >= 16 && second <= 31)
|| (first === 192 && second === 0)
|| (first === 192 && second === 168)
|| (first === 192 && second === 88 && third === 99)
|| (first === 100 && second >= 64 && second <= 127)
|| (first === 198 && (second === 18 || second === 19 || (second === 51 && third === 100)))
|| (first === 203 && second === 0 && third === 113)
|| first >= 224;
}
function isPrivateIpv6(hostname: string) {
const normalized = hostname.replace(/^\[|\]$/g, '').toLowerCase();
return normalized === '::'
|| normalized === '::1'
|| normalized.startsWith('::ffff:')
|| normalized.startsWith('fc')
|| normalized.startsWith('fd')
|| normalized.startsWith('fe8')
|| normalized.startsWith('fe9')
|| normalized.startsWith('fea')
|| normalized.startsWith('feb')
|| normalized.startsWith('ff')
|| normalized.startsWith('2001:db8:');
}
/** Returns a canonical, externally addressable HTTP(S) URL or null. */
export function normalizePublicHttpUrl(value: unknown): string | null {
const normalized = String(value || '').trim();
if (!normalized) return null;
try {
const url = new URL(normalized);
if (url.protocol !== 'https:' && url.protocol !== 'http:') return null;
if (url.username || url.password) return null;
const hostname = url.hostname.toLowerCase().replace(/\.$/, '');
if (!hostname
|| hostname === 'localhost'
|| hostname.endsWith('.localhost')
|| hostname.endsWith('.local')
|| hostname.endsWith('.internal')) return null;
const ipVersion = isIP(hostname.replace(/^\[|\]$/g, ''));
if ((ipVersion === 4 && isPrivateIpv4(hostname))
|| (ipVersion === 6 && isPrivateIpv6(hostname))) return null;
return url.toString();
} catch {
return null;
}
}

View File

@ -43,3 +43,23 @@ web/
└── lib/ # Utilities
```
## Talent Graph proof route
[`/talent-network`](./app/talent-network/page.tsx) presents one API-backed route:
1. Institution need from `GET /v1/talent-graph/opportunities`
2. Evidence matches from `GET /v1/talent-graph/opportunities/:id/matches`
3. Candidate-controlled Zen referral from `GET /v1/talent-graph/referrals/mine`
4. Pilot delivery and audit history from `GET /v1/talent-graph/pilots/mine`
5. Eligible public proof in the owner [`/collaborate`](./app/collaborate/page.tsx) dossier
Public pilot evidence requires a `COMPLETED` pilot, participant consent, and a public HTTP(S) deliverable. The client does not seed records. A zero count comes from the API; the screen renders request failures as an unavailable state with a retry action.
All Talent Graph writes now carry a retry-stable `Idempotency-Key`. Referral and
pilot updates also send the revision read from the API, so concurrent decisions
or edits fail with `409` instead of overwriting one another. Public profile and
matching reads consume the dedicated `TalentPublicProof` projection rather than
joining private opportunity/pilot records at request time. See the backend
[release runbook](../backend/docs/TALENT_GRAPH_RELEASE.md).
The owner dossier creates `/collaborate?profile=<username>` only when the account has a public username. Browser validation still needs two accounts for referral acceptance and institution completion, forced API failures for each resource, responsive anchor review, and public-link checks. The current hackathon cycle forbids build, test, lint, CI, migrations, and app-server runs.

View File

@ -1,183 +1,387 @@
'use client';
'use client'
import { useState, useEffect, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { useAuthStore } from '@/store/authStore';
import { useToast } from '@/components/ui/toast';
import api from '@/services/api';
import { useCallback, useEffect, useMemo, useState } from 'react'
import Link from 'next/link'
import { useRouter, useSearchParams } from 'next/navigation'
import { githubService } from '@/services/githubService'
import {
talentGraphService,
type TalentGraph,
type TalentProject,
type TalentVerificationLevel,
} from '@/services/talentGraphService'
import { useAuthStore } from '@/store/authStore'
import { useToast } from '@/components/ui/toast'
interface Collaboration {
id: string;
username: string;
repoName: string;
role: string;
createdAt: string;
const verificationCopy: Record<TalentVerificationLevel, string> = {
verified: 'WRITE ACCESS VERIFIED',
linked: 'GITHUB LINKED',
recorded: 'ACCOUNT RECORDED',
}
export default function CollaboratePage() {
const router = useRouter();
const { isAuthenticated } = useAuthStore();
const { showToast } = useToast();
function formatDate(value: string) {
return new Intl.DateTimeFormat('en', {
day: '2-digit',
month: 'short',
year: 'numeric',
}).format(new Date(value))
}
const [collaborations, setCollaborations] = useState<Collaboration[]>([]);
const [username, setUsername] = useState('');
const [repoId, setRepoId] = useState('');
const [role, setRole] = useState('contributor');
const [loading, setLoading] = useState(true);
const [inviting, setInviting] = useState(false);
const [removingId, setRemovingId] = useState<string | null>(null);
useEffect(() => {
if (!isAuthenticated) router.replace('/login');
}, [isAuthenticated, router]);
const loadCollaborations = useCallback(async () => {
try {
setLoading(true);
const response = await api.get('/v1/collaborations');
setCollaborations(response.data.collaborations ?? []);
} catch (error: unknown) {
const message = error instanceof Error ? error.message : 'Failed to load collaborations';
showToast(message, 'error');
} finally {
setLoading(false);
}
}, [showToast]);
useEffect(() => {
if (isAuthenticated) {
loadCollaborations();
}
}, [isAuthenticated, loadCollaborations]);
if (!isAuthenticated) return null;
const handleInvite = async (e: React.FormEvent) => {
e.preventDefault();
if (!username.trim() || !repoId.trim()) {
showToast('Username and repository are required', 'warning');
return;
}
try {
setInviting(true);
await api.post('/v1/collaborations/invite', { username, repoId, role });
showToast(`Invitation sent to ${username}`, 'success');
setUsername('');
setRepoId('');
setRole('contributor');
await loadCollaborations();
} catch (error: unknown) {
const message = error instanceof Error ? error.message : 'Failed to send invitation';
showToast(message, 'error');
} finally {
setInviting(false);
}
};
const handleRemove = async (id: string) => {
try {
setRemovingId(id);
await api.delete(`/v1/collaborations/${id}`);
setCollaborations((prev) => prev.filter((c) => c.id !== id));
showToast('Collaborator removed', 'success');
} catch (error: unknown) {
const message = error instanceof Error ? error.message : 'Failed to remove collaborator';
showToast(message, 'error');
} finally {
setRemovingId(null);
}
};
function getErrorMessage(error: unknown) {
if (typeof error === 'object' && error && 'response' in error) {
const response = (error as { response?: { data?: { error?: { message?: string } } } }).response
if (response?.data?.error?.message) return response.data.error.message
}
return error instanceof Error ? error.message : 'Talent Graph could not be loaded.'
}
function ProjectFolio({ project, index }: { project: TalentProject; index: number }) {
return (
<div className="max-w-4xl mx-auto p-8">
<h1 className="text-3xl font-bold mb-8 text-foreground">Collaboration</h1>
<div className="bg-card p-6 rounded-lg border border-border mb-8">
<h2 className="text-xl font-bold mb-4 text-foreground">Invite Collaborators</h2>
<form onSubmit={handleInvite} className="space-y-4">
<div className="flex gap-4">
<input
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
placeholder="Username"
className="flex-1 border border-border rounded px-4 py-2 bg-muted text-foreground"
required
/>
<input
type="text"
value={repoId}
onChange={(e) => setRepoId(e.target.value)}
placeholder="Repository ID"
className="flex-1 border border-border rounded px-4 py-2 bg-muted text-foreground"
required
/>
</div>
<div className="flex gap-4 items-center">
<select
value={role}
onChange={(e) => setRole(e.target.value)}
className="border border-border rounded px-4 py-2 bg-muted text-foreground"
>
<option value="viewer">Viewer</option>
<option value="contributor">Contributor</option>
<option value="admin">Admin</option>
</select>
<button
type="submit"
disabled={inviting}
className="bg-primary text-white px-6 py-2 rounded disabled:opacity-50"
>
{inviting ? 'Sending...' : 'Send Invite'}
</button>
</div>
</form>
<article className="grid border-t border-black lg:grid-cols-[96px_1fr_300px]">
<div className="border-b border-black px-4 py-5 font-mono text-xs lg:border-b-0 lg:border-r">
P-{String(index + 1).padStart(2, '0')}
</div>
<div className="bg-card p-6 rounded-lg border border-border">
<h2 className="text-xl font-bold mb-4 text-foreground">Active Collaborations</h2>
{loading ? (
<div className="space-y-4">
{[1, 2, 3].map((i) => (
<div key={i} className="flex items-center justify-between p-4 rounded-lg bg-muted animate-pulse">
<div className="space-y-2">
<div className="h-4 w-32 bg-border rounded" />
<div className="h-3 w-24 bg-border rounded" />
</div>
<div className="h-8 w-20 bg-border rounded" />
</div>
))}
<div className="border-b border-black px-4 py-5 lg:border-b-0 lg:border-r lg:px-7 lg:py-7">
<div className="mb-5 flex flex-wrap items-start justify-between gap-4">
<div>
<p className="mb-1 font-mono text-[11px] uppercase tracking-[0.16em] text-black/55">
{project.role} · {project.source}
</p>
<h3 className="break-words text-2xl font-semibold tracking-[-0.04em] sm:text-3xl">
{project.fullName}
</h3>
</div>
) : collaborations.length === 0 ? (
<div className="text-muted text-center py-8">
No active collaborations yet
</div>
) : (
<div className="space-y-4">
{collaborations.map((collab) => (
<div
key={collab.id}
className="flex items-center justify-between p-4 rounded-lg border border-border bg-muted"
>
<div>
<p className="font-medium text-foreground">{collab.username}</p>
<p className="text-sm text-muted">
{collab.repoName} - {collab.role}
</p>
</div>
<button
onClick={() => handleRemove(collab.id)}
disabled={removingId === collab.id}
className="bg-error text-white px-4 py-1.5 rounded text-sm disabled:opacity-50"
>
{removingId === collab.id ? 'Removing...' : 'Remove'}
</button>
</div>
<span className="bg-[#0038ff] px-3 py-2 font-mono text-[10px] font-semibold tracking-[0.12em] text-white">
{verificationCopy[project.verificationLevel]}
</span>
</div>
<p className="max-w-2xl text-sm leading-6 text-black/70">
{project.description || 'No repository description has been recorded.'}
</p>
<div className="mt-6 flex flex-wrap gap-x-6 gap-y-2 border-t border-black/20 pt-4 font-mono text-[11px] uppercase tracking-[0.08em]">
<span>{project.language || 'Language not recorded'}</span>
<span>{project.stars.toLocaleString()} stars</span>
<span>{project.forks.toLocaleString()} forks</span>
<span>Checked {formatDate(project.lastVerifiedAt)}</span>
</div>
{project.topics.length > 0 && (
<div className="mt-4 flex flex-wrap gap-2">
{project.topics.slice(0, 8).map((topic) => (
<span key={topic} className="border border-black px-2 py-1 font-mono text-[10px] uppercase">
{topic}
</span>
))}
</div>
)}
</div>
</div>
);
<div className="px-4 py-5 lg:px-5 lg:py-7">
<p className="mb-4 font-mono text-[10px] font-semibold uppercase tracking-[0.16em] text-black/55">
Evidence trail
</p>
<ol className="space-y-4">
{project.evidence.slice(0, 4).map((evidence, evidenceIndex) => (
<li key={evidence.id} className="grid grid-cols-[22px_1fr] gap-2 text-xs leading-5">
<span className="font-mono text-[#0038ff]">{String(evidenceIndex + 1).padStart(2, '0')}</span>
<div>
<p className="font-semibold uppercase tracking-[0.04em]">{evidence.label}</p>
<p className="text-black/60">{evidence.detail}</p>
<p className="mt-1 font-mono text-[10px] uppercase text-black/45">
{formatDate(evidence.occurredAt)}
</p>
</div>
</li>
))}
</ol>
{project.url && (
<a
href={project.url}
target="_blank"
rel="noreferrer"
className="mt-6 inline-block border-b border-black pb-1 font-mono text-[11px] font-semibold uppercase tracking-[0.12em] hover:text-[#0038ff]"
>
Open source record
</a>
)}
</div>
</article>
)
}
function LoadingDossier() {
return (
<div className="min-h-screen bg-[#f1f0eb] px-4 py-10 text-black">
<div className="mx-auto max-w-7xl border border-black bg-[#faf9f5]">
<div className="h-48 animate-pulse bg-black/5" />
<div className="grid grid-cols-2 border-t border-black sm:grid-cols-4">
{[0, 1, 2, 3].map((item) => (
<div key={item} className="h-28 animate-pulse border-r border-black bg-black/[0.03] last:border-r-0" />
))}
</div>
<div className="h-80 animate-pulse border-t border-black bg-black/5" />
</div>
</div>
)
}
export default function CollaboratePage() {
const router = useRouter()
const searchParams = useSearchParams()
const publicUsername = searchParams.get('profile')?.trim() || null
const { isAuthenticated, isInitialized } = useAuthStore()
const { showToast } = useToast()
const [graph, setGraph] = useState<TalentGraph | null>(null)
const [loading, setLoading] = useState(true)
const [syncing, setSyncing] = useState(false)
const [copied, setCopied] = useState(false)
const [error, setError] = useState<string | null>(null)
useEffect(() => {
if (!publicUsername && isInitialized && !isAuthenticated) router.replace('/login')
}, [isAuthenticated, isInitialized, publicUsername, router])
const loadGraph = useCallback(async () => {
try {
setLoading(true)
setError(null)
setGraph(
publicUsername
? await talentGraphService.getPublic(publicUsername)
: await talentGraphService.getMine(),
)
} catch (loadError) {
setError(getErrorMessage(loadError))
} finally {
setLoading(false)
}
}, [publicUsername])
useEffect(() => {
if (publicUsername || isAuthenticated) void loadGraph()
}, [isAuthenticated, loadGraph, publicUsername])
const handleSync = async () => {
try {
setSyncing(true)
await githubService.syncProjects()
await loadGraph()
showToast('GitHub project evidence refreshed.', 'success')
} catch (syncError) {
showToast(getErrorMessage(syncError), 'error')
} finally {
setSyncing(false)
}
}
const handleCopyShareLink = async () => {
if (!graph.profile.username) return
try {
const url = new URL('/collaborate', window.location.origin)
url.searchParams.set('profile', graph.profile.username)
await navigator.clipboard.writeText(url.toString())
setCopied(true)
window.setTimeout(() => setCopied(false), 2000)
showToast('Public dossier link copied.', 'success')
} catch {
showToast('The public link could not be copied.', 'error')
}
}
const initials = useMemo(() => {
const name = graph?.profile.displayName || graph?.profile.username || graph?.profile.githubUsername || 'G'
return name.split(/\s+/).map((part) => part[0]).join('').slice(0, 2).toUpperCase()
}, [graph])
if ((!publicUsername && !isInitialized) || loading) return <LoadingDossier />
if (!publicUsername && !isAuthenticated) return null
if (error || !graph) {
return (
<main className="min-h-screen bg-[#f1f0eb] px-4 py-16 text-black">
<section className="mx-auto max-w-3xl border border-black bg-[#faf9f5] p-8 sm:p-12">
<p className="font-mono text-xs uppercase tracking-[0.2em] text-[#0038ff]">Talent Graph / unavailable</p>
<h1 className="mt-4 text-4xl font-semibold tracking-[-0.05em]">The dossier could not be assembled.</h1>
<p className="mt-5 max-w-xl text-black/65">{error || 'No Talent Graph data was returned.'}</p>
<button onClick={() => void loadGraph()} className="mt-8 bg-black px-5 py-3 font-mono text-xs uppercase tracking-[0.12em] text-white">
Try again
</button>
</section>
</main>
)
}
const displayName = graph.profile.displayName || graph.profile.username || graph.profile.githubUsername || 'Gitgram member'
const isOwnerView = !publicUsername
const summary = [
['Projects', graph.summary.projectCount],
['Write verified', graph.summary.verifiedProjectCount],
['GitHub events', graph.summary.recordedActivityCount],
['Collaborators', graph.summary.collaboratorCount],
] as const
return (
<main className="min-h-screen bg-[#f1f0eb] px-3 py-6 text-[#111] sm:px-6 sm:py-10">
<div className="mx-auto max-w-7xl border border-black bg-[#faf9f5]">
<header className="grid lg:grid-cols-[1fr_320px]">
<div className="border-b border-black p-5 sm:p-8 lg:border-b-0 lg:border-r lg:p-12">
<div className="mb-14 flex flex-wrap items-center justify-between gap-4 font-mono text-[10px] uppercase tracking-[0.18em]">
<span>Gitgram / Talent Graph / {isOwnerView ? 'Owner dossier' : 'Public dossier'}</span>
<span>Generated {formatDate(graph.generatedAt)}</span>
</div>
<p className="mb-3 font-mono text-xs font-semibold uppercase tracking-[0.18em] text-[#0038ff]">
Verifiable builder dossier
</p>
<h1 className="max-w-4xl text-5xl font-semibold leading-[0.94] tracking-[-0.065em] sm:text-7xl lg:text-8xl">
Work that speaks for itself.
</h1>
<p className="mt-8 max-w-2xl text-base leading-7 text-black/65 sm:text-lg">
Repository access, connected GitHub projects, recorded activity, and collaboration paths—assembled from evidence already held by Gitgram.
</p>
</div>
<aside className="flex flex-col justify-between border-b border-black bg-[#0038ff] p-6 text-white lg:border-b-0 lg:p-8">
<div>
<div className="flex h-16 w-16 items-center justify-center border border-white font-mono text-lg font-semibold">
{initials}
</div>
<h2 className="mt-6 text-3xl font-semibold tracking-[-0.04em]">{displayName}</h2>
<p className="mt-2 font-mono text-xs uppercase tracking-[0.12em] text-white/70">
{graph.profile.githubUsername ? `github.com/${graph.profile.githubUsername}` : 'GitHub not connected'}
</p>
{graph.profile.bio && <p className="mt-5 text-sm leading-6 text-white/80">{graph.profile.bio}</p>}
</div>
<div className="mt-10 border-t border-white/50 pt-5">
<p className="font-mono text-[10px] uppercase tracking-[0.16em] text-white/70">Evidence source</p>
<p className="mt-2 text-sm font-semibold">
{graph.profile.githubConnected ? 'CONNECTED GITHUB ACCOUNT' : 'GITGRAM RECORDS ONLY'}
</p>
</div>
</aside>
</header>
<section aria-label="Talent summary" className="grid grid-cols-2 border-b border-black sm:grid-cols-4">
{summary.map(([label, value], index) => (
<div key={label} className={`p-5 sm:p-7 ${index < summary.length - 1 ? 'border-r border-black' : ''} ${index === 1 ? 'max-sm:border-r-0' : ''} ${index < 2 ? 'max-sm:border-b' : ''}`}>
<p className="font-mono text-[10px] uppercase tracking-[0.14em] text-black/55">{label}</p>
<p className="mt-3 text-4xl font-semibold tracking-[-0.06em] sm:text-5xl">{value}</p>
</div>
))}
</section>
<section>
<div className="flex flex-wrap items-end justify-between gap-5 p-5 sm:p-8">
<div>
<p className="font-mono text-[10px] uppercase tracking-[0.16em] text-[#0038ff]">01 / Project evidence</p>
<h2 className="mt-2 text-3xl font-semibold tracking-[-0.05em] sm:text-5xl">Verified work</h2>
</div>
<div className="flex flex-wrap gap-2">
{isOwnerView && (
<>
{graph.profile.githubConnected ? (
<button
onClick={handleSync}
disabled={syncing}
className="border border-black bg-black px-4 py-3 font-mono text-[10px] font-semibold uppercase tracking-[0.12em] text-white disabled:opacity-50"
>
{syncing ? 'Syncing records' : 'Refresh GitHub records'}
</button>
) : (
<button
onClick={() => githubService.connectGitHub()}
className="border border-black bg-black px-4 py-3 font-mono text-[10px] font-semibold uppercase tracking-[0.12em] text-white"
>
Connect GitHub
</button>
)}
<Link href="/claim" className="border border-black px-4 py-3 font-mono text-[10px] font-semibold uppercase tracking-[0.12em] hover:bg-[#0038ff] hover:text-white">
Verify a repository
</Link>
{graph.profile.username && (
<button
onClick={handleCopyShareLink}
className="border border-black px-4 py-3 font-mono text-[10px] font-semibold uppercase tracking-[0.12em] hover:bg-[#0038ff] hover:text-white"
>
{copied ? 'Link copied' : 'Copy public dossier'}
</button>
)}
</>
)}
</div>
</div>
{graph.projects.length > 0 ? (
graph.projects.map((project, index) => <ProjectFolio key={`${project.source}:${project.id}`} project={project} index={index} />)
) : (
<div className="border-t border-black px-5 py-16 sm:px-8">
<p className="max-w-xl text-2xl font-semibold tracking-[-0.04em]">No project evidence is recorded yet.</p>
<p className="mt-3 max-w-xl text-sm leading-6 text-black/60">
Connect and refresh GitHub to import projects, or verify write access by claiming a repository.
</p>
</div>
)}
</section>
<section className="border-t border-black">
<div className="grid lg:grid-cols-[330px_1fr]">
<div className="border-b border-black p-5 sm:p-8 lg:border-b-0 lg:border-r">
<p className="font-mono text-[10px] uppercase tracking-[0.16em] text-[#0038ff]">02 / Collaboration graph</p>
<h2 className="mt-2 text-3xl font-semibold tracking-[-0.05em]">Shared maintenance</h2>
<p className="mt-5 text-sm leading-6 text-black/60">
Each connection below is backed by a shared repository manager record. No inferred relationships are shown.
</p>
</div>
<div>
{graph.collaborators.length > 0 ? graph.collaborators.map((collaborator, index) => {
const name = collaborator.displayName || collaborator.username || collaborator.githubUsername || 'Gitgram collaborator'
return (
<article key={collaborator.id} className={`${index > 0 ? 'border-t border-black' : ''} p-5 sm:p-7`}>
<div className="flex flex-wrap items-start justify-between gap-4">
<div>
<p className="font-mono text-[10px] uppercase tracking-[0.14em] text-black/50">
C-{String(index + 1).padStart(2, '0')} · {collaborator.sharedProjects.length} shared {collaborator.sharedProjects.length === 1 ? 'repository' : 'repositories'}
</p>
<h3 className="mt-2 text-2xl font-semibold tracking-[-0.04em]">{name}</h3>
{collaborator.githubUsername && <p className="mt-1 font-mono text-xs text-[#0038ff]">@{collaborator.githubUsername}</p>}
</div>
{collaborator.username && (
<Link href={`/${collaborator.username}`} className="border-b border-black pb-1 font-mono text-[10px] uppercase tracking-[0.12em] hover:text-[#0038ff]">
View Gitgram profile
</Link>
)}
</div>
<div className="mt-5 grid gap-px bg-black sm:grid-cols-2">
{collaborator.sharedProjects.map((project) => (
<a key={`${collaborator.id}:${project.id}`} href={project.url} target="_blank" rel="noreferrer" className="bg-[#faf9f5] p-4 hover:bg-[#0038ff] hover:text-white">
<p className="font-semibold">{project.fullName}</p>
<p className="mt-2 font-mono text-[10px] uppercase tracking-[0.1em] opacity-65">
You: {project.yourRole} / Them: {project.theirRole}
</p>
</a>
))}
</div>
</article>
)
}) : (
<div className="p-5 sm:p-8">
<p className="text-xl font-semibold tracking-[-0.03em]">No shared-maintainer links are recorded.</p>
<p className="mt-3 text-sm leading-6 text-black/60">Collaboration edges appear after more than one Gitgram member manages the same repository.</p>
</div>
)}
</div>
</div>
</section>
<footer className="flex flex-wrap justify-between gap-3 border-t border-black bg-black px-5 py-4 font-mono text-[9px] uppercase tracking-[0.14em] text-white sm:px-8">
<span>Evidence over self-report</span>
<span>Member since {formatDate(graph.profile.memberSince)}</span>
</footer>
</div>
</main>
)
}

View File

@ -0,0 +1,831 @@
'use client'
import { FormEvent, useEffect, useMemo, useRef, useState } from 'react'
import Link from 'next/link'
import {
CreateTalentOpportunityInput,
TalentMatch,
TalentOpportunity,
TalentPilot,
TalentReferral,
talentGraphService,
} from '@/services/talentGraphService'
import styles from './talent-network.module.css'
type Notice = {
tone: 'status' | 'error'
text: string
}
const GUIDE_STEPS = [
{
id: 'talent-opportunities',
number: '01',
title: 'Kurum ihtiyacı',
detail: 'Kurum problemi, becerileri ve başarı ölçüsünü API kaydı olarak yayımlar.',
},
{
id: 'evidence-matches',
number: '02',
title: 'Kanıt eşleşmesi',
detail: 'GitGram, açık depo ve uygun pilot kanıtını aranan becerilerle karşılaştırır.',
},
{
id: 'zen-referrals',
number: '03',
title: 'Zen kararı',
detail: 'Zen yolunda kurum yönlendirir; aday tanıştırmayı kabul eder veya reddeder.',
},
{
id: 'pilot-audit',
number: '04',
title: 'Pilot kaydı',
detail: 'Kurum pilotu yürütür. GitGram teslimi ve durum değişikliklerini audit zincirine kaydeder.',
},
{
id: 'public-proof',
number: '05',
title: 'Açık kanıt',
detail: 'COMPLETED durum, katılımcı izni ve açık HTTP(S) teslimi birlikte gerekir.',
},
] as const
const EMPTY_FORM: CreateTalentOpportunityInput = {
organizationName: '',
title: '',
problem: '',
requiredSkills: [],
successMetric: '',
durationWeeks: 4,
sourceChannel: 'direct',
communityReferralConsent: false,
}
function getErrorMessage(error: unknown, fallback: string) {
if (typeof error === 'object' && error && 'response' in error) {
const response = (error as { response?: { data?: { error?: { message?: string } } } }).response
if (response?.data?.error?.message) return response.data.error.message
}
return error instanceof Error ? error.message : fallback
}
function mutationErrorStatus(error: unknown) {
if (typeof error === 'object' && error && 'response' in error) {
const status = (error as { response?: { status?: unknown } }).response?.status
return typeof status === 'number' ? status : 503
}
return 503
}
function formatAuditTime(value: string) {
return new Intl.DateTimeFormat('tr-TR', {
dateStyle: 'medium',
timeStyle: 'short',
}).format(new Date(value))
}
function hasPublicHttpDeliverable(value: string) {
try {
const url = new URL(value)
const hostname = url.hostname.toLowerCase().replace(/\.$/, '').replace(/^\[|\]$/g, '')
const ipv4 = hostname.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/)?.slice(1).map(Number)
const privateIpv4 = ipv4 && (
ipv4[0] === 0
|| ipv4[0] === 10
|| ipv4[0] === 127
|| (ipv4[0] === 169 && ipv4[1] === 254)
|| (ipv4[0] === 172 && ipv4[1] >= 16 && ipv4[1] <= 31)
|| (ipv4[0] === 192 && (ipv4[1] === 0 || ipv4[1] === 168))
|| (ipv4[0] === 100 && ipv4[1] >= 64 && ipv4[1] <= 127)
|| ipv4[0] >= 224
)
const privateIpv6 = hostname.includes(':') && (
hostname === '::'
|| hostname === '::1'
|| hostname.startsWith('::ffff:')
|| /^(fc|fd|fe[89ab]|ff)/.test(hostname)
|| hostname.startsWith('2001:db8:')
)
return (url.protocol === 'http:' || url.protocol === 'https:')
&& Boolean(hostname)
&& !url.username
&& !url.password
&& hostname !== 'localhost'
&& !hostname.endsWith('.localhost')
&& !hostname.endsWith('.local')
&& !hostname.endsWith('.internal')
&& !privateIpv4
&& !privateIpv6
} catch {
return false
}
}
export default function TalentNetworkPage() {
const [opportunities, setOpportunities] = useState<TalentOpportunity[]>([])
const [selectedId, setSelectedId] = useState<string | null>(null)
const [matches, setMatches] = useState<TalentMatch[]>([])
const [form, setForm] = useState<CreateTalentOpportunityInput>(EMPTY_FORM)
const [skillsText, setSkillsText] = useState('')
const [opportunitiesLoading, setOpportunitiesLoading] = useState(true)
const [opportunitiesError, setOpportunitiesError] = useState<string | null>(null)
const [opportunitiesRequest, setOpportunitiesRequest] = useState(0)
const [matchesLoading, setMatchesLoading] = useState(false)
const [matchesError, setMatchesError] = useState<string | null>(null)
const [matchesRequest, setMatchesRequest] = useState(0)
const [submitting, setSubmitting] = useState(false)
const [myPilots, setMyPilots] = useState<TalentPilot[]>([])
const [pilotsLoading, setPilotsLoading] = useState(true)
const [pilotsError, setPilotsError] = useState<string | null>(null)
const [pilotsRequest, setPilotsRequest] = useState(0)
const [pilotDrafts, setPilotDrafts] = useState<Record<string, { deliverableUrl: string; publicEvidenceConsent: boolean }>>({})
const [savingPilotId, setSavingPilotId] = useState<string | null>(null)
const [startingPilotId, setStartingPilotId] = useState<string | null>(null)
const [myReferrals, setMyReferrals] = useState<TalentReferral[]>([])
const [referralsLoading, setReferralsLoading] = useState(true)
const [referralsError, setReferralsError] = useState<string | null>(null)
const [referralsRequest, setReferralsRequest] = useState(0)
const [referringId, setReferringId] = useState<string | null>(null)
const [notice, setNotice] = useState<Notice | null>(null)
const mutationKeys = useRef(new Map<string, { body: string; key: string }>())
function mutationKey(action: string, payload: unknown) {
const body = JSON.stringify(payload)
const current = mutationKeys.current.get(action)
if (current?.body === body) return current.key
const key = crypto.randomUUID()
mutationKeys.current.set(action, { body, key })
return key
}
function settleMutation(action: string, error?: unknown) {
if (!error || mutationErrorStatus(error) < 500) mutationKeys.current.delete(action)
}
const selected = useMemo(
() => opportunities.find((opportunity) => opportunity.id === selectedId) || null,
[opportunities, selectedId],
)
const publicProofPilots = useMemo(
() => myPilots.filter((pilot) => (
pilot.status === 'COMPLETED'
&& pilot.publicEvidenceConsent
&& hasPublicHttpDeliverable(pilot.deliverableUrl || '')
)),
[myPilots],
)
const currentGuideStep = useMemo(() => {
if (publicProofPilots.length > 0) return 'public-proof'
if (myPilots.length > 0) return 'pilot-audit'
if (myReferrals.length > 0) return 'zen-referrals'
if (matches.length > 0) return 'evidence-matches'
return 'talent-opportunities'
}, [matches.length, myPilots.length, myReferrals.length, publicProofPilots.length])
useEffect(() => {
let active = true
setOpportunitiesLoading(true)
setOpportunitiesError(null)
talentGraphService.listOpportunities()
.then((items) => {
if (!active) return
setOpportunities(items)
setSelectedId((current) => (
current && items.some((opportunity) => opportunity.id === current)
? current
: items[0]?.id || null
))
})
.catch(() => {
if (!active) return
setOpportunities([])
setSelectedId(null)
setOpportunitiesError('Fırsat servisi yanıt vermedi. Oturumu kontrol edin veya yeniden deneyin.')
})
.finally(() => active && setOpportunitiesLoading(false))
return () => { active = false }
}, [opportunitiesRequest])
useEffect(() => {
let active = true
setReferralsLoading(true)
setReferralsError(null)
setMyReferrals([])
talentGraphService.listMyReferrals()
.then((referrals) => active && setMyReferrals(referrals))
.catch(() => active && setReferralsError('Yönlendirmeler okunamadı. Oturumu kontrol edin veya servisi yeniden çağırın.'))
.finally(() => active && setReferralsLoading(false))
return () => { active = false }
}, [referralsRequest])
useEffect(() => {
let active = true
setPilotsLoading(true)
setPilotsError(null)
setMyPilots([])
setPilotDrafts({})
talentGraphService.listMyPilots()
.then((pilots) => {
if (!active) return
setMyPilots(pilots)
setPilotDrafts(Object.fromEntries(pilots.map((pilot) => [pilot.id, {
deliverableUrl: pilot.deliverableUrl || '',
publicEvidenceConsent: pilot.publicEvidenceConsent,
}])))
})
.catch(() => active && setPilotsError('Pilot kayıtları okunamadı. Oturumu kontrol edin veya servisi yeniden çağırın.'))
.finally(() => active && setPilotsLoading(false))
return () => { active = false }
}, [pilotsRequest])
useEffect(() => {
if (!selectedId) {
setMatches([])
setMatchesError(null)
setMatchesLoading(false)
return
}
let active = true
setMatches([])
setMatchesError(null)
setMatchesLoading(true)
talentGraphService.getOpportunityMatches(selectedId)
.then((result) => active && setMatches(result.matches))
.catch(() => active && setMatchesError('Eşleşme servisi yanıt vermedi. Fırsatı yeniden seçin veya tekrar deneyin.'))
.finally(() => active && setMatchesLoading(false))
return () => { active = false }
}, [matchesRequest, selectedId])
async function createOpportunity(event: FormEvent<HTMLFormElement>) {
event.preventDefault()
const requiredSkills = skillsText.split(',').map((skill) => skill.trim().toLowerCase()).filter(Boolean)
if (requiredSkills.length === 0) {
setNotice({ tone: 'error', text: 'En az bir beceri yazın.' })
return
}
setSubmitting(true)
setNotice(null)
const input = { ...form, requiredSkills }
const action = 'opportunity:create'
try {
const created = await talentGraphService.createOpportunity(input, mutationKey(action, input))
settleMutation(action)
setOpportunities((current) => [created, ...current])
setSelectedId(created.id)
setOpportunitiesError(null)
setForm(EMPTY_FORM)
setSkillsText('')
setNotice({ tone: 'status', text: 'Kurum ihtiyacı yayımlandı ve eşleşmeye açıldı.' })
} catch (error) {
settleMutation(action, error)
setNotice({
tone: 'error',
text: getErrorMessage(error, 'İhtiyaç yayımlanamadı. Oturumu ve zorunlu alanları kontrol edip tekrar deneyin.'),
})
} finally {
setSubmitting(false)
}
}
async function startPilot(match: TalentMatch) {
if (!selected) return
setStartingPilotId(match.profile.id)
setNotice(null)
const milestones = [
'Başlangıç görüşmesi ve kapsam onayı',
'İlk teslim ve kurum geri bildirimi',
'Başarı metriği incelemesi',
]
const action = `pilot:start:${selected.id}:${match.profile.id}`
const payload = { participantId: match.profile.id, milestones }
try {
const created = await talentGraphService.startPilot(selected.id, match.profile.id, milestones, mutationKey(action, payload))
settleMutation(action)
setMyPilots((current) => [created, ...current.filter((pilot) => pilot.id !== created.id)])
setPilotDrafts((current) => ({
...current,
[created.id]: { deliverableUrl: created.deliverableUrl || '', publicEvidenceConsent: created.publicEvidenceConsent },
}))
setPilotsError(null)
setPilotsLoading(false)
setNotice({ tone: 'status', text: `${match.profile.displayName || match.profile.username} ile pilot başlatıldı.` })
setOpportunitiesRequest((request) => request + 1)
setMatchesRequest((request) => request + 1)
} catch (error) {
settleMutation(action, error)
setNotice({
tone: 'error',
text: getErrorMessage(error, 'Pilot başlatılamadı. Bu kurum ihtiyacının sahibi olarak giriş yapıp tekrar deneyin.'),
})
} finally {
setStartingPilotId(null)
}
}
async function savePilot(pilot: TalentPilot, complete = false) {
const draft = pilotDrafts[pilot.id] || { deliverableUrl: '', publicEvidenceConsent: false }
setSavingPilotId(pilot.id)
setNotice(null)
const input = {
expectedRevision: pilot.revision,
deliverableUrl: draft.deliverableUrl,
...(pilot.viewerRole === 'participant' ? { publicEvidenceConsent: draft.publicEvidenceConsent } : {}),
...(complete ? { status: 'COMPLETED' as const } : {}),
}
const action = `pilot:${complete ? 'complete' : 'save'}:${pilot.id}`
try {
const updated = await talentGraphService.updatePilot(pilot.id, input, mutationKey(action, input))
settleMutation(action)
setMyPilots((current) => current.map((item) => item.id === pilot.id ? updated : item))
if (complete) {
setOpportunitiesRequest((request) => request + 1)
}
setNotice({
tone: 'status',
text: complete
? 'Kurum pilotu tamamladı. Açık kanıt için katılımcı izni ve public HTTP(S) teslim bağlantısı da gerekir.'
: 'Pilot teslimi ve görünürlük tercihi kaydedildi.',
})
} catch (error) {
settleMutation(action, error)
setNotice({
tone: 'error',
text: getErrorMessage(error, 'Pilot güncellenemedi. Yetkinizi ve teslim bağlantısının public HTTP(S) adresi olduğunu kontrol edin.'),
})
} finally {
setSavingPilotId(null)
}
}
async function referMatch(match: TalentMatch) {
if (!selected) return
setReferringId(match.profile.id)
setNotice(null)
const action = `referral:create:${selected.id}:${match.profile.id}`
const payload = { participantId: match.profile.id }
try {
const referral = await talentGraphService.createReferral(selected.id, match.profile.id, mutationKey(action, payload))
settleMutation(action)
setMyReferrals((current) => [referral, ...current.filter((item) => item.id !== referral.id)])
setReferralsError(null)
setReferralsLoading(false)
setOpportunitiesRequest((request) => request + 1)
setMatchesRequest((request) => request + 1)
setNotice({ tone: 'status', text: `${match.profile.displayName || match.profile.username} için Zen Talent yönlendirmesi oluşturuldu.` })
} catch (error) {
settleMutation(action, error)
setNotice({
tone: 'error',
text: getErrorMessage(error, 'Yönlendirme yapılamadı. Fırsat sahibi oturumunu, Zen Talent kanalını ve topluluk iznini kontrol edin.'),
})
} finally {
setReferringId(null)
}
}
async function respondToReferral(referral: TalentReferral, status: 'ACCEPTED' | 'DECLINED') {
setReferringId(referral.id)
setNotice(null)
const action = `referral:${status.toLowerCase()}:${referral.id}`
const payload = { status, expectedRevision: referral.revision }
try {
const updated = await talentGraphService.updateReferral(referral.id, status, referral.revision, mutationKey(action, payload))
settleMutation(action)
setMyReferrals((current) => current.map((item) => item.id === referral.id ? updated : item))
setNotice({
tone: 'status',
text: status === 'ACCEPTED' ? 'Topluluk tanıştırmasını kabul ettiniz.' : 'Topluluk tanıştırmasını reddettiniz.',
})
} catch (error) {
settleMutation(action, error)
setNotice({
tone: 'error',
text: getErrorMessage(error, 'Yönlendirme kararı kaydedilemedi. Katılımcı oturumunu kontrol edip tekrar deneyin.'),
})
} finally {
setReferringId(null)
}
}
return (
<main className={styles.page}>
<header className={styles.header}>
<Link href="/" className={styles.brand}>GitGram Talent Graph</Link>
<span>Kanıtlı beceri eşleştirmesi</span>
</header>
<section className={styles.hero}>
<p>Zemin360 / 2026</p>
<h1>İhtiyacı yaz.<br />Üretim kanıtıyla eşleş.</h1>
<div className={styles.heroNote}>
<span>API</span>
<p>Bu ekran servis kayıtlarını okur. Sayılar API toplamıdır; GitGram istemci tarafında fırsat, aday veya pilot üretmez.</p>
</div>
</section>
<nav className={styles.guide} aria-label="Talent Graph kayıt zinciri">
<div className={styles.guideIntro}>
<p>Kayıt zinciri</p>
<h2>İhtiyaçtan açık kanıta</h2>
</div>
<ol>
{GUIDE_STEPS.map((step) => (
<li key={step.id} className={currentGuideStep === step.id ? styles.currentGuideStep : ''}>
<a href={`#${step.id}`} aria-current={currentGuideStep === step.id ? 'step' : undefined}>
<span>{step.number}</span>
<strong>{step.title}</strong>
<small>{step.detail}</small>
</a>
</li>
))}
</ol>
</nav>
{notice && (
<div
className={`${styles.message} ${notice.tone === 'error' ? styles.messageError : ''}`}
role={notice.tone === 'error' ? 'alert' : 'status'}
>
{notice.text}
</div>
)}
<section className={styles.board} aria-label="Fırsatlar ve eşleşmeler">
<aside id="talent-opportunities" className={styles.opportunities} aria-busy={opportunitiesLoading}>
<div className={styles.columnTitle}>
<span>01</span>
<h2>Açık ihtiyaçlar</h2>
</div>
{opportunitiesLoading && <p className={styles.empty}>GitGram fırsat kayıtlarını okuyor.</p>}
{!opportunitiesLoading && opportunitiesError && (
<div className={styles.resourceError} role="alert">
<p>{opportunitiesError}</p>
<button type="button" onClick={() => setOpportunitiesRequest((request) => request + 1)}>Yeniden dene</button>
</div>
)}
{!opportunitiesLoading && !opportunitiesError && opportunities.length === 0 && (
<div className={styles.empty}>
<p>API açık kurum ihtiyacı döndürmedi.</p>
<a href="#create-opportunity">İlk ihtiyacı ekle</a>
</div>
)}
{!opportunitiesLoading && !opportunitiesError && opportunities.map((opportunity) => (
<button
className={`${styles.opportunity} ${selectedId === opportunity.id ? styles.selected : ''}`}
key={opportunity.id}
onClick={() => {
setMatches([])
setMatchesError(null)
setSelectedId(opportunity.id)
}}
type="button"
aria-pressed={selectedId === opportunity.id}
>
<span>{opportunity.organizationName}</span>
<strong>{opportunity.title}</strong>
<small>{opportunity.durationWeeks} hafta · {opportunity.requiredSkills.join(', ')}</small>
<small className={styles.opportunityCounts}>
{opportunity.viewerRole === 'institution'
? `${opportunity.referralSummary?.total || 0} yönlendirme · ${opportunity.pilotSummary?.active || 0} aktif pilot · ${opportunity.pilotSummary?.completed || 0} tamamlanan pilot`
: 'Operasyon sayıları yalnız fırsat sahibine görünür'}
</small>
{opportunity.sourceChannel !== 'direct' && <small className={styles.channel}>{opportunity.sourceChannel}</small>}
</button>
))}
</aside>
<section id="evidence-matches" className={styles.matches} aria-live="polite" aria-busy={matchesLoading}>
<div className={styles.columnTitle}>
<span>02</span>
<h2>Kanıtlı eşleşmeler</h2>
</div>
{!selected && !opportunitiesLoading && !opportunitiesError && <p className={styles.empty}>Eşleşme görmek için bir fırsat seçin.</p>}
{!opportunitiesLoading && !opportunitiesError && selected && (
<article className={styles.problem}>
<span>{selected.organizationName}</span>
<h3>{selected.title}</h3>
<p>{selected.problem}</p>
<dl>
<div><dt>Başarı ölçüsü</dt><dd>{selected.successMetric}</dd></div>
<div><dt>Durum</dt><dd>{selected.status}</dd></div>
<div><dt>Kaynak</dt><dd>{selected.sourceChannel}</dd></div>
</dl>
{selected.viewerRole === 'institution' && (
<div className={styles.outcomeCounts} aria-label="Fırsat kayıt sayıları">
<div><span>Yönlendirme</span><strong>{selected.referralSummary?.total || 0}</strong></div>
<div><span>Aktif pilot</span><strong>{selected.pilotSummary?.active || 0}</strong></div>
<div><span>Tamamlanan pilot</span><strong>{selected.pilotSummary?.completed || 0}</strong></div>
</div>
)}
{selected.referralSummary && (
<p className={styles.referralBreakdown}>
Bekleyen {selected.referralSummary.contacted} · Kabul {selected.referralSummary.accepted} · Ret {selected.referralSummary.declined}
</p>
)}
{selected.viewerRole === 'institution' && (
<p className={styles.apiCountNote}>Bu değerler seçili fırsat için API toplamıdır.</p>
)}
</article>
)}
{!opportunitiesLoading && matchesLoading && <p className={styles.empty}>GitGram depo ve pilot kanıtlarını karşılaştırıyor.</p>}
{!opportunitiesLoading && !matchesLoading && matchesError && selected && (
<div className={styles.resourceError} role="alert">
<p>{matchesError}</p>
<button type="button" onClick={() => setMatchesRequest((request) => request + 1)}>Eşleşmeyi yeniden hesapla</button>
</div>
)}
{!opportunitiesLoading && !matchesLoading && !matchesError && selected && matches.length === 0 && (
<p className={styles.empty}>API, bu beceriler için herkese açık proje veya uygun pilot kanıtı olan profil döndürmedi.</p>
)}
{!opportunitiesLoading && !matchesLoading && !matchesError && matches.map((match, index) => {
const referral = myReferrals.find((item) => item.opportunityId === selected?.id && item.participantId === match.profile.id)
const existingPilot = myPilots.find((item) => item.opportunityId === selected?.id && item.participantId === match.profile.id)
const isZenPath = selected?.sourceChannel === 'zen-talent'
const isOpportunityOwner = selected?.viewerRole === 'institution'
const actionRecordsLoading = isOpportunityOwner && (pilotsLoading || (isZenPath && referralsLoading))
const actionRecordsUnavailable = isOpportunityOwner && Boolean(pilotsError || (isZenPath && referralsError))
return (
<article className={styles.match} key={match.profile.id}>
<div className={styles.rank}>{String(index + 1).padStart(2, '0')}</div>
<div>
<p className={styles.matchName}>{match.profile.displayName || match.profile.username}</p>
<p className={styles.reason}>{match.reason}</p>
<div className={styles.skills}>{match.matchedSkills.map((skill) => <span key={skill}>{skill}</span>)}</div>
<div className={styles.evidence}>
{match.projects.map((project) => (
<a href={project.url} target="_blank" rel="noreferrer" key={project.id}>
{project.fullName} · {project.verificationLevel}
</a>
))}
</div>
</div>
<div className={styles.matchAction}>
<strong>{match.score}</strong>
<span>uyum puanı</span>
{actionRecordsLoading && <em className={styles.referralState}>GitGram pilot ve yönlendirme kayıtlarını kontrol ediyor</em>}
{!actionRecordsLoading && actionRecordsUnavailable && <em className={styles.referralState}>GitGram eylem için gereken hesap kayıtlarını okuyamadı</em>}
{existingPilot && <em className={styles.referralState}>Pilot durumu: {existingPilot.status}</em>}
{!actionRecordsLoading && !actionRecordsUnavailable && selected?.viewerRole === 'institution' && !existingPilot && !isZenPath && (
<button
type="button"
disabled={startingPilotId === match.profile.id}
onClick={() => startPilot(match)}
>
{startingPilotId === match.profile.id ? 'Pilot başlatılıyor' : 'Pilot başlat'}
</button>
)}
{!actionRecordsLoading && !actionRecordsUnavailable && selected?.viewerRole === 'institution' && !existingPilot && isZenPath && referral?.status === 'ACCEPTED' && (
<button
type="button"
disabled={startingPilotId === match.profile.id}
onClick={() => startPilot(match)}
>
{startingPilotId === match.profile.id ? 'Pilot başlatılıyor' : 'Kabul edilen adayla pilot başlat'}
</button>
)}
{!actionRecordsLoading && !actionRecordsUnavailable && selected?.viewerRole === 'institution' && !existingPilot && isZenPath && referral?.status === 'CONTACTED' && <em className={styles.referralState}>Aday kararı bekleniyor</em>}
{!actionRecordsLoading && !actionRecordsUnavailable && selected?.viewerRole === 'institution' && !existingPilot && isZenPath && referral?.status === 'DECLINED' && <em className={styles.referralState}>Aday yönlendirmeyi reddetti</em>}
{!actionRecordsLoading && !actionRecordsUnavailable && selected?.viewerRole === 'institution' && !existingPilot && isZenPath && !selected.communityReferralConsent && (
<em className={styles.referralState}>Kurum Zen yönlendirmesi için topluluk izni vermedi</em>
)}
{!actionRecordsLoading && !actionRecordsUnavailable && selected?.viewerRole === 'institution' && !existingPilot && isZenPath && selected.communityReferralConsent && !referral && (
<button type="button" disabled={referringId === match.profile.id} onClick={() => referMatch(match)}>
{referringId === match.profile.id ? 'Yönlendiriliyor' : 'Zen’e yönlendir'}
</button>
)}
</div>
</article>
)
})}
</section>
</section>
<section id="zen-referrals" className={styles.referrals} aria-labelledby="my-referrals-title" aria-busy={referralsLoading}>
<div>
<span>03</span>
<h2 id="my-referrals-title">Topluluk tanıştırmaları</h2>
<p>Aday yönlendirmelerini burada görürsünüz. GitGram pilot ve açık kanıt sayılarını ayrı tutar.</p>
</div>
<div className={styles.referralList} aria-live="polite">
{referralsLoading && <p className={styles.empty}>GitGram yönlendirme kayıtlarını okuyor.</p>}
{!referralsLoading && referralsError && (
<div className={styles.resourceError} role="alert">
<p>{referralsError}</p>
<div className={styles.resourceActions}>
<Link href="/login">Giriş yap</Link>
<button type="button" onClick={() => setReferralsRequest((request) => request + 1)}>Servisi yeniden dene</button>
</div>
</div>
)}
{!referralsLoading && !referralsError && myReferrals.length === 0 && (
<p className={styles.empty}>Hesabınıza ait yönlendirme kaydı yok.</p>
)}
{!referralsLoading && !referralsError && myReferrals.map((referral) => (
<article key={referral.id}>
<div>
<span>{referral.opportunity.organizationName}</span>
<h3>{referral.opportunity.title}</h3>
<p>{referral.opportunity.problem}</p>
</div>
<strong>{referral.status}</strong>
{referral.viewerRole === 'participant' && referral.status === 'CONTACTED' && (
<div className={styles.referralActions}>
<button type="button" disabled={referringId === referral.id} onClick={() => respondToReferral(referral, 'DECLINED')}>
{referringId === referral.id ? 'Kaydediliyor' : 'Reddet'}
</button>
<button type="button" disabled={referringId === referral.id} onClick={() => respondToReferral(referral, 'ACCEPTED')}>
{referringId === referral.id ? 'Kaydediliyor' : 'Tanıştırmayı kabul et'}
</button>
</div>
)}
</article>
))}
</div>
</section>
<section id="pilot-audit" className={styles.pilots} aria-labelledby="my-pilots-title" aria-busy={pilotsLoading}>
<div className={styles.pilotIntro}>
<span>04</span>
<h2 id="my-pilots-title">Pilot kanıtları</h2>
<p>Kurum pilotu tamamlar. Taraflar teslimi kaydeder; katılımcı açık Talent Graph görünürlüğünü seçer.</p>
</div>
<div className={styles.pilotList} aria-live="polite">
{pilotsLoading && <p className={styles.empty}>GitGram pilot kayıtlarını okuyor.</p>}
{!pilotsLoading && pilotsError && (
<div className={styles.resourceError} role="alert">
<p>{pilotsError}</p>
<div className={styles.resourceActions}>
<Link href="/login">Giriş yap</Link>
<button type="button" onClick={() => setPilotsRequest((request) => request + 1)}>Servisi yeniden dene</button>
</div>
</div>
)}
{!pilotsLoading && !pilotsError && myPilots.length === 0 && (
<p className={styles.empty}>Hesabınıza ait aktif veya tamamlanmış pilot kaydı yok.</p>
)}
{!pilotsLoading && !pilotsError && myPilots.map((pilot) => {
const draft = pilotDrafts[pilot.id] || { deliverableUrl: '', publicEvidenceConsent: false }
const draftEligible = pilot.status === 'COMPLETED' && draft.publicEvidenceConsent && hasPublicHttpDeliverable(draft.deliverableUrl)
const proofEligibilitySaved = publicProofPilots.some((eligiblePilot) => eligiblePilot.id === pilot.id)
const referral = pilot.referral || null
const transitions = pilot.statusTransitions || []
return (
<article className={styles.pilot} key={pilot.id}>
<div className={styles.pilotHeading}>
<div>
<span>{pilot.opportunity.organizationName}</span>
<h3>{pilot.opportunity.title}</h3>
</div>
<strong>{pilot.status}</strong>
</div>
<ol className={styles.provenance} aria-label="Pilot kayıt zinciri">
<li>
<span>01 / Fırsat</span>
<strong>{pilot.opportunity.title}</strong>
<small>{pilot.opportunityId}</small>
</li>
<li>
<span>02 / Yönlendirme</span>
<strong>{referral ? referral.status : 'Doğrudan pilot'}</strong>
<small>{referral ? referral.id : 'Yönlendirme kaydı yok'}</small>
</li>
<li>
<span>03 / Katılımcı</span>
<strong>Katılımcı kaydı</strong>
<small>{pilot.participantId}</small>
</li>
<li>
<span>04 / Pilot</span>
<strong>{pilot.status}</strong>
<small>{pilot.id}</small>
</li>
<li>
<span>05 / Teslim</span>
<strong>{pilot.deliverableUrl ? 'Bağlantı kaydedildi' : 'Bağlantı bekleniyor'}</strong>
{pilot.deliverableUrl
? <a href={pilot.deliverableUrl} target="_blank" rel="noreferrer">{pilot.deliverableUrl}</a>
: <small>Henüz herkese açık teslim yok</small>}
</li>
</ol>
<div className={styles.auditTrail}>
<h4>Durum geçmişi</h4>
{transitions.length > 0 ? (
<ol>
{transitions.map((transition) => (
<li key={transition.id}>
<strong>{transition.previousStatus} → {transition.nextStatus}</strong>
<span>{formatAuditTime(transition.createdAt)}</span>
<small>Revizyon {transition.revision} · Aktör {transition.actorId}</small>
</li>
))}
</ol>
) : <p>Bu pilot için henüz audit kaydı yok.</p>}
</div>
<label>
Açık teslim bağlantısı
<input
type="url"
placeholder="https://"
value={draft.deliverableUrl}
onChange={(event) => setPilotDrafts((current) => ({
...current,
[pilot.id]: { ...draft, deliverableUrl: event.target.value },
}))}
/>
</label>
{pilot.viewerRole === 'participant' && (
<label className={styles.pilotConsent}>
<input
type="checkbox"
checked={draft.publicEvidenceConsent}
onChange={(event) => setPilotDrafts((current) => ({
...current,
[pilot.id]: { ...draft, publicEvidenceConsent: event.target.checked },
}))}
/>
Tamamlanmış bu pilotu herkese açık profilimde doğrulanmış proje kanıtı olarak göster.
</label>
)}
<div className={styles.pilotActions}>
<span className={draftEligible ? styles.ready : ''}>
{proofEligibilitySaved
? 'AÇIK KANIT KOŞULLARI KAYITLI'
: draftEligible
? 'KOŞULLAR HAZIR · KAYDET'
: pilot.viewerRole === 'participant' ? 'KATILIMCI' : 'KURUM'}
</span>
<button type="button" disabled={savingPilotId === pilot.id} onClick={() => savePilot(pilot)}>
{savingPilotId === pilot.id ? 'Kaydediliyor' : 'Teslimatı kaydet'}
</button>
{pilot.viewerRole === 'institution' && pilot.status !== 'COMPLETED' && (
<button type="button" disabled={savingPilotId === pilot.id} onClick={() => savePilot(pilot, true)}>
{savingPilotId === pilot.id ? 'Kaydediliyor' : 'Pilotu tamamla'}
</button>
)}
</div>
</article>
)
})}
</div>
</section>
<section id="public-proof" className={styles.publicProof} aria-labelledby="public-proof-title">
<div>
<span>05</span>
<h2 id="public-proof-title">Public Talent Graph kanıtı</h2>
</div>
<div className={styles.publicProofBody} aria-live="polite">
<p>GitGram yalnız COMPLETED pilotu, katılımcı iznini ve public HTTP(S) teslim bağlantısını birlikte bulduğunda pilotu açık dosyaya ekler.</p>
{pilotsLoading && <p className={styles.proofState} role="status">GitGram açık kanıt uygunluğu için pilot kayıtlarını okuyor.</p>}
{!pilotsLoading && pilotsError && (
<div className={styles.proofUnavailable} role="alert">
<p>Pilot servisi yanıt vermediği için GitGram açık kanıt uygunluğunu ölçemiyor.</p>
<Link href="/login">Oturumu kontrol et</Link>
</div>
)}
{!pilotsLoading && !pilotsError && (
<p className={styles.proofState}>
{publicProofPilots.length > 0
? `${publicProofPilots.length} pilot API kaydında açık kanıt koşullarını karşılıyor.`
: 'API kayıtlarında üç koşulu birlikte karşılayan pilot yok.'}
</p>
)}
<Link href="/collaborate" className={styles.proofLink}>Talent Graph dosyanı aç</Link>
<small>Bu bağlantı oturum sahibinin dosyasını açar. Kullanıcı adı bulunan dosya sahibi, ekrandaki paylaşım eylemiyle `/collaborate?profile=...` bağlantısını kopyalar.</small>
</div>
</section>
<section id="create-opportunity" className={styles.create}>
<div className={styles.createIntro}>
<span>01 / Yeni kayıt</span>
<h2>Kurum ihtiyacı ekle</h2>
<p>Çözüm adı yerine problemi ve ölçülebilir sonucu yazın. Beceri alanı virgülle ayrılır.</p>
</div>
<form onSubmit={createOpportunity}>
<label>Kurum adı<input required value={form.organizationName} onChange={(event) => setForm({ ...form, organizationName: event.target.value })} /></label>
<label>İhtiyaç başlığı<input required value={form.title} onChange={(event) => setForm({ ...form, title: event.target.value })} /></label>
<label className={styles.full}>Problem<textarea required rows={5} value={form.problem} onChange={(event) => setForm({ ...form, problem: event.target.value })} /></label>
<label>Beceriler<input required placeholder="typescript, data, ux" value={skillsText} onChange={(event) => setSkillsText(event.target.value)} /></label>
<label>Süre (hafta)<input required type="number" min={1} max={16} value={form.durationWeeks} onChange={(event) => setForm({ ...form, durationWeeks: Number(event.target.value) })} /></label>
<label>Topluluk kanalı
<select value={form.sourceChannel} onChange={(event) => setForm({ ...form, sourceChannel: event.target.value as CreateTalentOpportunityInput['sourceChannel'] })}>
<option value="direct">Doğrudan</option>
<option value="gitgram">GitGram</option>
<option value="zemin360">Zemin360</option>
<option value="zen-talent">Zen Talent</option>
</select>
</label>
<label className={styles.full}>Başarı ölçüsü<input required value={form.successMetric} onChange={(event) => setForm({ ...form, successMetric: event.target.value })} /></label>
<label className={`${styles.full} ${styles.check}`}>
<input type="checkbox" checked={form.communityReferralConsent} onChange={(event) => setForm({ ...form, communityReferralConsent: event.target.checked })} />
Bu ihtiyacın seçilen topluluk kanalındaki uygun adaylara yönlendirilmesine izin veriyorum.
</label>
<button type="submit" disabled={submitting}>{submitting ? 'Yayımlanıyor' : 'İhtiyacı yayımla'}</button>
</form>
</section>
</main>
)
}

View File

@ -0,0 +1,235 @@
.page {
--paper: #ffffff;
--ground: #f7f7f8;
--ink: #161616;
--rule: #c8c8c8;
--red: #e4002b;
min-height: 100vh;
color: var(--ink);
background: var(--paper);
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}
.header {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 24px;
padding: 22px 4vw;
border-bottom: 1px solid var(--ink);
font-size: 13px;
}
.brand { color: var(--ink); font-weight: 700; text-decoration: none; }
.header > span { text-align: right; }
.page a:focus-visible, .page button:focus-visible, .page input:focus-visible, .page textarea:focus-visible, .page select:focus-visible { outline: 3px solid var(--red); outline-offset: 3px; }
.page [id] { scroll-margin-top: 18px; }
.hero {
display: grid;
grid-template-columns: 90px minmax(0, 1fr) minmax(240px, 0.36fr);
gap: 3vw;
padding: 72px 4vw 92px;
border-bottom: 1px solid var(--ink);
}
.hero > p, .columnTitle > span, .createIntro > span { color: var(--red); font-size: 12px; font-weight: 700; }
.hero h1 { margin: 0; font-size: clamp(58px, 9vw, 148px); font-weight: 600; letter-spacing: -0.075em; line-height: 0.84; }
.heroNote { align-self: end; padding-top: 16px; border-top: 5px solid var(--red); }
.heroNote span { color: var(--red); font-size: 34px; font-weight: 700; }
.heroNote p { margin: 32px 0 0; font-size: 14px; line-height: 1.6; }
.guide { display: grid; grid-template-columns: minmax(220px, 0.28fr) 1fr; border-bottom: 1px solid var(--ink); background: var(--ground); }
.guideIntro { padding: 30px 4vw; }
.guideIntro p { margin: 0; color: var(--red); font-size: 11px; font-weight: 700; text-transform: uppercase; }
.guideIntro h2 { margin: 12px 0 0; font-size: clamp(24px, 3vw, 42px); letter-spacing: -0.05em; line-height: 0.95; }
.guide ol { display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); margin: 0; padding: 0; border-left: 1px solid var(--ink); list-style: none; }
.guide li { position: relative; min-width: 0; border-right: 1px solid var(--rule); }
.guide li:last-child { border-right: 0; }
.guide li::before { position: absolute; top: 0; left: 0; width: 100%; height: 5px; background: transparent; content: ""; }
.guide li.currentGuideStep::before { background: var(--red); }
.guide a { display: grid; align-content: start; gap: 10px; min-height: 182px; padding: 24px 18px; color: var(--ink); text-decoration: none; }
.guide a:hover { background: var(--paper); }
.guide a > span { color: var(--red); font-size: 24px; font-weight: 700; font-variant-numeric: tabular-nums; }
.guide a > strong { font-size: 13px; }
.guide a > small { font-size: 10px; line-height: 1.5; }
.guide a[aria-current="step"] > strong { color: var(--red); }
.message { padding: 16px 4vw; color: var(--paper); background: var(--ink); font-size: 14px; }
.messageError { background: var(--red); }
.board { display: grid; grid-template-columns: minmax(280px, 0.34fr) 1fr; min-height: 760px; border-bottom: 1px solid var(--ink); }
.opportunities { border-right: 1px solid var(--ink); }
.columnTitle { display: flex; align-items: baseline; justify-content: space-between; gap: 20px; padding: 24px 28px; border-bottom: 1px solid var(--ink); }
.columnTitle h2 { margin: 0; font-size: 15px; font-weight: 700; }
.opportunity { display: block; width: 100%; padding: 28px; color: var(--ink); background: var(--paper); border: 0; border-bottom: 1px solid var(--rule); text-align: left; cursor: pointer; }
.opportunity:hover, .opportunity.selected { color: var(--paper); background: var(--red); }
.opportunity span, .opportunity small { display: block; font-size: 11px; }
.opportunity strong { display: block; margin: 12px 0 28px; font-size: 26px; line-height: 1.05; }
.opportunity small { line-height: 1.5; }
.opportunity .opportunityCounts { margin-top: 14px; padding-top: 10px; border-top: 1px solid currentColor; font-variant-numeric: tabular-nums; }
.opportunity .channel { margin-top: 10px; font-weight: 700; text-transform: uppercase; }
.matches { min-width: 0; }
.problem { display: grid; grid-template-columns: 150px 1fr; column-gap: 26px; padding: 36px 3vw; background: var(--ground); border-bottom: 1px solid var(--ink); }
.problem > span { color: var(--red); font-size: 12px; font-weight: 700; }
.problem h3 { margin: 0; font-size: clamp(30px, 4vw, 64px); letter-spacing: -0.05em; line-height: 0.95; }
.problem > p { grid-column: 2; max-width: 780px; margin: 28px 0; font-size: 15px; line-height: 1.65; }
.problem dl { grid-column: 2; display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 20px; margin: 0; padding-top: 20px; border-top: 1px solid var(--rule); }
.problem dl div { display: grid; gap: 7px; }
.problem dt { font-size: 10px; text-transform: uppercase; }
.problem dd { margin: 0; font-size: 13px; }
.outcomeCounts { grid-column: 2; display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); margin-top: 28px; border: 1px solid var(--ink); }
.outcomeCounts div { min-width: 0; padding: 16px; border-right: 1px solid var(--ink); }
.outcomeCounts div:last-child { border-right: 0; }
.outcomeCounts span { display: block; min-height: 28px; font-size: 10px; text-transform: uppercase; }
.outcomeCounts strong { display: block; margin-top: 12px; color: var(--red); font-size: clamp(34px, 4vw, 58px); font-variant-numeric: tabular-nums; line-height: 0.9; }
.referralBreakdown { grid-column: 2; margin: 10px 0 0; font-size: 10px; text-transform: uppercase; }
.apiCountNote { grid-column: 2; margin: 6px 0 0; font-size: 10px; }
.match { display: grid; grid-template-columns: 60px minmax(0, 1fr) 130px; gap: 24px; padding: 28px 3vw; border-bottom: 1px solid var(--rule); }
.rank { color: var(--red); font-size: 28px; font-weight: 700; }
.matchName { margin: 0; font-size: 24px; font-weight: 700; }
.reason { max-width: 650px; margin: 8px 0 16px; font-size: 13px; line-height: 1.5; }
.skills { display: flex; flex-wrap: wrap; gap: 6px; }
.skills span { padding: 5px 8px; border: 1px solid var(--ink); font-size: 10px; }
.evidence { display: flex; flex-direction: column; gap: 5px; margin-top: 16px; }
.evidence a { color: var(--ink); font-size: 11px; text-decoration-thickness: 1px; text-underline-offset: 3px; }
.matchAction { text-align: right; }
.matchAction strong { display: block; color: var(--red); font-size: 54px; line-height: 0.9; }
.matchAction span { display: block; margin-top: 4px; font-size: 10px; }
.matchAction button, .create button { margin-top: 24px; padding: 10px 14px; color: var(--paper); background: var(--ink); border: 0; cursor: pointer; }
.matchAction button:hover, .create button:hover { background: var(--red); }
.matchAction button:disabled { cursor: wait; opacity: 0.55; }
.referralState { display: block; margin-top: 20px; font-size: 11px; font-style: normal; line-height: 1.4; }
.empty { margin: 0; padding: 32px; font-size: 13px; }
.empty p { margin: 0 0 12px; }
.empty a { color: var(--ink); font-weight: 700; text-underline-offset: 3px; }
.resourceError { padding: 32px; border-top: 5px solid var(--red); background: var(--ground); }
.resourceError p { max-width: 560px; margin: 0; font-size: 13px; line-height: 1.55; }
.resourceActions { display: flex; flex-wrap: wrap; align-items: center; gap: 14px; margin-top: 18px; }
.resourceActions a { color: var(--ink); font-size: 12px; font-weight: 700; text-underline-offset: 3px; }
.resourceError button { padding: 10px 14px; color: var(--paper); background: var(--ink); border: 0; cursor: pointer; }
.resourceError button:hover { background: var(--red); }
.referrals { display: grid; grid-template-columns: minmax(260px, 0.34fr) 1fr; border-bottom: 1px solid var(--ink); background: var(--ground); }
.referrals > div:first-child { padding: 42px 4vw; }
.referrals > div:first-child span { color: var(--red); font-size: 12px; font-weight: 700; }
.referrals > div:first-child h2 { margin: 22px 0 0; font-size: clamp(34px, 4vw, 60px); letter-spacing: -0.055em; line-height: 0.95; }
.referrals > div:first-child p { max-width: 390px; margin: 24px 0 0; font-size: 13px; line-height: 1.55; }
.referralList { border-left: 1px solid var(--ink); }
.referralList article { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 24px; padding: 30px 3vw; border-bottom: 1px solid var(--rule); }
.referralList article:last-child { border-bottom: 0; }
.referralList span { color: var(--red); font-size: 11px; font-weight: 700; }
.referralList h3 { margin: 7px 0 12px; font-size: 28px; letter-spacing: -0.035em; }
.referralList p { max-width: 680px; margin: 0; font-size: 13px; line-height: 1.55; }
.referralList article > strong { align-self: start; padding: 6px 8px; color: var(--paper); background: var(--ink); font-size: 10px; }
.referralActions { grid-column: 1 / -1; display: flex; justify-content: flex-end; gap: 8px; }
.referralActions button { padding: 10px 14px; color: var(--paper); background: var(--ink); border: 0; cursor: pointer; }
.referralActions button:last-child { background: var(--red); }
.referralActions button:disabled { cursor: wait; opacity: 0.55; }
.pilots { display: grid; grid-template-columns: minmax(260px, 0.34fr) 1fr; border-bottom: 1px solid var(--ink); }
.pilotIntro { padding: 50px 4vw; color: var(--paper); background: var(--ink); }
.pilotIntro > span { color: var(--red); font-size: 12px; font-weight: 700; }
.pilotIntro h2 { margin: 24px 0; font-size: clamp(38px, 5vw, 72px); letter-spacing: -0.055em; line-height: 0.95; }
.pilotIntro p { max-width: 400px; font-size: 14px; line-height: 1.6; }
.pilotList { min-width: 0; }
.pilot { padding: 34px 3vw; border-bottom: 1px solid var(--rule); }
.pilot:last-child { border-bottom: 0; }
.pilotHeading { display: flex; align-items: flex-start; justify-content: space-between; gap: 24px; }
.pilotHeading span { color: var(--red); font-size: 11px; font-weight: 700; }
.pilotHeading h3 { margin: 8px 0 26px; font-size: clamp(24px, 3vw, 40px); letter-spacing: -0.04em; }
.pilotHeading > strong { padding: 6px 8px; color: var(--paper); background: var(--ink); font-size: 10px; }
.pilot > label { display: grid; gap: 8px; font-size: 11px; font-weight: 700; }
.pilot > label input[type="url"] { padding: 12px 0; border: 0; border-bottom: 1px solid var(--ink); border-radius: 0; outline: 0; }
.pilot .pilotConsent { grid-template-columns: 18px 1fr; align-items: start; margin-top: 20px; max-width: 700px; font-weight: 500; line-height: 1.5; }
.pilotConsent input { width: 16px; height: 16px; margin: 2px 0 0; accent-color: var(--red); }
.provenance { display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); margin: 0 0 30px; padding: 0; border: 1px solid var(--ink); list-style: none; }
.provenance li { position: relative; display: grid; align-content: start; gap: 8px; min-width: 0; min-height: 138px; padding: 14px; border-right: 1px solid var(--ink); }
.provenance li:last-child { border-right: 0; }
.provenance li:not(:last-child)::after { position: absolute; z-index: 1; top: 16px; right: -5px; width: 9px; height: 9px; background: var(--red); content: ""; }
.provenance span { color: var(--red); font-size: 9px; font-weight: 700; text-transform: uppercase; }
.provenance strong { font-size: 12px; line-height: 1.35; }
.provenance small, .provenance a { overflow-wrap: anywhere; color: var(--ink); font-size: 9px; line-height: 1.35; }
.auditTrail { display: grid; grid-template-columns: 130px minmax(0, 1fr); margin-bottom: 28px; padding: 18px 0; border-top: 1px solid var(--ink); border-bottom: 1px solid var(--ink); }
.auditTrail h4 { margin: 0; font-size: 11px; text-transform: uppercase; }
.auditTrail > p { margin: 0; font-size: 11px; }
.auditTrail ol { display: grid; gap: 12px; margin: 0; padding: 0; list-style: none; }
.auditTrail li { display: grid; grid-template-columns: minmax(150px, 1fr) minmax(140px, auto) minmax(0, 1fr); gap: 12px; font-size: 10px; }
.auditTrail li span { font-variant-numeric: tabular-nums; }
.auditTrail li small { overflow-wrap: anywhere; color: var(--ink); opacity: 0.6; }
.pilotActions { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin-top: 24px; }
.pilotActions > span { margin-right: auto; font-size: 10px; font-weight: 700; }
.pilotActions > .ready { color: var(--red); }
.pilotActions button { padding: 10px 14px; color: var(--paper); background: var(--ink); border: 0; cursor: pointer; }
.pilotActions button:hover { background: var(--red); }
.pilotActions button:disabled { cursor: wait; opacity: 0.55; }
.publicProof { display: grid; grid-template-columns: minmax(260px, 0.34fr) 1fr; border-bottom: 1px solid var(--ink); background: var(--ground); }
.publicProof > div:first-child { padding: 50px 4vw; color: var(--paper); background: var(--red); }
.publicProof > div:first-child span { font-size: 12px; font-weight: 700; }
.publicProof > div:first-child h2 { margin: 24px 0 0; font-size: clamp(38px, 5vw, 72px); letter-spacing: -0.055em; line-height: 0.92; }
.publicProofBody { display: grid; align-content: center; justify-items: start; gap: 22px; padding: 50px 4vw; }
.publicProofBody > p { max-width: 760px; margin: 0; font-size: 15px; line-height: 1.65; }
.publicProofBody .proofState { width: 100%; padding: 14px 0; border-top: 1px solid var(--ink); border-bottom: 1px solid var(--ink); font-size: 12px; font-weight: 700; }
.proofUnavailable { width: 100%; padding: 14px 0; border-top: 5px solid var(--red); border-bottom: 1px solid var(--ink); }
.proofUnavailable p { margin: 0; font-size: 12px; font-weight: 700; }
.proofUnavailable a { display: inline-block; margin-top: 12px; color: var(--ink); font-size: 11px; font-weight: 700; text-underline-offset: 3px; }
.proofLink { padding: 13px 18px; color: var(--paper); background: var(--ink); font-size: 12px; font-weight: 700; text-decoration: none; }
.proofLink:hover { background: var(--red); }
.publicProofBody small { max-width: 680px; font-size: 10px; line-height: 1.55; }
.create { display: grid; grid-template-columns: minmax(260px, 0.42fr) 1fr; gap: 7vw; padding: 90px 4vw 120px; background: var(--ground); }
.createIntro h2 { margin: 20px 0; font-size: clamp(38px, 5vw, 72px); letter-spacing: -0.055em; line-height: 0.95; }
.createIntro p { max-width: 420px; font-size: 14px; line-height: 1.6; }
.create form { display: grid; grid-template-columns: 1fr 1fr; gap: 24px; align-content: start; }
.create label { display: grid; gap: 8px; font-size: 11px; font-weight: 700; }
.create input, .create textarea, .create select { width: 100%; padding: 13px 0; color: var(--ink); background: transparent; border: 0; border-bottom: 1px solid var(--ink); border-radius: 0; outline: 0; }
.create textarea { padding: 13px; border: 1px solid var(--ink); resize: vertical; }
.create input:focus, .create textarea:focus { border-color: var(--red); box-shadow: inset 0 -2px 0 var(--red); }
.create .full { grid-column: 1 / -1; }
.create .check { grid-template-columns: 18px 1fr; align-items: start; font-weight: 500; line-height: 1.5; }
.create .check input { width: 16px; height: 16px; margin: 2px 0 0; accent-color: var(--red); }
.create button { justify-self: start; margin: 8px 0 0; padding: 14px 24px; font-weight: 700; }
.create button:disabled { cursor: wait; opacity: 0.6; }
@media (max-width: 900px) {
.hero { grid-template-columns: 50px 1fr; }
.heroNote { grid-column: 2; max-width: 520px; }
.guide { grid-template-columns: 1fr; }
.guide ol { border-top: 1px solid var(--ink); border-left: 0; overflow-x: auto; }
.guide a { min-width: 180px; }
.board, .referrals, .pilots, .publicProof, .create { grid-template-columns: 1fr; }
.provenance { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.provenance li { border-bottom: 1px solid var(--ink); }
.provenance li:nth-child(even) { border-right: 0; }
.provenance li:last-child { border-bottom: 0; }
.referralList { border-left: 0; border-top: 1px solid var(--ink); }
.opportunities { border-right: 0; border-bottom: 1px solid var(--ink); }
.create { gap: 50px; }
}
@media (max-width: 640px) {
.header { grid-template-columns: 1fr; }
.header > span { text-align: left; }
.hero { grid-template-columns: 1fr; padding-top: 50px; }
.hero h1, .heroNote { grid-column: 1; }
.problem { grid-template-columns: 1fr; }
.problem > p, .problem dl, .outcomeCounts, .referralBreakdown, .apiCountNote { grid-column: 1; }
.problem h3 { margin-top: 16px; }
.outcomeCounts { grid-template-columns: 1fr; }
.outcomeCounts div { border-right: 0; border-bottom: 1px solid var(--ink); }
.outcomeCounts div:last-child { border-bottom: 0; }
.match { grid-template-columns: 44px 1fr; }
.matchAction { grid-column: 2; text-align: left; }
.provenance { grid-template-columns: 1fr; }
.provenance li, .provenance li:nth-child(even) { border-right: 0; }
.provenance li:not(:last-child)::after { top: auto; right: 14px; bottom: -5px; }
.auditTrail { grid-template-columns: 1fr; gap: 14px; }
.auditTrail li { grid-template-columns: 1fr; gap: 4px; }
.guide ol { grid-template-columns: 1fr; overflow-x: visible; }
.guide li { border-right: 0; border-bottom: 1px solid var(--rule); }
.guide li:last-child { border-bottom: 0; }
.guide a { min-height: 0; min-width: 0; }
.create form { grid-template-columns: 1fr; }
.create .full { grid-column: 1; }
}

View File

@ -52,6 +52,12 @@ export default function Navbar() {
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
</svg>
</Link>
<Link
href="/collaborate"
className="border border-primary/50 px-3 py-1.5 font-mono text-[10px] font-semibold uppercase tracking-[0.12em] text-primary hover:bg-primary hover:text-background"
>
Talent graph
</Link>
<NotificationBell />
<Link href="/camera" className="hover:text-primary">
<svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">

View File

@ -0,0 +1,243 @@
import api from './api'
export type TalentVerificationLevel = 'verified' | 'linked' | 'recorded'
export interface TalentEvidence {
id: string
kind: 'repository_claim' | 'github_sync' | 'github_activity' | 'project_record' | 'institutional_pilot'
label: string
detail: string
occurredAt: string
sourceUrl: string | null
}
export interface TalentProject {
id: string
source: 'repository' | 'project'
name: string
fullName: string
description: string | null
url: string | null
language: string | null
topics: string[]
stars: number
forks: number
role: string
verificationLevel: TalentVerificationLevel
lastVerifiedAt: string
evidence: TalentEvidence[]
}
export interface TalentCollaborator {
id: string
username: string | null
displayName: string | null
avatarUrl: string | null
githubUsername: string | null
sharedProjects: Array<{
id: string
fullName: string
url: string
theirRole: string
yourRole: string
}>
}
export interface TalentGraph {
profile: {
id: string
username: string | null
displayName: string | null
avatarUrl: string | null
bio: string | null
githubUsername: string | null
githubConnected: boolean
memberSince: string
}
summary: {
projectCount: number
verifiedProjectCount: number
recordedActivityCount: number
collaboratorCount: number
}
projects: TalentProject[]
collaborators: TalentCollaborator[]
generatedAt: string
}
export type TalentOpportunityStatus = 'OPEN' | 'MATCHING' | 'PILOT' | 'CLOSED'
export interface TalentPilotSummary {
id: string
participantId: string
status: 'PLANNED' | 'ACTIVE' | 'REVIEW' | 'COMPLETED' | 'CANCELLED'
updatedAt: string
revision: number
}
export interface TalentPilotStatusTransition {
id: string
pilotId: string
actorId: string
previousStatus: TalentPilotSummary['status']
nextStatus: TalentPilotSummary['status']
revision: number
createdAt: string
}
export interface TalentPilot extends TalentPilotSummary {
opportunityId: string
referralId: string | null
deliverableUrl: string | null
feedback: string | null
publicEvidenceConsent: boolean
startedAt: string | null
completedAt: string | null
viewerRole: 'participant' | 'institution'
opportunity: TalentOpportunity
referral: Omit<TalentReferral, 'opportunity' | 'viewerRole'> | null
statusTransitions: TalentPilotStatusTransition[]
}
export interface UpdateTalentPilotInput {
expectedRevision: number
status?: TalentPilotSummary['status']
deliverableUrl?: string
publicEvidenceConsent?: boolean
}
export interface TalentOpportunity {
id: string
organizationName: string
title: string
problem: string
requiredSkills: string[]
successMetric: string
durationWeeks: number
sourceChannel: 'direct' | 'gitgram' | 'zemin360' | 'zen-talent'
communityReferralConsent: boolean
viewerRole?: 'institution' | 'public'
status: TalentOpportunityStatus
revision: number
pilotSummary?: {
total: number
active: number
completed: number
}
referralSummary?: {
total: number
contacted: number
accepted: number
declined: number
}
createdAt: string
updatedAt: string
}
export interface TalentReferral {
id: string
opportunityId: string
participantId: string
referredById: string
status: 'CONTACTED' | 'ACCEPTED' | 'DECLINED'
revision: number
respondedAt: string | null
createdAt: string
updatedAt: string
viewerRole: 'participant' | 'institution'
opportunity: TalentOpportunity
}
export interface TalentMatch {
profile: {
id: string
username: string
displayName: string | null
avatarUrl: string | null
bio: string | null
githubUsername: string | null
}
score: number
matchedSkills: string[]
missingSkills: string[]
reason: string
projects: Array<{
id: string
fullName: string
url: string
matchedSkills: string[]
verificationLevel: TalentVerificationLevel
}>
}
export interface CreateTalentOpportunityInput {
organizationName: string
title: string
problem: string
requiredSkills: string[]
successMetric: string
durationWeeks: number
sourceChannel: 'direct' | 'gitgram' | 'zemin360' | 'zen-talent'
communityReferralConsent: boolean
}
export const talentGraphService = {
getMine: async (): Promise<TalentGraph> => {
const { data } = await api.get<{ data: TalentGraph }>('/talent-graph/me')
return data.data
},
getPublic: async (username: string): Promise<TalentGraph> => {
const { data } = await api.get<{ data: TalentGraph }>(`/talent-graph/public/${encodeURIComponent(username)}`)
return data.data
},
listOpportunities: async (): Promise<TalentOpportunity[]> => {
const { data } = await api.get<{ data: TalentOpportunity[] }>('/talent-graph/opportunities')
return data.data
},
createOpportunity: async (input: CreateTalentOpportunityInput, idempotencyKey: string): Promise<TalentOpportunity> => {
const { data } = await api.post<{ data: TalentOpportunity }>('/talent-graph/opportunities', input, mutationConfig(idempotencyKey))
return data.data
},
getOpportunityMatches: async (id: string): Promise<{ opportunity: TalentOpportunity; matches: TalentMatch[] }> => {
const { data } = await api.get<{ data: { opportunity: TalentOpportunity; matches: TalentMatch[] } }>(`/talent-graph/opportunities/${encodeURIComponent(id)}/matches`)
return data.data
},
startPilot: async (opportunityId: string, participantId: string, milestones: string[], idempotencyKey: string): Promise<TalentPilot> => {
const { data } = await api.post<{ data: TalentPilot }>(`/talent-graph/opportunities/${encodeURIComponent(opportunityId)}/pilots`, { participantId, milestones }, mutationConfig(idempotencyKey))
return data.data
},
createReferral: async (opportunityId: string, participantId: string, idempotencyKey: string): Promise<TalentReferral> => {
const { data } = await api.post<{ data: TalentReferral }>(`/talent-graph/opportunities/${encodeURIComponent(opportunityId)}/referrals`, { participantId }, mutationConfig(idempotencyKey))
return data.data
},
listMyReferrals: async (): Promise<TalentReferral[]> => {
const { data } = await api.get<{ data: TalentReferral[] }>('/talent-graph/referrals/mine')
return data.data
},
updateReferral: async (referralId: string, status: 'ACCEPTED' | 'DECLINED', expectedRevision: number, idempotencyKey: string): Promise<TalentReferral> => {
const { data } = await api.patch<{ data: TalentReferral }>(`/talent-graph/referrals/${encodeURIComponent(referralId)}`, { status, expectedRevision }, mutationConfig(idempotencyKey))
return data.data
},
listMyPilots: async (): Promise<TalentPilot[]> => {
const { data } = await api.get<{ data: TalentPilot[] }>('/talent-graph/pilots/mine')
return data.data
},
updatePilot: async (pilotId: string, input: UpdateTalentPilotInput, idempotencyKey: string): Promise<TalentPilot> => {
const { data } = await api.patch<{ data: TalentPilot }>(`/talent-graph/pilots/${encodeURIComponent(pilotId)}`, input, mutationConfig(idempotencyKey))
return data.data
},
}
function mutationConfig(idempotencyKey: string) {
return { headers: { 'Idempotency-Key': idempotencyKey } }
}

187
package-lock.json generated

File diff suppressed because it is too large Load Diff