"use client"; import React from "react"; import { Link, useNavigate, useParams, useSearchParams } from "react-router-dom"; import { Card, CardContent, CardHeader, CardTitle, CardDescription, Badge, Button, Input, Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui"; import { PageHeader } from "@/components/ui/PageHeader"; import { ProjectRouteFallback } from "@/shared/components/ProjectRouteFallback"; import { ArrowRight, Brain, CheckCircle2, ClipboardList, Layers, Lightbulb, Sparkles, TriangleAlert, } from "lucide-react"; import { useProject } from "@/shared/contexts/ProjectContext"; import type { ContextPack, EvidenceItem, Feature, KnowledgeItem } from "@/shared/lib/model"; import { projectBrainClientMode } from "@/shared/api/projectBrainClient"; import { useProjectContextPackSelectionData, useProjectContextPacksData } from "@/shared/hooks/useProjectData"; import type { ContextPackSelectionMode } from "@/shared/lib/contextPackSelector"; import { showSuccess } from "@/utils/toast"; type PackActionMode = "all" | "workspace" | "feature"; type TrustPayload = { source: string; confidence: number; lastChecked: string; approvalState: string; evidenceCount: number; }; const TrustPanel = ({ trust, title }: { trust: TrustPayload; title: string }) => ( {title} Evidence-linked trust metadata

Source: {trust.source}

Confidence: {trust.confidence}%

Evidence refs: {trust.evidenceCount}

Last checked: {new Date(trust.lastChecked).toLocaleString()}

Approval: {trust.approvalState}

); const BulletList = ({ title, items, emptyLabel = "No entries." }: { title: string; items: string[]; emptyLabel?: string }) => (

{title}

{items.length === 0 ? (

{emptyLabel}

) : ( )}
); const ContextPacks = () => { const { projectId, packId } = useParams(); const [searchParams] = useSearchParams(); const navigate = useNavigate(); const { projects, activeProjectId, contextPacks, checks, knowledge, relationships, evidence, setActiveContextPack, } = useProject(); const isRealMode = projectBrainClientMode === "real"; const project = projects.find((item) => item.id === projectId) || projects.find((item) => item.id === activeProjectId); const activeMode = (searchParams.get("source") as PackActionMode) || "all"; const featureId = searchParams.get("featureId"); const [selectionMode, setSelectionMode] = React.useState("codex"); const [selectionIntent, setSelectionIntent] = React.useState( "Continue the next build pass without breaking accepted truth, runtime persistence or validation gates.", ); const realContextPackState = useProjectContextPacksData(project?.id); const selectionRequest = React.useMemo( () => ({ mode: selectionMode, intent: selectionIntent, ...(featureId ? { targetType: "feature" as const, targetId: featureId } : { targetType: "project" as const }), maxPacks: 3, }), [featureId, selectionIntent, selectionMode], ); const autoSelectionState = useProjectContextPackSelectionData( project?.id, selectionRequest, project?.activeContextPackId, ); const autoSelection = autoSelectionState.data; if (!project) return ; const dataSourceCard = ( Context pack data source {isRealMode ? "Real backend mode is enabled. Context packs are loaded through the Fastify R4 read endpoint." : "Local data mode is enabled. Context packs are loaded from the local ProjectBrain fixture store."} {isRealMode ? "Live data" : "Local data"} {isRealMode && realContextPackState.isLoading ? Loading packs : null} {isRealMode && realContextPackState.error ? ( {realContextPackState.error.message} ) : null} {isRealMode ? ( ) : null} ); const allFeatures: Feature[] = project.featureGroups.flatMap((group) => group.features); const featureById = new Map(allFeatures.map((feature) => [feature.id, feature])); const projectPacks = isRealMode ? realContextPackState.data ?? [] : contextPacks.filter((pack) => pack.projectId === project.id); const activePack = projectPacks.find((pack) => pack.id === project.activeContextPackId) ?? projectPacks[0]; const selectedPack = packId ? projectPacks.find((pack) => pack.id === packId) : undefined; const targetPack = featureId ? projectPacks.find((pack) => pack.featureIds?.includes(featureId)) ?? selectedPack ?? activePack : selectedPack ?? activePack; const getFeatureNames = (ids: string[] = []) => ids.map((id) => featureById.get(id)?.name).filter(Boolean) as string[]; const getEvidenceForPack = (pack: ContextPack): EvidenceItem[] => pack.evidence .map((ref) => { return evidence.find( (entry) => entry.id === ref.id || entry.linkedEntity.id === ref.refId || entry.linkedEntity.label === ref.label, ); }) .filter(Boolean) as EvidenceItem[]; const getKnowledgeForPack = (pack: ContextPack): KnowledgeItem[] => knowledge.filter( (item) => item.projectId === project.id && ((item.relatedContextPackIds?.includes(pack.id)) || (item.includeInContextPacks?.includes(pack.id))), ); const getChecksForPack = (pack: ContextPack) => checks.filter((check) => check.linkedContextPackIds?.includes(pack.id)); const getRelationshipsForPack = (pack: ContextPack) => relationships.filter( (relationship) => pack.featureIds?.includes(relationship.from) || pack.featureIds?.includes(relationship.to) || pack.bugIds?.includes(relationship.from) || pack.bugIds?.includes(relationship.to) || pack.taskIds?.includes(relationship.from) || pack.taskIds?.includes(relationship.to), ); const isInActivePack = (candidateId: string) => activePack?.id === candidateId; const activeDecisions = activePack?.decisionIds ?? []; const applyActivePack = (targetPackId: string) => { if (!project) return; setActiveContextPack(project.id, targetPackId); showSuccess("Active context pack updated."); }; const renderListCard = ( items: string[], title: string, emptyLabel: string, ) => (

{title}

{items.length === 0 ? (

{emptyLabel}

) : (
    {items.map((item) =>
  • {item}
  • )}
)}
); const renderPackCard = (pack: ContextPack) => { const inActivePack = isInActivePack(pack.id); const inclusionLabel = inActivePack ? "Included in active context pack" : "Not included in active context pack"; return ( {pack.title} {inActivePack ? "active" : pack.category} {inclusionLabel}

{pack.summary}

Vision: {pack.dna.vision}
Current focus:{" "} {pack.currentFocus ? `${pack.currentFocus.title} (${pack.currentFocus.purpose})` : "project-wide"}
Features:{" "} {(pack.featureIds ?? []).length}
); }; const renderPackDetail = (pack: ContextPack) => { const packFeatures = getFeatureNames(pack.featureIds ?? []); const packBugs = (pack.bugIds ?? []).map((id) => id); const packTasks = (pack.taskIds ?? []).map((id) => id); const packDecisions = pack.decisionIds ?? []; const linkedEvidence = getEvidenceForPack(pack); const linkedKnowledge = getKnowledgeForPack(pack); const linkedChecks = getChecksForPack(pack); const linkedRelations = getRelationshipsForPack(pack); const inActivePack = activePack?.id === pack.id; const actionLabel = inActivePack ? "Already included in active context pack" : "Add to active context pack"; return ( {pack.title} {pack.category} From source: {activeMode}

Project DNA

Vision: {pack.dna.vision}

Goals: {pack.dna.goals.join(", ") || "none"}

Non-goals: {pack.dna.nonGoals.join(", ") || "none"}

Target audience: {pack.dna.targetAudience}

Principles: {pack.dna.principles.join(", ") || "none"}

Maturity: {pack.dna.maturityStage}

Context state

Focus: {pack.currentFocus?.title ?? "project-wide"} ({pack.currentFocus?.purpose ?? "context"})

Active inclusion: {inActivePack ? "Yes" : "No"}

{renderListCard(packFeatures, "Features", "No features linked")} {renderListCard([...packBugs, ...packTasks], "Bugs / Tasks", "No bugs/tasks linked")} {renderListCard([...packDecisions, ...activeDecisions], "Decisions / Rules", "No decision links")}
Evidence
{linkedEvidence.length === 0 ? (

No evidence linked.

) : (
{linkedEvidence.map((item) => (

{item.linkedEntity.label}

Type: {item.type} - Confidence: {item.confidence}%

Source: {item.source}

))}
)}

Knowledge

{linkedKnowledge.length === 0 ? (

No knowledge entries linked.

) : (
{linkedKnowledge.map((item) => (

{item.title}

Category: {item.category}

Source: {item.source}

))}
)}
check.title)} emptyLabel="No linked checks." />
Relationship links
{linkedRelations.length === 0 ? (

No direct relationship links found.

) : (
{linkedRelations.map((item) => (

{`${item.from} -> ${item.to}`}

Type: {item.type} - Confidence: {item.strength}

Rationale: {item.rationale}

))}
)}
); }; const selectionControlCard = ( Automatic context-pack selection Deterministic selector used by normal workspace flow and AI/Codex handoff flow. It explains why packs were selected before any prompt is generated.
setSelectionIntent(event.target.value)} placeholder="Describe the current work intent so ProjectBrain can choose the right packs." />
{autoSelectionState.error ? (

Selector failed: {autoSelectionState.error.message}

) : null} {autoSelection ? (

{autoSelection.decisionSummary}

Selected packs: {autoSelection.selectedContextPackIds.join(", ") || "none"}

Intent: {autoSelection.intent}

{autoSelection.candidates.slice(0, 3).map((candidate) => (

{candidate.title}

{candidate.category} | {candidate.generatedBy}

{candidate.score}
    {candidate.reasons.slice(0, 2).map((reason) =>
  • {reason}
  • )}
{candidate.warnings[0] ?

{candidate.warnings[0]}

: null}
))}
) : (

No selector result yet.

)}
); const modeLabel = activeMode === "feature" && featureId ? `for feature ${featureById.get(featureId)?.name ?? featureId}` : "workspace"; const focusedPack = activePack ? activePack.id : project.activeContextPackId; return (
} /> {dataSourceCard} {selectionControlCard} {targetPack && !selectedPack && (

Showing context pack generated from {modeLabel}.{" "} Back to all packs

)} {selectedPack ? ( <>

Back to all packs

{renderPackDetail(selectedPack)} ) : (
{projectPacks.map((pack) => renderPackCard(pack))} {projectPacks.length === 0 &&

No context packs available.

}
)} ); }; export default ContextPacks;