@loomcycle/explorer 0.19.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["createContext","useContext","LoomcycleClient","useMemo","useState","useState","useMemo","useState","useRef","useCallback","useState","useState","useCallback","useState","_Fragment","useRef","useState","useState","useState","useState","useMemo","_Fragment","useState","useMemo","_Fragment","_Fragment","useState","useState","useRef","useState","_Fragment","useState","_Fragment","useState","useRef","useCallback","_Fragment","useState","useRef","useId","useCallback","useState","_Fragment","ReactMarkdown","remarkGfm","_Fragment","useMemo","useState","useRef","useCallback","_Fragment","_Fragment","useState","useRef","useCallback","useMemo","useSyncExternalStore","_Fragment","useState","useRef","useCallback","_Fragment","__create","__defProp","__getOwnPropDesc","__getOwnPropNames","__getProtoOf","__hasOwnProp","__copyProps","from","keys","i","n","key","to","except","k","desc","__toESM","mod","isNodeMode","target","react","react_jsx_runtime","_loomcycle_client","react_markdown","remark_gfm","NAVIGATOR_KEY","readNavigatorMode","storage","writeNavigatorMode","mode","isSubjectRoot","chunk","entityTypeNames","classes","described","names","c","name","kind","a","b","subjectTypeChoices","cur","current","inForce","t","transferInput","input","r","trimSlash","transferProblem","transferSummary","res","verb","op","lines","parts","plural","m","refused","d","u","f","transferBlocked","dropDangling","p","end","one","many","annotationsApply","scope","BRIEF_MAX_CHARS","ABSTRACT_MAX_CHARS","LEVELS","isLevel","v","usableAnnotations","records","chunkId","loadAnnotations","data","browse","annotationLevelFor","isRoot","codePoints","s","annotationDraftProblem","brief","abstract","setAnnotationInput","edit","writtenByLabel","writtenBy","writtenAtLabel","writtenAt","filenameFromContentDisposition","header","star","baseName","quoted","token","errorMessageFromBody","o","text","status","statusText","fileStem","title","saveBlob","url","blob","filename","DOCUMENT_PATH_PAGES","DOCUMENT_PATH_PAGE_LIMIT","dataLayerFromClient","reviewOps","client","jsonPost","page","cursor","resp","hit","documentId","req","opts","parentId","afterId","patch","mediaType","dataBase64","reason","includeMetadata","limit","fromRevision","toRevision","assetFetch","q","documentExportPath","format","tenantQuery","out","scopeIdOf","rulingId","scopeId","ExplorerDataContext","ExplorerDataProvider","useExplorerData","LS_MAX_LIMIT","lsTarget","dir","parentPathOf","idx","fullPath","ancestorsOf","segs","path","errMessage","listingOf","before","LazyPathTree","pageLimit","fn","listing","tracked","prev","shown","want","ep","e","running","l","last","dirs","keepSet","keep","listSubtree","next","documentIdsOf","ids","entries","id","createLoomcycleClient","impl","init","assetFetchFromConnection","doFetch","headers","RequestError","message","code","jsonPostFromConnection","body","parsed","useResolvedDataLayer","src","dataLayer","connection","ExplorerRoot","themeAttr","theme","followReference","trail","origin","defined","jumpTo","index","amendCurrent","labelOf","loc","collapseTrail","all","length","max","tail","hidden","findDocumentPath","documentIdOf","entry","landingChunk","wanted","rows","DocTrail","showAll","setShowAll","previous","items","onJump","item","TransferModal","setOp","toScope","setToScope","setTo","fromPath","setDropDangling","checked","setChecked","done","setDone","busy","setBusy","err","setErr","underPath","problem","blocked","submit","onClose","real","onDone","ex","label","line","HANDLE_WIDTH","Splitter","restore","storageKey","stored","minLeftWidth","defaultLeftWidth","leftWidth","setLeftWidth","widthKey","setWidthKey","containerRef","dragging","setDragging","onPointerDown","onPointerMove","rect","raw","maxAllowed","minRightWidth","onPointerUp","className","hideRight","children","IMAGE_MEDIA_TYPES","isSupportedImage","type","readImageAsBase64","file","reject","reader","result","comma","resolve","imageFileFromPaste","it","EDGE_PAGE_CAP","loadDocumentEdges","edges","after","maxPages","chunkAncestors","byId","chunks","seen","up","parent","ORDINARY_METHODS","QUOTE_MAX","statusLabel","methodLabel","isProposed","formatNsDate","ns","validityLabel","until","verdictHint","head","evidencePreview","total","clipQuote","quote","RULING_CHUNK","QUEUE_CHANGED_RETRIES","MAX_CHUNKS","isQueueChanged","runRuling","base","sel","dryRun","api","confirm","hooks","why","dry","retries","e2","undoRulings","rulingIds","revert","chunkCount","matched","reviewScopeFor","bulkReviewScope","documentProposals","reviewPanel","ruleDocumentProposals","rulingNote","x","action","DEFAULT_SCHEME","TINT_ALPHA","effectiveScheme","scheme","lookup","docColor","chunkColor","chunkInheritsDocColor","hexToTint","hex","h","alpha","tintStyle","color","bg","washStyle","chunkRowStyle","documentColor","copyToClipboard","IdCopy","state","setState","copy","ok","value","glyph","btnTitle","button","compact","buildChunkTree","roots","node","sortRec","nodes","typeIcon","findChunkNode","DocumentChunkTree","expanded","setExpanded","toggle","selectedId","parents","ancestorIds","tree","mutated","tintScheme","colorEnabled","ChunkTreeNode","walk","hasChildren","isOpen","isSelected","rowStyle","hasLink","linkedIds","onSelect","AnnotationBrief","record","StaleBadge","AnnotationPanel","open","setOpen","defaultOpen","editing","setEditing","busyLevel","setBusyLevel","onSave","onRegenerate","regenerate","level","anyStale","anyManual","AnnotationEditor","newLevel","initialBrief","initialAbstract","setBrief","setAbstract","saving","setSaving","save","onCancel","mermaidSeq","flowchartNode","MermaidDiagram","ref","cancelled","mermaid","attr","dark","onNodeClick","ChunkEditorModal","setTitle","setType","setStatus","setBody","fieldsText","setFieldsText","tagsText","setTagsText","conflict","setConflict","isMermaid","isImage","preview","setPreview","replaceImage","b64","onSaved","bodyLabel","msg","SubjectTypeModal","setInForce","choice","setChoice","notice","setNotice","types","choices","unchanged","updated","isStringArray","classificationRecord","fields","rec","pendingClassification","proposedTags","statementCount","resultLabel","report","classDisposition","canApply","formatShare","share","STEP_LABELS","stepLabel","step","candidateDetail","summarizeStep","acceptSummary","notices","skipped","classifyErrorText","Classification","answer","setAnswer","accepting","setAccepting","acceptErr","setAcceptErr","accepted","setAccepted","pending","rootFields","requestKey","apply","onChanged","accept","acceptedSummary","ClassifyAnswerView","disposition","issuers","concepts","steps","written","iss","j","w","normalizeHex","ColorSchemeEditor","root","setRoot","enabled","setEnabled","setScheme","set","docType","docStatus","chunkStatuses","rootChunkId","setColor","fieldsWith","existing","copyToType","targets","documents","applied","tr","docKeys","chunkKeys","ColorRow","onChange","ChunkTarget","targetDocumentId","onSelectChunk","onOpenDocument","StatementMeta","statement","method","verdict","validity","ev","more","StatementReview","rejecting","setRejecting","setReason","rule","onRule","SAMPLE","ProposalReview","selected","setSelected","setStep","setResult","confirmRef","listed","proposals","picked","begin","reasonFor","undo","allPicked","noneToRule","incomplete","BulkConfirm","onAnswer","RELATED_LIMIT","MENTIONS_LIMIT","isEmbedderError","Connections","loading","setLoading","loadedId","setLoadedId","backlinks","setBacklinks","related","setRelated","relatedNote","setRelatedNote","mentions","setMentions","mentionsTruncated","setMentionsTruncated","refreshKey","ready","review","GRAPH_CAP","CrossReferences","showGraph","setShowGraph","refs","graphEdges","graphDef","buildGraph","RefRow","graphEndpoint","outgoing","edge","otherId","otherTitle","otherDoc","onRuleStatement","nodeId","arrow","HANDLE_HEIGHT","clampBottom","minBottom","minTop","StackSplitter","bottom","setBottom","minBottomHeight","defaultBottomHeight","minTopHeight","DocUnavailable","detail","ENTRIES","downloadEntries","runDownload","DownloadMenu","openAt","setOpenAt","rootRef","buttonRef","itemRefs","menuId","onDown","choose","onError","focusItem","onItemKeyDown","busyLabel","el","formatTs","ms","createdAt","HistoryModal","revisions","setRevisions","setMode","selectedRev","setSelectedRev","fromRev","setFromRev","toRev","setToRev","diff","setDiff","revs","nums","viewVersion","rev","runDiff","chunkTitle","DiffView","cls","ln","BARE_BREAK","kids","remarkBareBreak","Markdown","MD_COMPONENTS","source","href","external","lang","imageAlt","DocumentViewerBody","browseProp","setChunks","setSelectedId","selectedDetail","setSelectedDetail","subtreeMd","setSubtreeMd","imageUrl","setImageUrl","imageErr","setImageErr","fileInputRef","retyping","setRetyping","historyOpen","setHistoryOpen","confirmDelete","setConfirmDelete","loadedFor","setLoadedFor","loadErr","setLoadErr","reload","setReload","assistantOpen","setAssistantOpen","meta","setMeta","colorsOpen","setColorsOpen","setEdges","edgesIncomplete","setEdgesIncomplete","edgesReload","setEdgesReload","classifyKey","setClassifyKey","setRootFields","docAnnotations","setDocAnnotations","chunkAnnotations","setChunkAnnotations","annotationReload","setAnnotationReload","refresh","initialChunkRef","initialChunkId","onTitleRef","onTitle","rootTitle","titleHint","selectedIsRoot","ancestors","onChunkSelectRef","onChunkSelect","toolbarTint","unavailable","loadedTitle","saveAnnotation","canEditAnnotations","onAnnotationChanged","regenerateAnnotation","onRegenerateAnnotation","folder","documentBrief","selectedAnnotations","ruleStatement","reviewScope","onReviewChanged","focusSeq","focusChunk","focusRef","chunksRef","depth","md","lvl","details","heading","cap","openDocument","canCreate","addImageFile","created","addDiagram","addText","insertAfter","addChild","siblingBounds","sibs","reorderSelected","direction","deleteSelected","onPaste","ae","tag","renderAssistant","principal","buildLazyTree","opens","ad","KIND_ICON","ANNOTATION_ICON","isAnnotationEntry","nodeBrief","ann","documentSummaryOf","summaries","PathTree","props","PathTreeNode","ListingRows","onRetry","onLoadMore","isDir","selectedPath","summary","onToggle","NAME_RE","joinPath","findNode","PathExplorer","resolved","PathExplorerBody","pathProp","navigatorProp","setScope","defaultScope","internalSelected","setInternalSelected","modal","setModal","transfer","setTransfer","onPathChangeRef","onPathChange","onErrorRef","setTrail","navSeq","emittedPath","applySelection","lazy","navMode","setNavModeState","renderNavigator","starsOn","setNavMode","setMaximized","maximized","navReload","setNavReload","liveChunk","setLiveChunk","focus","setFocus","invalidate","setSummaries","requested","summaryGen","resetSummaries","firstLoad","revealedIn","switched","fresh","gen","loadMore","retry","rootErr","selectedDir","setStored","storedLabel","currentDir","currentDirLabel","newFolder","newDocument","renameSelected","subtree","docIds","mutable","canTransfer","transferSelected","transferDone","view","seq","known","jumpToCrumb","onDocTitle","onNavigatorSelect","navigatorCtx","focusForView","viewIsSelected","PromptModal","vals","setVals","DocumentViewer","DocumentViewerHost","hostChunk","jump"],"sources":["../src/lib/navigator.ts","../src/lib/subjectType.ts","../src/lib/transfer.ts","../src/lib/annotation.ts","../src/lib/download.ts","../src/lib/dataLayer.tsx","../src/lib/lazyPathTree.ts","../src/lib/createClient.ts","../src/components/ExplorerRoot.tsx","../src/lib/docTrail.ts","../src/components/DocTrail.tsx","../src/components/TransferModal.tsx","../src/components/Splitter.tsx","../src/lib/imageUpload.ts","../src/lib/edgePages.ts","../src/lib/chunkAncestry.ts","../src/lib/statement.ts","../src/lib/ruling.ts","../src/lib/bulkReview.ts","../src/lib/colorScheme.ts","../src/lib/clipboard.ts","../src/components/IdCopy.tsx","../src/components/DocumentChunkTree.tsx","../src/components/AnnotationPanel.tsx","../src/components/Mermaid.tsx","../src/components/ChunkEditorModal.tsx","../src/components/SubjectTypeModal.tsx","../src/lib/classify.ts","../src/components/Classification.tsx","../src/components/ColorSchemeEditor.tsx","../src/components/ChunkTarget.tsx","../src/components/Statement.tsx","../src/components/ProposalReview.tsx","../src/components/Connections.tsx","../src/components/CrossReferences.tsx","../src/components/StackSplitter.tsx","../src/components/DocUnavailable.tsx","../src/components/DownloadMenu.tsx","../src/components/HistoryModal.tsx","../src/lib/remarkBareBreak.ts","../src/components/Markdown.tsx","../src/components/DocumentViewerBody.tsx","../src/components/PathTree.tsx","../src/PathExplorer.tsx","../src/DocumentViewer.tsx"],"sourcesContent":["// The explorer's navigator choice: the Path tree (the default) or the slot a\n// host provides (the 3D star map). Remembered per browser; storage failures\n// (private mode, blocked site data) fall back to the tree.\n\nexport type NavigatorMode = \"tree\" | \"stars\";\n\nexport const NAVIGATOR_KEY = \"loomcycle.explorer.navigator\";\n\nexport function readNavigatorMode(storage: Pick<Storage, \"getItem\"> | undefined): NavigatorMode {\n try {\n return storage?.getItem(NAVIGATOR_KEY) === \"stars\" ? \"stars\" : \"tree\";\n } catch {\n return \"tree\";\n }\n}\n\nexport function writeNavigatorMode(\n storage: Pick<Storage, \"setItem\"> | undefined,\n mode: NavigatorMode,\n): void {\n try {\n storage?.setItem(NAVIGATOR_KEY, mode);\n } catch {\n // Blocked storage: the choice lasts for this page only.\n }\n}\n","import type { ChunkDetail } from \"../types\";\n\n// A subject is a document whose ROOT chunk is the entity node: it carries a natural\n// key. A keyed chunk below a root is a fact filed under a subject, not a subject, and\n// re-typing it is an ordinary chunk edit.\nexport function isSubjectRoot(chunk: ChunkDetail | null | undefined): boolean {\n return !!chunk && !chunk.parent_id && !!chunk.entity?.natural_key;\n}\n\n// entityTypeNames reads the entity types in force out of a describe_ontology answer:\n// its chunk classes, sorted. A document class types a document, never the subject a\n// document is about, so it is left out. Anything unexpected reads as no types.\nexport function entityTypeNames(described: unknown): string[] {\n const classes = (described as { classes?: unknown } | null)?.classes;\n if (!Array.isArray(classes)) return [];\n const names = new Set<string>();\n for (const c of classes) {\n const { name, kind } = (c ?? {}) as { name?: unknown; kind?: unknown };\n if (typeof name === \"string\" && name !== \"\" && kind !== \"document\") names.add(name);\n }\n return [...names].sort((a, b) => a.localeCompare(b));\n}\n\n// subjectTypeChoices is what the change-type picker offers: the types in force, and\n// the subject's current type even when it is not one of them, so the picker can show\n// where the subject stands rather than silently preselecting something else.\nexport function subjectTypeChoices(inForce: string[], current: string | undefined): string[] {\n const cur = current ?? \"\";\n if (cur === \"\" || inForce.some((t) => t.toLowerCase() === cur.toLowerCase())) return inForce;\n return [cur, ...inForce];\n}\n","// transfer.ts — the explorer's \"copy / move\" of a document or a folder's\n// documents into another scope (the Document tool's copy_documents and\n// move_documents). Pure: the request the dialog sends and the lines it shows,\n// kept apart from the component so both are tested without a DOM.\n\nimport type { DocScope } from \"../types\";\n\nexport type TransferOp = \"copy\" | \"move\";\n\n// TransferRequest is what the dialog asks for. A document is named by id (its\n// own path names no folder to list); a folder by its path, every document at or\n// under it. `from` → `to` rewrites the names on the way.\nexport interface TransferRequest {\n op: TransferOp;\n scope: DocScope;\n toScope: DocScope;\n documentId?: string;\n underPath?: string;\n from: string;\n to: string;\n dropDangling?: boolean;\n dryRun: boolean;\n expectCount?: number;\n}\n\nexport interface TransferRefusal {\n document_id: string;\n code: string;\n detail?: string;\n}\n\nexport interface TransferDangling {\n statement_id: string;\n kind: string;\n from: string;\n to: string;\n outside: \"from\" | \"to\" | \"evidence\" | string;\n}\n\n// TransferResult is the answer of both ops, dry run or not. Fields a call did\n// not produce are absent.\nexport interface TransferResult {\n dry_run: boolean;\n documents: { id: string; new_id?: string; paths: string[]; resumed?: boolean }[];\n counts: Record<string, number>;\n refused: TransferRefusal[];\n refused_count?: number;\n dangling: TransferDangling[];\n dangling_count: number;\n blocked_by?: string;\n dropped?: number;\n moved?: string[];\n to_finish?: string[];\n unfinished?: { document_id: string; code: string; detail?: string }[];\n name_failures?: { document_id: string; path: string; error: string }[];\n body_failures?: number;\n statements_failed?: number;\n statement_error?: string;\n}\n\n// transferInput is the Document tool input for a request.\nexport function transferInput(r: TransferRequest): Record<string, unknown> {\n const input: Record<string, unknown> = {\n op: r.op === \"copy\" ? \"copy_documents\" : \"move_documents\",\n scope: r.scope,\n to_scope: r.toScope,\n dry_run: r.dryRun,\n };\n if (r.documentId) input.document_ids = [r.documentId];\n if (r.underPath) input.under_path = r.underPath;\n const from = trimSlash(r.from);\n const to = trimSlash(r.to);\n if (from && to && from !== to) input.path_map = { [from]: to };\n if (r.op === \"move\") {\n if (r.dropDangling) input.dangling = \"drop\";\n if (!r.dryRun) input.expect_count = r.expectCount ?? 0;\n }\n return input;\n}\n\n// transferProblem is why a request cannot be sent, or null.\nexport function transferProblem(r: TransferRequest): string | null {\n const to = r.to.trim();\n if (!to.startsWith(\"/\")) return \"the new path must start with /\";\n if (r.op === \"move\" && r.toScope === r.scope) {\n return \"a move goes to another scope; to rename within this one, use rename / move\";\n }\n if (r.op === \"copy\" && r.toScope === r.scope && trimSlash(to) === trimSlash(r.from)) {\n return \"a copy into the same scope needs a new path\";\n }\n return null;\n}\n\n// transferSummary is the lines the dialog shows for an answer: what will happen\n// (a dry run) or what did (a real call), then what stands in the way.\nexport function transferSummary(op: TransferOp, res: TransferResult): string[] {\n const c = res.counts ?? {};\n const n = c.documents ?? 0;\n const verb = op === \"copy\" ? \"copied\" : \"moved\";\n const lines: string[] = [];\n const parts = `${c.chunks ?? 0} parts, ${c.revisions ?? 0} revisions, ${c.statements ?? 0} relations, ${c.assets ?? 0} images`;\n if (res.dry_run) {\n lines.push(`${n} ${plural(n, \"document\")} would be ${verb}: ${parts}.`);\n if (res.to_finish?.length) {\n lines.push(`${res.to_finish.length} ${plural(res.to_finish.length, \"document\")} left by an earlier interrupted move will be finished.`);\n }\n } else if (op === \"move\") {\n const m = res.moved?.length ?? 0;\n lines.push(`${m} ${plural(m, \"document\")} moved: ${parts}.`);\n } else {\n lines.push(`${n} ${plural(n, \"document\")} copied: ${parts}.`);\n }\n const refused = res.refused_count ?? res.refused?.length ?? 0;\n if (refused > 0) {\n lines.push(`${refused} ${plural(refused, \"document\")} refused:`);\n for (const r of res.refused ?? []) lines.push(` ${r.document_id}: ${r.code}${r.detail ? ` — ${r.detail}` : \"\"}`);\n }\n if (res.dangling_count > 0) {\n if (op === \"copy\") {\n lines.push(`${res.dangling_count} ${plural(res.dangling_count, \"relation\")} to documents outside the set stay behind.`);\n } else if (res.dropped !== undefined) {\n lines.push(`${res.dropped} ${plural(res.dropped, \"relation\")} to documents outside the set were dropped.`);\n } else if (res.blocked_by === \"dangling_relations\") {\n lines.push(\n `${res.dangling_count} ${plural(res.dangling_count, \"relation\")} join these documents to ones outside the set. ` +\n \"A relation cannot span two scopes: include the other documents, or drop these relations.\",\n );\n } else {\n lines.push(`${res.dangling_count} ${plural(res.dangling_count, \"relation\")} to documents outside the set will be dropped.`);\n }\n for (const d of res.dangling ?? []) lines.push(` ${d.kind}: ${d.from} → ${d.to} (outside: ${d.outside})`);\n }\n for (const u of res.unfinished ?? []) {\n lines.push(`not finished: ${u.document_id}: ${u.code}${u.detail ? ` — ${u.detail}` : \"\"}. Run the move again.`);\n }\n for (const f of res.name_failures ?? []) lines.push(`no name ${f.path} for ${f.document_id}: ${f.error}`);\n if (res.body_failures) lines.push(`${res.body_failures} ${plural(res.body_failures, \"body\", \"bodies\")} could not be written.`);\n if (res.statements_failed) {\n lines.push(`${res.statements_failed} ${plural(res.statements_failed, \"relation\")} could not be written${res.statement_error ? `: ${res.statement_error}` : \"\"}.`);\n }\n return lines;\n}\n\n// transferBlocked: the real call would be refused as the dry run stands.\nexport function transferBlocked(op: TransferOp, res: TransferResult, dropDangling: boolean): boolean {\n if (op === \"move\" && res.dangling_count > 0 && !dropDangling) return true;\n return (res.counts?.documents ?? 0) === 0 && !(res.to_finish?.length ?? 0);\n}\n\n// trimSlash drops trailing slashes, keeping a lone \"/\". A loop, not /\\/+$/: that\n// regex backtracks polynomially on a long run of slashes not at the end.\nfunction trimSlash(p: string): string {\n const t = p.trim();\n let end = t.length;\n while (end > 1 && t[end - 1] === \"/\") end--;\n return t.slice(0, end);\n}\n\nfunction plural(n: number, one: string, many = one + \"s\"): string {\n return n === 1 ? one : many;\n}\n","import type { Annotation, AnnotationEdit, AnnotationLevel, BrowseScope, DocScope } from \"../types\";\nimport type { ExplorerDataLayer } from \"./dataLayer\";\n\n// Annotations live only in the tenant scope: the runtime refuses to write one\n// anywhere else and reads return nothing. The viewer therefore makes no call at\n// all for another scope rather than asking a question whose answer is known.\nexport function annotationsApply(scope: DocScope): boolean {\n return scope === \"tenant\";\n}\n\n// The runtime's length caps, in characters (Unicode code points, as the runtime\n// counts them). The editor checks them before sending so an over-long draft is\n// named in place instead of coming back as a refusal.\nexport const BRIEF_MAX_CHARS = 240;\nexport const ABSTRACT_MAX_CHARS = 2000;\n\nconst LEVELS: readonly AnnotationLevel[] = [\"branch\", \"document\", \"path\", \"scheme\", \"concept\", \"class\"];\n\nfunction isLevel(v: unknown): v is AnnotationLevel {\n return typeof v === \"string\" && (LEVELS as readonly string[]).includes(v);\n}\n\n// usableAnnotations keeps the records that describe `chunkId` and carry a\n// brief, ordered branch → document → path. A record that would render as an\n// empty panel is dropped, not padded: nothing here is ever written in place of\n// a missing record.\nexport function usableAnnotations(records: unknown, chunkId: string): Annotation[] {\n if (!Array.isArray(records)) return [];\n return records\n .filter(\n (r): r is Annotation =>\n !!r &&\n typeof r === \"object\" &&\n (r as Annotation).chunk_id === chunkId &&\n isLevel((r as Annotation).level) &&\n typeof (r as Annotation).brief === \"string\" &&\n (r as Annotation).brief.trim() !== \"\",\n )\n .sort((a, b) => LEVELS.indexOf(a.level) - LEVELS.indexOf(b.level));\n}\n\n// loadAnnotations fetches a chunk's records. It answers [] without a call when\n// the scope holds no annotations or the data layer cannot read them.\nexport async function loadAnnotations(\n data: Pick<ExplorerDataLayer, \"documentGetAnnotation\">,\n chunkId: string,\n scope: DocScope,\n browse?: BrowseScope,\n): Promise<Annotation[]> {\n if (!annotationsApply(scope) || !data.documentGetAnnotation || !chunkId) return [];\n const resp = await data.documentGetAnnotation(chunkId, scope, browse);\n return usableAnnotations(resp?.annotations, chunkId);\n}\n\n// annotationLevelFor is the level a new annotation of a chunk takes: the root\n// chunk stands for the whole document, any other chunk is a branch.\nexport function annotationLevelFor(isRoot: boolean): AnnotationLevel {\n return isRoot ? \"document\" : \"branch\";\n}\n\n// codePoints counts characters the way the runtime does (a surrogate pair is\n// one character, not two).\nexport function codePoints(s: string): number {\n return [...s].length;\n}\n\n// annotationDraftProblem says what is wrong with an edit before it is sent, or\n// undefined when it can go.\nexport function annotationDraftProblem(brief: string, abstract: string): string | undefined {\n if (brief.trim() === \"\") return \"The brief is required.\";\n if (codePoints(brief) > BRIEF_MAX_CHARS) return `The brief is longer than ${BRIEF_MAX_CHARS} characters.`;\n if (abstract.trim() === \"\") return \"The abstract is required.\";\n if (codePoints(abstract) > ABSTRACT_MAX_CHARS) {\n return `The abstract is longer than ${ABSTRACT_MAX_CHARS} characters.`;\n }\n return undefined;\n}\n\n// setAnnotationInput is the wire input of an operator's edit: always a manual\n// record (the background walk then leaves it alone), and never an inputs hash,\n// so the runtime stores the hash of the text as it is now.\nexport function setAnnotationInput(edit: AnnotationEdit, scope: DocScope): Record<string, unknown> {\n return {\n op: \"set_annotation\",\n scope,\n id: edit.id,\n level: edit.level,\n brief: edit.brief.trim(),\n abstract: edit.abstract.trim(),\n manual: true,\n };\n}\n\n// writtenByLabel renders a record's writer for the provenance line.\nexport function writtenByLabel(writtenBy: string | undefined): string | undefined {\n if (!writtenBy) return undefined;\n if (writtenBy.startsWith(\"run:\")) return `run ${writtenBy.slice(4)}`;\n if (writtenBy.startsWith(\"principal:\")) return writtenBy.slice(10);\n return writtenBy;\n}\n\n// writtenAtLabel renders the write time in the reader's locale; an unparseable\n// value is shown as the runtime sent it.\nexport function writtenAtLabel(writtenAt: string | undefined): string | undefined {\n if (!writtenAt) return undefined;\n const t = Date.parse(writtenAt);\n return Number.isNaN(t) ? writtenAt : new Date(t).toLocaleString();\n}\n\n// ANNOTATION_ENTRY is the reserved Path name of a folder's annotation document.\nexport const ANNOTATION_ENTRY = \"_annotation\";\n","// Helpers for handing a file to the browser: the document downloads (RFC BS\n// .md / .canvas, RFC GR rendered files) share them.\n\n/** The file formats the runtime renders a document into (RFC GR). */\nexport type RenderFormat = \"pdf\" | \"docx\" | \"odt\" | \"epub\" | \"html\" | \"md\";\n\n/** Options of a rendered export — `GET /v1/_document/export/{id}`. Unset\n * options are left to the server's defaults. */\nexport interface DocumentExportOptions {\n /** Render only the subtree under this chunk. */\n chunk?: string;\n toc?: boolean;\n titlePage?: boolean;\n pageSize?: \"a4\" | \"letter\";\n language?: string;\n /** false leaves the provenance note out (the server puts it in by default). */\n provenance?: boolean;\n}\n\n/** The file name a Content-Disposition header names: the RFC 8187\n * `filename*=UTF-8''…` form first (it carries non-ASCII names), then the plain\n * `filename=\"…\"` / `filename=token` fallback. Undefined when it names none, or\n * only an undecodable `filename*` with no fallback. Any directory part is\n * dropped — the name is used as a download name, never a path. */\nexport function filenameFromContentDisposition(header: string | null | undefined): string | undefined {\n if (!header) return undefined;\n const star = /filename\\*\\s*=\\s*([^']*)'[^']*'([^;]+)/i.exec(header);\n if (star && /^utf-8$/i.test(star[1]!.trim())) {\n try {\n const name = baseName(decodeURIComponent(star[2]!.trim()));\n if (name) return name;\n } catch {\n // malformed percent-encoding: fall back to the plain parameter\n }\n }\n const quoted = /(?:^|;)\\s*filename\\s*=\\s*\"((?:[^\"\\\\]|\\\\.)*)\"/i.exec(header);\n if (quoted) return baseName(quoted[1]!.replace(/\\\\(.)/g, \"$1\")) || undefined;\n const token = /(?:^|;)\\s*filename\\s*=\\s*([^;\\s\"]+)/i.exec(header);\n if (token) return baseName(token[1]!) || undefined;\n return undefined;\n}\n\nfunction baseName(name: string): string {\n return name.slice(Math.max(name.lastIndexOf(\"/\"), name.lastIndexOf(\"\\\\\")) + 1).trim();\n}\n\n/** The message of a refused request: the `error` field of the runtime's\n * `{\"code\",\"error\"}` body, else the status line (e.g. a proxy's HTML page). */\nexport function errorMessageFromBody(text: string, status: number, statusText = \"\"): string {\n try {\n const o = JSON.parse(text) as { error?: unknown };\n if (typeof o.error === \"string\" && o.error) return o.error;\n } catch {\n // not JSON\n }\n return `${status} ${statusText}`.trim();\n}\n\n/** A title made safe as a file-name stem — the rule the .md download has\n * always used. */\nexport function fileStem(title: string | undefined): string {\n return (title || \"document\").replace(/[^\\w.-]+/g, \"_\");\n}\n\n/** Hand a Blob to the browser as a download named `filename`. The object URL\n * is revoked on the next tick, not at once: some browsers start reading the\n * blob only after click() returns. */\nexport function saveBlob(blob: Blob, filename: string): void {\n const url = URL.createObjectURL(blob);\n const a = document.createElement(\"a\");\n a.href = url;\n a.download = filename;\n a.click();\n setTimeout(() => URL.revokeObjectURL(url), 0);\n}\n","import { createContext, useContext, type ReactNode } from \"react\";\nimport type { LoomcycleClient, DocumentToolInput } from \"@loomcycle/client\";\nimport type {\n AcceptClassificationAnswer,\n Annotation,\n AnnotationEdit,\n Backlink,\n BrowseScope,\n CanvasDoc,\n ChunkDetail,\n ChunkRevision,\n ChunkRow,\n ClassifyAnswer,\n ClassifyWrite,\n DocEdge,\n DocScope,\n PathEntry,\n StatementStatus,\n PathScope,\n RelatedChunk,\n UnlinkedMention,\n} from \"../types\";\nimport type { DocSummary, DocumentMeta } from \"./colorScheme\";\nimport type { AssetFetch, JsonPost } from \"./createClient\";\nimport type { RulingCounts, RulingRequest } from \"./ruling\";\nimport { entityTypeNames } from \"./subjectType\";\nimport { transferInput, type TransferRequest, type TransferResult } from \"./transfer\";\nimport { setAnnotationInput } from \"./annotation\";\nimport {\n errorMessageFromBody,\n filenameFromContentDisposition,\n type DocumentExportOptions,\n type RenderFormat,\n} from \"./download\";\n\n// ChunkPatch is the subset of chunk fields update_chunk accepts. `fields` is\n// unknown (arbitrary typed JSON the chunk carries); a blank/absent value leaves\n// the existing fields untouched (the caller only sends what changed).\nexport interface ChunkPatch {\n body?: string;\n fields?: unknown;\n title?: string;\n status?: string;\n type?: string;\n // tags (RFC BS) replace-set the chunk's whole tag set when present ([] clears);\n // the editor always sends the parsed set, so it is authoritative for what shows.\n tags?: string[];\n}\n\n// DocRulingFilter is the review queue filter a document's bulk ruling sends:\n// the statements filed from that document.\nexport interface DocRulingFilter {\n from_document_id: string;\n}\n\n// DocRulingAnswer is a bulk ruling's answer (POST /v1/_statements/rule): the\n// counts runRuling reads, and on a dry run a sample and a breakdown.\nexport interface DocRulingAnswer extends RulingCounts {\n sample?: DocEdge[] | null;\n breakdown?: { kind: string; method: string; count: number }[] | null;\n}\n\n// DocRevertAnswer is a ruling's undo (POST /v1/_statements/revert).\nexport interface DocRevertAnswer {\n ruling_id: string;\n reverted: number;\n changed: number;\n}\n\n// PathLsPage selects one page of an `ls`: `limit` bounds it (the runtime clamps\n// it to 5000), `cursor` is a previous page's next_cursor, passed back verbatim.\nexport interface PathLsPage {\n limit?: number;\n cursor?: string;\n}\n\n// DocEdgesPage is one get_edges page: truncated + next_cursor are present only\n// when more edges follow.\nexport interface DocEdgesPage {\n edges: DocEdge[];\n truncated?: boolean;\n next_cursor?: string;\n}\n\nexport interface PathLsResult {\n path: string;\n entries: PathEntry[];\n truncated?: boolean;\n next_cursor?: string;\n}\n\n// ExplorerDataLayer is the narrow data contract the Path / Document components\n// need — the ten off-run reads/writes the browser makes. Decoupling behind this\n// interface lets a host inject the default client-backed implementation\n// (dataLayerFromClient), or a custom one (e.g. a cookie-authed same-origin\n// fetcher) without the components importing any global api module. Every method\n// takes an optional `browse` (RFC AS browse-by-subject) threaded to the runtime.\nexport interface ExplorerDataLayer {\n // pathLs lists one directory (or, recursive, a whole subtree, flat). The\n // runtime pages every listing (default 500 entries, max 5000): a clipped page\n // reports truncated + next_cursor, and passing that back as `page.cursor`\n // continues it. A custom data layer that returns neither reads as complete.\n pathLs(\n path: string,\n scope: PathScope,\n recursive: boolean,\n browse?: BrowseScope,\n page?: PathLsPage,\n ): Promise<PathLsResult>;\n // pathIsStored reports whether a path has its own dirent (false: an implicit\n // directory, one that exists only through its descendants). A one-level ls\n // reports both as plain `directory` entries, so this is the only way to tell\n // them apart. Optional: without it the detail pane omits its \"stored\" row.\n pathIsStored?(path: string, scope: PathScope, browse?: BrowseScope): Promise<boolean>;\n // documentPath answers \"where is this document in the Path tree\" — the reverse\n // of a dirent, which the runtime has no index for (a dirent names a document;\n // a document does not know its names). It lets the tree follow a document that\n // was opened by id, i.e. reached through a reference. undefined = no dirent\n // found: the document is still readable by id. Optional — without it the tree\n // only follows documents in directories it has already listed.\n documentPath?(\n documentId: string,\n scope: PathScope,\n browse?: BrowseScope,\n ): Promise<string | undefined>;\n pathMkdir(\n path: string,\n scope: PathScope,\n browse?: BrowseScope,\n ): Promise<unknown>;\n pathMv(\n from: string,\n to: string,\n scope: PathScope,\n browse?: BrowseScope,\n ): Promise<unknown>;\n pathRm(\n path: string,\n scope: PathScope,\n recursive: boolean,\n browse?: BrowseScope,\n ): Promise<unknown>;\n documentCreate(\n title: string,\n path: string,\n scope: DocScope,\n browse?: BrowseScope,\n ): Promise<{\n document_id: string;\n root_chunk_id?: string;\n title?: string;\n path?: string;\n }>;\n documentDelete(\n id: string,\n scope: DocScope,\n browse?: BrowseScope,\n ): Promise<unknown>;\n // documentsTransfer copies or moves documents into another scope (the\n // Document tool's copy_documents / move_documents), dry run or real.\n // Optional: a data layer without it hides the explorer's copy / move action.\n documentsTransfer?(req: TransferRequest, browse?: BrowseScope): Promise<TransferResult>;\n documentGet(\n id: string,\n scope: DocScope,\n browse?: BrowseScope,\n ): Promise<DocumentMeta>;\n // documentsSummary returns per-document display metadata (type/status + RFC BN\n // color settings) for a set of ids and/or a Path subtree — the Path tree's\n // one-call coloring source (dirents carry only a document_id).\n documentsSummary(\n opts: { documentIds?: string[]; underPath?: string },\n scope: DocScope,\n browse?: BrowseScope,\n ): Promise<{ documents: DocSummary[] }>;\n documentQueryChunks(\n documentId: string,\n scope: DocScope,\n browse?: BrowseScope,\n ): Promise<{ chunks: ChunkRow[] }>;\n documentGetChunk(\n id: string,\n scope: DocScope,\n browse?: BrowseScope,\n ): Promise<ChunkDetail>;\n // documentCreateChunk creates a new chunk under a parent (RFC BO authoring).\n // afterId (RFC BP) inserts the new chunk immediately after that sibling\n // (server insert-and-shift); when set it overrides parentId.\n documentCreateChunk(\n documentId: string,\n parentId: string,\n patch: ChunkPatch,\n scope: DocScope,\n browse?: BrowseScope,\n afterId?: string,\n ): Promise<ChunkDetail>;\n // documentReorderChunk moves a chunk up/down within its level (RFC BP).\n documentReorderChunk(\n id: string,\n direction: \"up\" | \"down\",\n scope: DocScope,\n browse?: BrowseScope,\n ): Promise<unknown>;\n // documentDeleteChunk deletes a chunk + its subtree (RFC BP; existing\n // delete_chunk op — cascades, refuses the document root).\n documentDeleteChunk(\n id: string,\n scope: DocScope,\n browse?: BrowseScope,\n ): Promise<unknown>;\n // documentSetAsset attaches an image's base64 bytes to a chunk (→ type=image,\n // served by GET /v1/_document/asset/{id}). RFC BO.\n documentSetAsset(\n chunkId: string,\n mediaType: string,\n dataBase64: string,\n filename: string | undefined,\n scope: DocScope,\n browse?: BrowseScope,\n ): Promise<ChunkDetail>;\n // documentGetEdges returns one page of the cross-reference edges touching a\n // document (RFC BN P4) — the References list + relationship graph source. The\n // runtime pages them (500 a page, ordered by kind): a clipped page reports\n // truncated + next_cursor, and passing that back as `page.after` continues it.\n // loadDocumentEdges follows the pages. A custom data layer that returns\n // neither reads as complete.\n documentGetEdges(\n documentId: string,\n scope: DocScope,\n browse?: BrowseScope,\n page?: { after?: string },\n ): Promise<DocEdgesPage>;\n // RFC FN statement ops. Optional, like pathIsStored, so a custom data layer\n // written before them still satisfies the interface: without get_edge the\n // viewer only shows the evidence preview the listing carries, and without both\n // rulings it shows a proposal's status but no Accept / Reject.\n //\n // documentGetEdge returns one statement with ALL its evidence rows.\n documentGetEdge?(\n id: string,\n scope: DocScope,\n browse?: BrowseScope,\n ): Promise<{ statement: DocEdge }>;\n // documentAcceptStatement / documentRejectStatement are the operator's ruling on\n // a proposed statement. The runtime accepts them only from the off-run operator\n // plane (this console), never from an agent inside a run; a refusal rejects the\n // promise with the runtime's error text. A rejection needs a reason.\n documentAcceptStatement?(\n id: string,\n scope: DocScope,\n browse?: BrowseScope,\n reason?: string,\n ): Promise<{ id: string; status: StatementStatus }>;\n documentRejectStatement?(\n id: string,\n reason: string,\n scope: DocScope,\n browse?: BrowseScope,\n ): Promise<{ id: string; status: StatementStatus }>;\n // documentListStatements is the review queue: statements in a status\n // (the runtime defaults to \"proposed\"), paged by `after` = a previous page's\n // next_cursor.\n documentListStatements?(\n scope: DocScope,\n browse?: BrowseScope,\n opts?: { status?: StatementStatus; kind?: string; limit?: number; after?: string },\n ): Promise<{ statements: DocEdge[]; truncated?: boolean; next_cursor?: string }>;\n // RFC FS bulk rulings. Optional, like the single rulings: without\n // documentRuleStatements the Connections panel offers no bulk Accept / Reject,\n // and without documentRevertRuling no undo of one.\n //\n // documentRuleStatements is POST /v1/_statements/rule: a dry run unless\n // `dry_run` is false, and a real call must carry the dry run's `matched` as\n // `expect_count` (runRuling does both). `req.scope` is the review scope, and\n // with the user scope `req.scope_id` the subject whose documents (an\n // operator may name another; a member is refused). `browse.tenant` is an\n // admin's tenant focus. A refusal rejects with an error carrying the\n // server's `code` (queue_changed, forbidden, …).\n documentRuleStatements?(\n req: RulingRequest<DocRulingFilter>,\n browse?: BrowseScope,\n ): Promise<DocRulingAnswer>;\n // documentRevertRuling is POST /v1/_statements/revert: each statement the\n // ruling ruled and nothing changed since goes back to its earlier status.\n // With the user scope, browse.scopeId names the subject, as for the ruling.\n documentRevertRuling?(\n rulingId: string,\n scope: \"tenant\" | \"user\",\n browse?: BrowseScope,\n ): Promise<DocRevertAnswer>;\n // RFC FO classification ops. Optional, like the statement rulings: without\n // documentClassify the viewer offers no Classify action, and without\n // documentAcceptClassification a pending classification is not shown.\n //\n // documentClassify says what the document is from the confirmed ontology.\n // `report` writes nothing; `propose` applies a unique rule match and files the\n // rest for review. A refusal rejects with the runtime's error text.\n documentClassify?(\n documentId: string,\n write: ClassifyWrite,\n scope: DocScope,\n browse?: BrowseScope,\n ): Promise<ClassifyAnswer>;\n // documentAcceptClassification is the operator's acceptance of the pending\n // classification in the root's fields. Like the statement rulings, the runtime\n // takes it only from the off-run operator plane. Nothing pending rejects with\n // the runtime's nothing_pending error.\n documentAcceptClassification?(\n documentId: string,\n scope: DocScope,\n browse?: BrowseScope,\n ): Promise<AcceptClassificationAnswer>;\n // documentEntityTypes lists the entity types in force for the tenant (from\n // describe_ontology), for re-typing a subject. Optional: without it the viewer\n // offers no change-type action.\n documentEntityTypes?(scope: DocScope, browse?: BrowseScope): Promise<string[]>;\n // Annotation ops. Optional, like the rulings: without documentGetAnnotation\n // the viewer shows no annotations, and without documentSetAnnotation it offers\n // no Edit. Annotations exist only in the tenant scope; the viewer never calls\n // either for another scope.\n //\n // documentGetAnnotation returns every record of one chunk (a branch chunk, or a\n // document's root, which may carry both a document and a path record). No\n // record → an empty list.\n documentGetAnnotation?(\n chunkId: string,\n scope: DocScope,\n browse?: BrowseScope,\n ): Promise<{ annotations: Annotation[] }>;\n // documentSetAnnotation writes an operator's edit as a manual record. A\n // refusal rejects with the runtime's error text.\n documentSetAnnotation?(\n edit: AnnotationEdit,\n scope: DocScope,\n browse?: BrowseScope,\n ): Promise<{ annotation: Annotation }>;\n // documentAssetObjectUrl fetches an image chunk's bytes (RFC BO) WITH auth and\n // returns a blob object-URL for an <img src> — a bare <img src=/v1/...> can't\n // carry a bearer header. The CALLER must URL.revokeObjectURL when done. Absent\n // when the data source can't do a raw binary GET (a bare client with no\n // connection) → the viewer falls back to a placeholder.\n documentAssetObjectUrl?(\n chunkId: string,\n scope: DocScope,\n browse?: BrowseScope,\n ): Promise<string>;\n // documentExportFile renders the document into a file (RFC GR —\n // GET /v1/_document/export/{id}): PDF, Word, HTML or Markdown (a Markdown\n // render with pictures arrives as a .zip). `filename` is the server's\n // Content-Disposition name, \"\" when it sent none. A refusal rejects with the\n // server's message. Absent, like documentAssetObjectUrl, when the data source\n // can't do a raw binary GET → the viewer offers only the .md / .canvas\n // downloads.\n documentExportFile?(\n documentId: string,\n scope: DocScope,\n format: RenderFormat,\n browse?: BrowseScope,\n opts?: DocumentExportOptions,\n ): Promise<{ blob: Blob; filename: string }>;\n documentUpdateChunk(\n id: string,\n revision: number,\n patch: ChunkPatch,\n scope: DocScope,\n browse?: BrowseScope,\n ): Promise<ChunkDetail>;\n documentExportMd(\n documentId: string,\n scope: DocScope,\n includeMetadata: boolean,\n browse?: BrowseScope,\n ): Promise<{ markdown: string; title: string; document_id: string }>;\n // documentBacklinks returns the chunks that link TO this chunk (RFC BS) — the\n // \"what links here\" list, each enriched with the source's title/type/status +\n // whether the edge was auto-derived from a [[name]] wikilink.\n documentBacklinks(\n id: string,\n scope: DocScope,\n browse?: BrowseScope,\n ): Promise<{ backlinks: Backlink[] }>;\n // documentRelated returns semantic neighbours of a chunk (RFC BS, vector\n // similarity). It REFUSES when no embedder is configured — the caller catches\n // the error and shows a \"semantic search not configured\" note. limit caps the\n // result count (server default when omitted).\n documentRelated(\n id: string,\n scope: DocScope,\n browse?: BrowseScope,\n limit?: number,\n ): Promise<{ related: RelatedChunk[] }>;\n // documentUnlinkedMentions returns chunks that mention this chunk's title but\n // don't link to it (RFC BS) — candidate links. `truncated` flags an elided tail.\n documentUnlinkedMentions(\n id: string,\n scope: DocScope,\n browse?: BrowseScope,\n limit?: number,\n ): Promise<{ unlinked_mentions: UnlinkedMention[]; truncated: boolean }>;\n // documentHistory returns a chunk's edit history (RFC BS) — revision numbers +\n // timestamps + actors, newest-relevant first as the server orders them.\n documentHistory(\n id: string,\n scope: DocScope,\n browse?: BrowseScope,\n limit?: number,\n ): Promise<{ chunk_id: string; revisions: ChunkRevision[] }>;\n // documentGetVersion returns one historical revision's body verbatim (RFC BS).\n documentGetVersion(\n id: string,\n revision: number,\n scope: DocScope,\n browse?: BrowseScope,\n ): Promise<{ chunk_id: string; revision: number; body: string }>;\n // documentDiff returns a unified-diff text between two revisions of a chunk\n // (RFC BS) — from_revision → to_revision.\n documentDiff(\n id: string,\n fromRevision: number,\n toRevision: number,\n scope: DocScope,\n browse?: BrowseScope,\n ): Promise<{\n chunk_id: string;\n from_revision: number;\n to_revision: number;\n diff: string;\n }>;\n // documentExportCanvas returns the whole document as a node/edge canvas graph\n // (RFC BS), downloaded as a `.canvas` (JSON) file by the viewer.\n documentExportCanvas(\n documentId: string,\n scope: DocScope,\n browse?: BrowseScope,\n ): Promise<{ canvas: CanvasDoc; document_id: string }>;\n}\n\n// DOCUMENT_PATH_PAGES bounds the documentPath scan: that many pages of the\n// largest size the runtime serves. Subject-homed facts are document dirents too,\n// so a scope can hold tens of thousands; past the bound the lookup gives up and\n// the document simply opens without a tree position.\nconst DOCUMENT_PATH_PAGES = 4;\nconst DOCUMENT_PATH_PAGE_LIMIT = 5000;\n\n// dataLayerFromClient maps a @loomcycle/client instance onto the\n// ExplorerDataLayer. Path ops route to client.path (POST /v1/_path); document\n// ops to client.document (POST /v1/_document) — both op-discriminated.\n//\n// browse is passed straight through as the client's opts second argument: a\n// BrowseScope ({scopeId?, tenant?}) is structurally the client's browse opts, so\n// the SDK serializes it to ?scope_id= / ?tenant= (empty/undefined → the caller's\n// own subject, byte-identical to the pre-RFC-AS behaviour). Responses are\n// op-varying `unknown`, cast to the kept shapes the components consume.\n//\n// jsonPost (the connection path) reaches the RFC FS review routes when the\n// client has no method for them; see reviewOps.\nexport function dataLayerFromClient(\n client: LoomcycleClient,\n assetFetch?: AssetFetch,\n jsonPost?: JsonPost,\n): ExplorerDataLayer {\n return {\n ...reviewOps(client, jsonPost),\n pathLs: (path, scope, recursive, browse, page) =>\n client.path(\n {\n op: \"ls\",\n path,\n scope,\n recursive,\n ...(page?.limit ? { limit: page.limit } : {}),\n ...(page?.cursor ? { cursor: page.cursor } : {}),\n },\n browse,\n ) as Promise<PathLsResult>,\n // stat refuses a path with no dirent; that refusal IS the answer \"implicit\"\n // here (the path came from a listing, so it exists). Any other failure —\n // network, auth — is not an answer and propagates. Matched by name, not\n // instanceof: the host's client may be a different copy of the package.\n pathIsStored: (path, scope, browse) =>\n client.path({ op: \"stat\", path, scope }, browse).then(\n () => true,\n (e: unknown) => {\n if ((e as { name?: string } | null)?.name === \"SubstrateToolRefusedError\") return false;\n throw e;\n },\n ),\n // One recursive listing of document dirents, followed page by page until the\n // document turns up.\n documentPath: async (documentId, scope, browse) => {\n let cursor: string | undefined;\n for (let page = 0; page < DOCUMENT_PATH_PAGES; page++) {\n const resp = (await client.path(\n {\n op: \"ls\",\n path: \"/\",\n scope,\n recursive: true,\n kind_filter: \"document\",\n limit: DOCUMENT_PATH_PAGE_LIMIT,\n ...(cursor ? { cursor } : {}),\n },\n browse,\n )) as PathLsResult;\n const hit = (resp.entries ?? []).find(\n (e) => (e.resource_ref as { document_id?: string } | undefined)?.document_id === documentId,\n );\n if (hit) return hit.full_path;\n cursor = resp.next_cursor || undefined;\n if (!cursor) return undefined;\n }\n return undefined;\n },\n pathMkdir: (path, scope, browse) =>\n client.path({ op: \"mkdir\", path, scope }, browse),\n pathMv: (from, to, scope, browse) =>\n client.path({ op: \"mv\", path: from, to, scope }, browse),\n pathRm: (path, scope, recursive, browse) =>\n client.path({ op: \"rm\", path, scope, recursive }, browse),\n // The `as unknown as DocumentToolInput` casts below are the same pinned-SDK\n // workaround documentReorderChunk already uses, for a different reason: the\n // published @loomcycle/client still types `scope` as \"agent\" | \"user\", from\n // when Documents refused tenant scope. The runtime has accepted tenant since\n // v1.41.0 and adapters/ts is fixed at source, so these casts come out on the\n // next client publish — they are not papering over a wire mismatch, they are\n // waiting for a version bump.\n documentCreate: (title, path, scope, browse) =>\n client.document(\n { op: \"create_document\", title, path, scope } as unknown as DocumentToolInput,\n browse,\n ) as Promise<{\n document_id: string;\n root_chunk_id?: string;\n title?: string;\n path?: string;\n }>,\n documentDelete: (id, scope, browse) =>\n client.document({ op: \"delete_document\", id, scope } as unknown as DocumentToolInput, browse),\n // copy_documents / move_documents are newer than the pinned SDK type; the\n // /v1/_document passthrough takes them verbatim.\n documentsTransfer: (req, browse) =>\n client.document(transferInput(req) as unknown as DocumentToolInput, browse) as Promise<TransferResult>,\n documentGet: (id, scope, browse) =>\n client.document({ op: \"get_document\", id, scope } as unknown as DocumentToolInput, browse) as Promise<DocumentMeta>,\n documentsSummary: (opts, scope, browse) =>\n client.document(\n // documents_summary + document_ids are RFC BN wire additions the pinned\n // SDK type doesn't enumerate; the /v1/_document passthrough accepts them\n // verbatim, so cast past DocumentToolInput (same pattern as update_chunk).\n {\n op: \"documents_summary\",\n scope,\n ...(opts.documentIds ? { document_ids: opts.documentIds } : {}),\n ...(opts.underPath ? { under_path: opts.underPath } : {}),\n } as unknown as DocumentToolInput,\n browse,\n ) as Promise<{ documents: DocSummary[] }>,\n documentQueryChunks: (documentId, scope, browse) =>\n client.document(\n { op: \"query_chunks\", document_id: documentId, scope, limit: 1000 } as unknown as DocumentToolInput,\n browse,\n ) as Promise<{ chunks: ChunkRow[] }>,\n documentGetChunk: (id, scope, browse) =>\n client.document({ op: \"get_chunk\", id, scope } as unknown as DocumentToolInput, browse) as Promise<ChunkDetail>,\n documentCreateChunk: (documentId, parentId, patch, scope, browse, afterId) =>\n client.document(\n {\n op: \"create_chunk\",\n document_id: documentId,\n parent_id: parentId,\n scope,\n ...(afterId ? { after_id: afterId } : {}),\n ...patch,\n } as unknown as DocumentToolInput,\n browse,\n ) as Promise<ChunkDetail>,\n documentReorderChunk: (id, direction, scope, browse) =>\n client.document(\n // reorder_chunk is an RFC BP wire op the pinned SDK type doesn't\n // enumerate; the /v1/_document passthrough accepts it verbatim.\n { op: \"reorder_chunk\", id, direction, scope } as unknown as DocumentToolInput,\n browse,\n ),\n documentDeleteChunk: (id, scope, browse) =>\n client.document({ op: \"delete_chunk\", id, scope } as unknown as DocumentToolInput, browse),\n documentSetAsset: (chunkId, mediaType, dataBase64, filename, scope, browse) =>\n client.document(\n // set_asset is an RFC BO wire op the pinned SDK type doesn't enumerate;\n // the /v1/_document passthrough accepts it verbatim.\n {\n op: \"set_asset\",\n id: chunkId,\n media_type: mediaType,\n data: dataBase64,\n ...(filename ? { filename } : {}),\n scope,\n } as unknown as DocumentToolInput,\n browse,\n ) as Promise<ChunkDetail>,\n documentGetEdges: (documentId, scope, browse, page) =>\n client.document(\n // get_edges is an RFC BN P4 wire op the pinned SDK type doesn't\n // enumerate; the /v1/_document passthrough accepts it verbatim.\n {\n op: \"get_edges\",\n document_id: documentId,\n scope,\n ...(page?.after ? { after: page.after } : {}),\n } as unknown as DocumentToolInput,\n browse,\n ) as Promise<DocEdgesPage>,\n // RFC FN statement ops — the same passthrough cast: new wire ops the pinned\n // SDK type doesn't enumerate.\n documentGetEdge: (id, scope, browse) =>\n client.document(\n { op: \"get_edge\", id, scope } as unknown as DocumentToolInput,\n browse,\n ) as Promise<{ statement: DocEdge }>,\n documentAcceptStatement: (id, scope, browse, reason) =>\n client.document(\n {\n op: \"accept_statement\",\n id,\n scope,\n ...(reason ? { reason } : {}),\n } as unknown as DocumentToolInput,\n browse,\n ) as Promise<{ id: string; status: StatementStatus }>,\n documentRejectStatement: (id, reason, scope, browse) =>\n client.document(\n { op: \"reject_statement\", id, reason, scope } as unknown as DocumentToolInput,\n browse,\n ) as Promise<{ id: string; status: StatementStatus }>,\n documentListStatements: (scope, browse, opts) =>\n client.document(\n {\n op: \"list_statements\",\n scope,\n ...(opts?.status ? { status: opts.status } : {}),\n ...(opts?.kind ? { kind: opts.kind } : {}),\n ...(opts?.limit ? { limit: opts.limit } : {}),\n ...(opts?.after ? { after: opts.after } : {}),\n } as unknown as DocumentToolInput,\n browse,\n ) as Promise<{ statements: DocEdge[]; truncated?: boolean; next_cursor?: string }>,\n // RFC FO classification ops — the same passthrough cast.\n documentClassify: (documentId, write, scope, browse) =>\n client.document(\n { op: \"classify\", document_id: documentId, write, scope } as unknown as DocumentToolInput,\n browse,\n ) as Promise<ClassifyAnswer>,\n documentEntityTypes: (scope, browse) =>\n client\n .document({ op: \"describe_ontology\", scope } as unknown as DocumentToolInput, browse)\n .then(entityTypeNames),\n documentAcceptClassification: (documentId, scope, browse) =>\n client.document(\n { op: \"accept_classification\", document_id: documentId, scope } as unknown as DocumentToolInput,\n browse,\n ) as Promise<AcceptClassificationAnswer>,\n // Annotation ops — the same passthrough cast: wire ops newer than the\n // pinned SDK type.\n documentGetAnnotation: (chunkId, scope, browse) =>\n client.document(\n { op: \"get_annotation\", id: chunkId, scope } as unknown as DocumentToolInput,\n browse,\n ) as Promise<{ annotations: Annotation[] }>,\n documentSetAnnotation: (edit, scope, browse) =>\n client.document(setAnnotationInput(edit, scope) as unknown as DocumentToolInput, browse) as Promise<{\n annotation: Annotation;\n }>,\n documentUpdateChunk: (id, revision, patch, scope, browse) =>\n client.document(\n // `patch.fields` is unknown but DocumentToolInput.fields is a typed\n // Record; the cast reconciles the spread (the server accepts arbitrary\n // JSON there). Op order + arg names mirror the wire contract exactly.\n {\n op: \"update_chunk\",\n id,\n revision,\n scope,\n ...patch,\n } as DocumentToolInput,\n browse,\n ) as Promise<ChunkDetail>,\n documentExportMd: (documentId, scope, includeMetadata, browse) =>\n client.document(\n {\n op: \"export_md\",\n document_id: documentId,\n scope,\n include_metadata: includeMetadata,\n } as unknown as DocumentToolInput,\n browse,\n ) as Promise<{ markdown: string; title: string; document_id: string }>,\n // RFC BS document-connections + history + canvas ops. Same `as unknown as\n // DocumentToolInput` passthrough as documentGetEdges — new wire ops the pinned\n // SDK type doesn't enumerate; the /v1/_document passthrough accepts them\n // verbatim (adapters/ts is fixed at source, so the casts come out on the next\n // client publish).\n documentBacklinks: (id, scope, browse) =>\n client.document(\n { op: \"backlinks\", id, scope } as unknown as DocumentToolInput,\n browse,\n ) as Promise<{ backlinks: Backlink[] }>,\n documentRelated: (id, scope, browse, limit) =>\n client.document(\n {\n op: \"related\",\n id,\n scope,\n ...(limit ? { limit } : {}),\n } as unknown as DocumentToolInput,\n browse,\n ) as Promise<{ related: RelatedChunk[] }>,\n documentUnlinkedMentions: (id, scope, browse, limit) =>\n client.document(\n {\n op: \"unlinked_mentions\",\n id,\n scope,\n ...(limit ? { limit } : {}),\n } as unknown as DocumentToolInput,\n browse,\n ) as Promise<{ unlinked_mentions: UnlinkedMention[]; truncated: boolean }>,\n documentHistory: (id, scope, browse, limit) =>\n client.document(\n {\n op: \"history\",\n id,\n scope,\n ...(limit ? { limit } : {}),\n } as unknown as DocumentToolInput,\n browse,\n ) as Promise<{ chunk_id: string; revisions: ChunkRevision[] }>,\n documentGetVersion: (id, revision, scope, browse) =>\n client.document(\n { op: \"get_version\", id, revision, scope } as unknown as DocumentToolInput,\n browse,\n ) as Promise<{ chunk_id: string; revision: number; body: string }>,\n documentDiff: (id, fromRevision, toRevision, scope, browse) =>\n client.document(\n {\n op: \"diff\",\n id,\n from_revision: fromRevision,\n to_revision: toRevision,\n scope,\n } as unknown as DocumentToolInput,\n browse,\n ) as Promise<{\n chunk_id: string;\n from_revision: number;\n to_revision: number;\n diff: string;\n }>,\n documentExportCanvas: (documentId, scope, browse) =>\n client.document(\n { op: \"export_canvas\", document_id: documentId, scope } as unknown as DocumentToolInput,\n browse,\n ) as Promise<{ canvas: CanvasDoc; document_id: string }>,\n // Present only when an AssetFetch was supplied (the connection path); a bare\n // client can't do the raw binary GET, so the op is omitted and the viewer\n // shows a placeholder.\n ...(assetFetch\n ? {\n documentAssetObjectUrl: async (chunkId, scope, browse) => {\n const q = new URLSearchParams({ scope });\n if (browse?.scopeId) q.set(\"scope_id\", browse.scopeId);\n if (browse?.tenant) q.set(\"tenant\", browse.tenant);\n const resp = await assetFetch(\n `/v1/_document/asset/${encodeURIComponent(chunkId)}?${q.toString()}`,\n );\n if (!resp.ok) throw new Error(`asset fetch failed: ${resp.status}`);\n const blob = await resp.blob();\n return URL.createObjectURL(blob);\n },\n documentExportFile: async (documentId, scope, format, browse, opts) => {\n const resp = await assetFetch(documentExportPath(documentId, scope, format, browse, opts));\n if (!resp.ok) {\n throw new Error(errorMessageFromBody(await resp.text(), resp.status, resp.statusText));\n }\n const blob = await resp.blob();\n return {\n blob,\n filename: filenameFromContentDisposition(resp.headers.get(\"Content-Disposition\")) ?? \"\",\n };\n },\n }\n : {}),\n };\n}\n\n// documentExportPath builds the export route's path + query. Unset options are\n// left out, so the server's defaults apply.\nexport function documentExportPath(\n documentId: string,\n scope: DocScope,\n format: RenderFormat,\n browse?: BrowseScope,\n opts?: DocumentExportOptions,\n): string {\n const q = new URLSearchParams({ format, scope });\n if (browse?.scopeId) q.set(\"scope_id\", browse.scopeId);\n if (browse?.tenant) q.set(\"tenant\", browse.tenant);\n if (opts?.chunk) q.set(\"chunk\", opts.chunk);\n if (opts?.toc) q.set(\"toc\", \"true\");\n if (opts?.titlePage) q.set(\"title_page\", \"true\");\n if (opts?.pageSize) q.set(\"page_size\", opts.pageSize);\n if (opts?.language) q.set(\"language\", opts.language);\n if (opts?.provenance === false) q.set(\"provenance\", \"false\");\n return `/v1/_document/export/${encodeURIComponent(documentId)}?${q.toString()}`;\n}\n\n// ReviewClient is the part of a newer @loomcycle/client this package reads when\n// present: the review methods arrived after the client version it pins.\ninterface ReviewClient {\n ruleStatements?: (\n action: \"accept\" | \"reject\",\n select: { ids: string[] } | { filter: DocRulingFilter },\n opts: {\n reason?: string;\n dryRun?: boolean;\n expectCount?: number;\n max?: number;\n scope?: \"tenant\" | \"user\";\n scopeId?: string;\n tenant?: string;\n },\n ) => Promise<DocRulingAnswer>;\n revertRuling?: (\n rulingId: string,\n opts: { scope?: \"tenant\" | \"user\"; scopeId?: string; tenant?: string },\n ) => Promise<DocRevertAnswer>;\n}\n\n// reviewOps is the bulk ruling and its undo: through the client's own methods\n// when it has them, else a JSON POST over the connection, else absent — and\n// absent means the viewer offers no bulk action.\nfunction reviewOps(\n client: LoomcycleClient,\n jsonPost?: JsonPost,\n): Pick<ExplorerDataLayer, \"documentRuleStatements\" | \"documentRevertRuling\"> {\n const c = client as unknown as ReviewClient;\n const tenantQuery = (browse?: BrowseScope) => (browse?.tenant ? `?tenant=${encodeURIComponent(browse.tenant)}` : \"\");\n const out: Pick<ExplorerDataLayer, \"documentRuleStatements\" | \"documentRevertRuling\"> = {};\n if (typeof c.ruleStatements === \"function\") {\n out.documentRuleStatements = (req, browse) =>\n c.ruleStatements!(req.action, req.ids ? { ids: req.ids } : { filter: req.filter! }, {\n reason: req.reason,\n dryRun: req.dry_run,\n expectCount: req.expect_count,\n max: req.max,\n scope: req.scope,\n scopeId: req.scope_id,\n tenant: browse?.tenant,\n });\n } else if (jsonPost) {\n out.documentRuleStatements = (req, browse) =>\n jsonPost(`/v1/_statements/rule${tenantQuery(browse)}`, req) as Promise<DocRulingAnswer>;\n }\n // The subject whose user documents a revert acts on, as its ruling did.\n const scopeIdOf = (scope: \"tenant\" | \"user\", browse?: BrowseScope) =>\n scope === \"user\" && browse?.scopeId ? browse.scopeId : undefined;\n if (typeof c.revertRuling === \"function\") {\n out.documentRevertRuling = (rulingId, scope, browse) =>\n c.revertRuling!(rulingId, { scope, scopeId: scopeIdOf(scope, browse), tenant: browse?.tenant });\n } else if (jsonPost) {\n out.documentRevertRuling = (rulingId, scope, browse) => {\n const scopeId = scopeIdOf(scope, browse);\n return jsonPost(`/v1/_statements/revert${tenantQuery(browse)}`, {\n ruling_id: rulingId,\n scope,\n ...(scopeId ? { scope_id: scopeId } : {}),\n }) as Promise<DocRevertAnswer>;\n };\n }\n return out;\n}\n\n// The data layer reaches the components through context — no module-global\n// singleton. The root (<PathExplorer> / <DocumentViewer>) builds it once\n// (useMemo over connection identity) and provides it; nested panels/modals read\n// it via useExplorerData().\nconst ExplorerDataContext = createContext<ExplorerDataLayer | null>(null);\n\nexport function ExplorerDataProvider({\n value,\n children,\n}: {\n value: ExplorerDataLayer;\n children: ReactNode;\n}) {\n return (\n <ExplorerDataContext.Provider value={value}>\n {children}\n </ExplorerDataContext.Provider>\n );\n}\n\nexport function useExplorerData(): ExplorerDataLayer {\n const v = useContext(ExplorerDataContext);\n if (!v) {\n throw new Error(\n \"useExplorerData must be used within <PathExplorer> or <DocumentViewer> (no ExplorerDataLayer in context)\",\n );\n }\n return v;\n}\n","import type { BrowseScope, PathEntry, PathScope } from \"../types\";\nimport type { ExplorerDataLayer, PathLsResult } from \"./dataLayer\";\n\n// The Path tree is loaded one directory at a time, one page at a time.\n//\n// WHY NOT ONE RECURSIVE LISTING: the runtime pages every `ls` (500 entries by\n// default, 5000 at most) and orders a recursive one by full path. Subject-homed\n// facts make /facts as large as the tenant's entity count, so a single recursive\n// `ls /` filled its whole first page with /documents/* and /facts/* — and every\n// top-level directory sorting after \"facts\" silently vanished from the tree while\n// the data sat intact server-side. Following every cursor instead would still\n// fetch tens of thousands of dirents to draw a tree whose directories are\n// mostly collapsed. So a directory is listed only when it is opened, and a\n// directory too large for one page says so with a \"load more\" row rather than\n// dropping its tail.\n\n// LS_PAGE_LIMIT matches the runtime's default page; LS_MAX_LIMIT is its ceiling\n// (a larger limit is clamped server-side, so asking for more is pointless).\nexport const LS_PAGE_LIMIT = 500;\nexport const LS_MAX_LIMIT = 5000;\n\n// DirListing is one directory's load state. `entries` are in the runtime's page\n// order (by name), which is what makes \"the next segment is not in a later page\"\n// decidable in reveal.\nexport interface DirListing {\n entries: PathEntry[];\n nextCursor?: string; // set while more pages remain\n loaded: boolean; // at least one page has arrived\n loading: boolean;\n error?: string;\n}\n\n// DirMap keys a listing by directory path, spelled like PathNode.fullPath:\n// \"\" is the root, then \"/a\", \"/a/b\".\nexport type DirMap = ReadonlyMap<string, DirListing>;\n\n// lsTarget maps a directory key onto the path the runtime lists.\nexport function lsTarget(dir: string): string {\n return dir === \"\" ? \"/\" : dir;\n}\n\n// parentPathOf returns the canonical parent of a node path (\"\" = root).\nexport function parentPathOf(fullPath: string): string {\n const idx = fullPath.lastIndexOf(\"/\");\n return idx <= 0 ? \"\" : fullPath.slice(0, idx);\n}\n\n// ancestorsOf returns every directory that must be listed for `path` to show,\n// root first: \"/a/b/c\" → [\"\", \"/a\", \"/a/b\"].\nexport function ancestorsOf(path: string): string[] {\n const out = [\"\"];\n const segs = path.split(\"/\").filter(Boolean);\n let dir = \"\";\n for (let i = 0; i < segs.length - 1; i++) {\n dir = `${dir}/${segs[i]}`;\n out.push(dir);\n }\n return out;\n}\n\nfunction errMessage(e: unknown): string {\n return e instanceof Error ? e.message : String(e);\n}\n\nfunction listingOf(resp: PathLsResult, before: PathEntry[]): DirListing {\n return {\n entries: [...before, ...(resp.entries ?? [])],\n nextCursor: resp.next_cursor || undefined,\n loaded: true,\n loading: false,\n };\n}\n\n// LazyPathTree is the per-(scope, browse) cache of directory listings. It is a\n// plain subscribable store rather than React state so the paging rules can be\n// tested without a DOM; PathExplorer reads it through useSyncExternalStore and\n// builds a fresh instance whenever the scope or browsed subject changes, which\n// is also what discards a previous subject's in-flight responses.\n//\n// Every method that fetches records a failure on the directory's listing (the\n// tree renders it inline) AND rejects, so the caller can report it.\nexport class LazyPathTree {\n private dirs = new Map<string, DirListing>();\n private snapshot: DirMap = new Map();\n private readonly listeners = new Set<() => void>();\n private readonly inflight = new Map<string, Promise<void>>();\n // epoch bumps whenever a directory is re-listed from its first page or\n // dropped, so a page that was in flight across that point is discarded\n // instead of being appended to a listing it no longer continues.\n private readonly epoch = new Map<string, number>();\n\n constructor(\n private readonly data: ExplorerDataLayer,\n private readonly scope: PathScope,\n private readonly browse?: BrowseScope,\n private readonly pageLimit: number = LS_PAGE_LIMIT,\n ) {}\n\n getSnapshot = (): DirMap => this.snapshot;\n\n subscribe = (fn: () => void): (() => void) => {\n this.listeners.add(fn);\n return () => {\n this.listeners.delete(fn);\n };\n };\n\n private publish() {\n this.snapshot = new Map(this.dirs);\n this.listeners.forEach((fn) => fn());\n }\n\n private set(dir: string, listing: DirListing) {\n this.dirs.set(dir, listing);\n this.publish();\n }\n\n private track(dir: string, p: Promise<void>): Promise<void> {\n const tracked = p.finally(() => {\n if (this.inflight.get(dir) === tracked) this.inflight.delete(dir);\n });\n this.inflight.set(dir, tracked);\n return tracked;\n }\n\n // loadDir lists a directory's first page unless it is already listed. A\n // request already in flight for it is joined rather than repeated.\n loadDir(dir: string): Promise<void> {\n const running = this.inflight.get(dir);\n if (running) return running;\n if (this.dirs.get(dir)?.loaded) return Promise.resolve();\n return this.fetchFirst(dir, this.pageLimit);\n }\n\n // reload re-lists a directory from its first page, asking for as many entries\n // as it already showed so a refresh does not fold away pages the operator\n // loaded (up to the runtime's ceiling; past it the \"load more\" row returns).\n // A directory that was shown in full gets a page of headroom on top, so the\n // entry just created in it does not split it back into \"load more\".\n reload(dir: string): Promise<void> {\n const prev = this.dirs.get(dir);\n const shown = prev?.entries.length ?? 0;\n const want = prev?.loaded && !prev.nextCursor ? shown + this.pageLimit : shown;\n return this.fetchFirst(dir, Math.min(LS_MAX_LIMIT, Math.max(this.pageLimit, want)));\n }\n\n private fetchFirst(dir: string, limit: number): Promise<void> {\n const ep = (this.epoch.get(dir) ?? 0) + 1;\n this.epoch.set(dir, ep);\n const prev = this.dirs.get(dir);\n // Keep showing what was there while the new listing is in flight.\n this.set(dir, {\n entries: prev?.entries ?? [],\n nextCursor: prev?.nextCursor,\n loaded: prev?.loaded ?? false,\n loading: true,\n });\n const p = this.data\n .pathLs(lsTarget(dir), this.scope, false, this.browse, { limit })\n .then(\n (resp) => {\n if (this.epoch.get(dir) === ep) this.set(dir, listingOf(resp, []));\n },\n (e: unknown) => {\n if (this.epoch.get(dir) === ep) {\n this.set(dir, {\n entries: prev?.entries ?? [],\n nextCursor: prev?.nextCursor,\n loaded: prev?.loaded ?? false,\n loading: false,\n error: errMessage(e),\n });\n }\n throw e;\n },\n );\n return this.track(dir, p);\n }\n\n // loadMore appends a directory's next page. A no-op when it has none.\n loadMore(dir: string): Promise<void> {\n const running = this.inflight.get(dir);\n if (running) return running;\n const cur = this.dirs.get(dir);\n if (!cur?.nextCursor) return Promise.resolve();\n const ep = this.epoch.get(dir) ?? 0;\n this.set(dir, { ...cur, loading: true, error: undefined });\n const p = this.data\n .pathLs(lsTarget(dir), this.scope, false, this.browse, {\n limit: this.pageLimit,\n cursor: cur.nextCursor,\n })\n .then(\n (resp) => {\n if (this.epoch.get(dir) === ep) this.set(dir, listingOf(resp, cur.entries));\n },\n (e: unknown) => {\n if (this.epoch.get(dir) === ep) {\n this.set(dir, { ...cur, loading: false, error: errMessage(e) });\n }\n throw e;\n },\n );\n return this.track(dir, p);\n }\n\n // reveal lists every ancestor of `path`, paging each one until the next path\n // segment appears, so a deep link to an entry on a later page still resolves.\n // Resolves false when the path is not there. Because a page is ordered by\n // name, paging stops as soon as a page ends past the wanted name.\n async reveal(path: string): Promise<boolean> {\n const segs = path.split(\"/\").filter(Boolean);\n let dir = \"\";\n for (const name of segs) {\n await this.loadDir(dir);\n for (;;) {\n const l = this.dirs.get(dir);\n if (!l) return false;\n if (l.entries.some((e) => e.name === name)) break;\n const last = l.entries[l.entries.length - 1];\n if (!l.nextCursor || (last && last.name > name)) return false;\n const cursor = l.nextCursor;\n await this.loadMore(dir);\n // A page that moved nothing forward (a reload raced it, or a runtime\n // that handed back the same cursor) must not spin this loop.\n if (this.dirs.get(dir)?.nextCursor === cursor) return false;\n }\n dir = `${dir}/${name}`;\n }\n return true;\n }\n\n // invalidate re-lists what a change at `path` can alter: every ancestor that\n // is already listed — not just the parent, because an implicit directory\n // appears with its first descendant and vanishes with its last. dropSubtree\n // also forgets the listings at/under `path` (a moved or removed directory's\n // old children must not linger under its old name).\n async invalidate(path: string, opts?: { dropSubtree?: boolean }): Promise<void> {\n if (opts?.dropSubtree) {\n for (const k of [...this.dirs.keys()]) {\n if (k === path || k.startsWith(`${path}/`)) {\n this.dirs.delete(k);\n this.epoch.set(k, (this.epoch.get(k) ?? 0) + 1);\n this.inflight.delete(k);\n }\n }\n this.publish();\n }\n const dirs = ancestorsOf(path).filter((d) => this.dirs.has(d));\n await Promise.all(dirs.map((d) => this.reload(d)));\n }\n\n // refresh re-lists the root and every directory in `keep` that is listed, and\n // forgets the rest (a collapsed directory re-lists when it is next opened).\n async refresh(keep: Iterable<string>): Promise<void> {\n const keepSet = new Set(keep);\n keepSet.add(\"\");\n for (const k of [...this.dirs.keys()]) {\n if (!keepSet.has(k)) {\n this.dirs.delete(k);\n this.epoch.set(k, (this.epoch.get(k) ?? 0) + 1);\n this.inflight.delete(k);\n }\n }\n this.publish();\n const dirs = [...keepSet].filter((d) => d === \"\" || this.dirs.has(d));\n await Promise.all(dirs.map((d) => this.reload(d)));\n }\n}\n\n// listSubtree returns every dirent under `dir`, following the runtime's cursor\n// to the end. For the operations that genuinely need the whole subtree (a branch\n// delete has to find every Document under it) — never for drawing the tree.\nexport async function listSubtree(\n data: ExplorerDataLayer,\n dir: string,\n scope: PathScope,\n browse?: BrowseScope,\n): Promise<PathEntry[]> {\n const out: PathEntry[] = [];\n let cursor: string | undefined;\n for (;;) {\n const resp = await data.pathLs(lsTarget(dir), scope, true, browse, {\n limit: LS_MAX_LIMIT,\n cursor,\n });\n out.push(...(resp.entries ?? []));\n const next = resp.next_cursor || undefined;\n if (!next || next === cursor) return out;\n cursor = next;\n }\n}\n\n// documentIdsOf returns the document_id of every `document` entry.\nexport function documentIdsOf(entries: Iterable<PathEntry>): string[] {\n const ids: string[] = [];\n for (const e of entries) {\n if (e.kind !== \"document\") continue;\n const id = (e.resource_ref as { document_id?: string } | undefined)?.document_id;\n if (id) ids.push(id);\n }\n return ids;\n}\n","import { LoomcycleClient } from \"@loomcycle/client\";\n\n// Connection the host hands to <PathExplorer> / <DocumentViewer>. `fetch` is an\n// optional override so an embedding app can route requests however it needs\n// (proxying, header injection, instrumentation). External consumers just pass\n// baseUrl + token and hit the runtime directly.\nexport interface Connection {\n /** loomcycle base URL. \"\" means same-origin. */\n baseUrl: string;\n /** Bearer token. Omit when the runtime runs in open mode (or when the host\n * authenticates via a same-origin cookie through a custom `fetch`). */\n token?: string;\n /** Optional fetch override (proxying, header injection, instrumentation). */\n fetch?: typeof fetch;\n}\n\n/** Build a loomcycle client from a Connection. The fetch is always wrapped: the\n * SDK calls its stored fetch as a method (`ctx.fetchImpl(url)`), and the\n * browser's native fetch rejects a non-global receiver with \"Illegal\n * invocation\" — so we hand it a plain function that calls global fetch. */\nexport function createLoomcycleClient(c: Connection): LoomcycleClient {\n const impl = c.fetch;\n return new LoomcycleClient({\n baseUrl: c.baseUrl,\n authToken: c.token || undefined,\n fetch: (input, init) => (impl ? impl(input, init) : fetch(input, init)),\n });\n}\n\n/** AssetFetch does a raw authenticated GET against a relative loomcycle path and\n * returns the Response — for BINARY endpoints (RFC BO image assets) the JSON\n * client can't model. It mirrors the Connection's transport: the custom `fetch`\n * (e.g. the Web UI's same-origin cookie fetch) carries cookie auth, and a bearer\n * token is added as an Authorization header when set. */\nexport type AssetFetch = (path: string) => Promise<Response>;\n\n/** Build the AssetFetch from a Connection — the SAME auth transport the JSON\n * client uses, so an image asset loads under both cookie (web) and bearer\n * (standalone package) auth. */\nexport function assetFetchFromConnection(c: Connection): AssetFetch {\n const impl = c.fetch;\n const doFetch: typeof fetch = (input, init) => (impl ? impl(input, init) : fetch(input, init));\n return (path) => {\n const headers: Record<string, string> = {};\n if (c.token) headers.Authorization = `Bearer ${c.token}`;\n return doFetch(c.baseUrl + path, { headers });\n };\n}\n\n/** JsonPost POSTs a JSON body to a relative loomcycle path and returns the parsed\n * answer; a refusal rejects with an Error carrying the HTTP `status` and the\n * server's `code` (e.g. `queue_changed`), its message the server's `error`. It\n * reaches routes the pinned @loomcycle/client may not have a method for yet\n * (RFC FS: POST /v1/_statements/rule and /revert), over the same transport. */\nexport type JsonPost = (path: string, body: unknown) => Promise<unknown>;\n\n/** RequestError is a JsonPost refusal. */\nexport class RequestError extends Error {\n readonly status: number;\n readonly code?: string;\n constructor(message: string, status: number, code?: string) {\n super(message);\n this.name = \"RequestError\";\n this.status = status;\n this.code = code;\n }\n}\n\n/** Build the JsonPost from a Connection — the same auth transport as the JSON\n * client and the asset fetch. */\nexport function jsonPostFromConnection(c: Connection): JsonPost {\n const impl = c.fetch;\n const doFetch: typeof fetch = (input, init) => (impl ? impl(input, init) : fetch(input, init));\n return async (path, body) => {\n const headers: Record<string, string> = { \"Content-Type\": \"application/json\", Accept: \"application/json\" };\n if (c.token) headers.Authorization = `Bearer ${c.token}`;\n const resp = await doFetch(c.baseUrl + path, { method: \"POST\", headers, body: JSON.stringify(body) });\n const text = await resp.text();\n let parsed: unknown = undefined;\n try {\n parsed = text ? JSON.parse(text) : undefined;\n } catch {\n // not JSON: the status line is the message below\n }\n if (!resp.ok) {\n const o = parsed && typeof parsed === \"object\" ? (parsed as { error?: unknown; code?: unknown }) : {};\n const msg = typeof o.error === \"string\" && o.error ? o.error : `${resp.status} ${resp.statusText}`.trim();\n throw new RequestError(msg, resp.status, typeof o.code === \"string\" ? o.code : undefined);\n }\n return parsed;\n };\n}\n","import { useMemo, type ReactNode } from \"react\";\nimport type { LoomcycleClient } from \"@loomcycle/client\";\nimport {\n createLoomcycleClient,\n assetFetchFromConnection,\n jsonPostFromConnection,\n type Connection,\n} from \"../lib/createClient\";\nimport {\n ExplorerDataProvider,\n dataLayerFromClient,\n type ExplorerDataLayer,\n} from \"../lib/dataLayer\";\n\n// ExplorerDataSource is the data-source contract shared by both public roots\n// (<PathExplorer> / <DocumentViewer>). Provide exactly one; precedence is\n// dataLayer > client > connection. The default path is `connection` → an\n// internal LoomcycleClient.\nexport interface ExplorerDataSource {\n /** A raw connection (baseUrl + optional token + optional fetch override). */\n connection?: Connection;\n /** A prebuilt @loomcycle/client instance. */\n client?: LoomcycleClient;\n /** A fully custom data layer (e.g. a cookie-authed same-origin fetcher). */\n dataLayer?: ExplorerDataLayer;\n}\n\n// useResolvedDataLayer picks the data layer from the source props once per\n// connection identity. Depending on the connection's PRIMITIVE fields (not the\n// object) keeps an inline `connection={{...}}` from rebuilding the client every\n// render.\nexport function useResolvedDataLayer(src: ExplorerDataSource): ExplorerDataLayer | null {\n const { dataLayer, client, connection } = src;\n return useMemo<ExplorerDataLayer | null>(() => {\n if (dataLayer) return dataLayer;\n if (client) return dataLayerFromClient(client);\n if (connection)\n return dataLayerFromClient(\n createLoomcycleClient(connection),\n assetFetchFromConnection(connection), // RFC BO — binary image-asset GET\n jsonPostFromConnection(connection), // RFC FS — the review routes\n );\n return null;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [dataLayer, client, connection?.baseUrl, connection?.token, connection?.fetch]);\n}\n\n// ExplorerRoot renders the themeable `.loomcycle-explorer` wrapper + provides the\n// data layer to nested components. When no data source resolved, it shows an\n// inline error banner instead (so a misconfiguration is visible, not silent).\n// The component NEVER redirects on 401 — the host owns the auth flow.\nexport function ExplorerRoot({\n theme,\n dataLayer,\n children,\n}: {\n theme?: \"light\" | \"dark\";\n dataLayer: ExplorerDataLayer | null;\n children: ReactNode;\n}) {\n const themeAttr = theme ? { \"data-theme\": theme } : {};\n if (!dataLayer) {\n return (\n <div className=\"loomcycle-explorer\" {...themeAttr}>\n <div className=\"error-banner\">\n @loomcycle/explorer: provide a <code>connection</code>, <code>client</code>, or{\" \"}\n <code>dataLayer</code> prop.\n </div>\n </div>\n );\n }\n return (\n <div className=\"loomcycle-explorer\" {...themeAttr}>\n <ExplorerDataProvider value={dataLayer}>{children}</ExplorerDataProvider>\n </div>\n );\n}\n","import type { ChunkRow, PathEntry } from \"../types\";\nimport type { DirMap } from \"./lazyPathTree\";\n\n// The document trail: where the reader has been while following references from\n// one document into another, so there is a way back.\n//\n// A reference between chunks can cross documents, and following one replaces the\n// document in the viewer. Without a record of where the reader came from, the\n// only way back is to find the original document again in the tree — and the\n// chunk that was selected there is lost either way. The trail is that record. It\n// is kept as plain data + pure functions (no React) so both hosts — the tree\n// console and the single-document viewer — share one set of rules, and so those\n// rules can be tested without a DOM.\n\n// DocLocation is one stop on the trail: a document and the chunk selected in it.\n// `path` is the document's Path-tree name when it has one and it is known — a\n// document can exist without a dirent, and is then addressed by id alone.\nexport interface DocLocation {\n documentId: string;\n chunkId?: string;\n title?: string;\n path?: string;\n}\n\n// Trail is the visited documents, oldest first; the last entry is the one on\n// screen. Empty = the document was opened directly (from the tree or by a host),\n// and nothing has been followed yet.\nexport type Trail = readonly DocLocation[];\n\n// followReference records a jump from `origin` into `target`. `origin` is the\n// document being left, WITH the chunk selected at that moment — that is what\n// Back has to restore, and it is only known at the moment of leaving. An empty\n// trail is seeded with it; a trail already under way has its last entry (the\n// same document) brought up to date instead of duplicated.\nexport function followReference(trail: Trail, origin: DocLocation, target: DocLocation): Trail {\n const last = trail[trail.length - 1];\n const head =\n last && last.documentId === origin.documentId\n ? [...trail.slice(0, -1), { ...last, ...defined(origin) }]\n : [...trail, origin];\n return [...head, target];\n}\n\n// jumpTo cuts the trail back to the entry at `index`, which becomes the document\n// on screen (with its remembered chunk). An out-of-range index is a no-op.\nexport function jumpTo(trail: Trail, index: number): Trail {\n if (index < 0 || index >= trail.length - 1) return trail;\n return trail.slice(0, index + 1);\n}\n\n// back is jumpTo the previous entry.\nexport function back(trail: Trail): Trail {\n return jumpTo(trail, trail.length - 2);\n}\n\n// amendCurrent fills in what is learned about the document on screen AFTER the\n// jump — its real title once it loads, its path once the lookup answers. It\n// only applies while that document is still the one on screen, so a late answer\n// for a document the reader has already left lands nowhere.\nexport function amendCurrent(\n trail: Trail,\n documentId: string,\n patch: Pick<DocLocation, \"title\" | \"path\">,\n): Trail {\n const last = trail[trail.length - 1];\n if (!last || last.documentId !== documentId) return trail;\n const next = { ...last, ...defined(patch) };\n if (next.title === last.title && next.path === last.path) return trail;\n return [...trail.slice(0, -1), next];\n}\n\n// defined drops undefined values, so merging a partial location never erases a\n// field the trail already knows (an origin snapshot carries no path of its own).\nfunction defined<T extends object>(o: T): Partial<T> {\n return Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined)) as Partial<T>;\n}\n\n// labelOf is what a crumb shows: the document's title, else its path's last\n// segment, else a short id — never blank.\nexport function labelOf(loc: DocLocation): string {\n if (loc.title) return loc.title;\n if (loc.path) return loc.path.slice(loc.path.lastIndexOf(\"/\") + 1) || loc.path;\n return loc.documentId.slice(0, 8);\n}\n\n// TrailItem is one rendered breadcrumb slot: an entry (by its index in the\n// trail), or a gap standing in for the entries folded out of a long trail.\nexport type TrailItem = { kind: \"crumb\"; index: number } | { kind: \"gap\"; hidden: number[] };\n\n// TRAIL_VISIBLE is how many crumbs a trail shows before it folds its middle.\nexport const TRAIL_VISIBLE = 4;\n\n// collapseTrail folds a long trail to its first entry, a gap, and its last\n// entries. The ends are what matter: where the reader started, and the steps\n// that led directly here.\nexport function collapseTrail(length: number, max: number = TRAIL_VISIBLE): TrailItem[] {\n const all: TrailItem[] = Array.from({ length }, (_, index) => ({ kind: \"crumb\", index }));\n if (length <= max || max < 3) return all;\n const tail = max - 1; // crumbs kept at the end, after the first one\n const hidden = Array.from({ length: length - 1 - tail }, (_, i) => i + 1);\n return [all[0], { kind: \"gap\", hidden }, ...all.slice(length - tail)];\n}\n\n// findDocumentPath looks a document up among the directories the tree has\n// already listed. Dirents point at documents (never the reverse), so this is the\n// free half of the id → path lookup; a document in a directory nobody opened is\n// not found here, and the data layer's documentPath is asked instead.\nexport function findDocumentPath(dirs: DirMap, documentId: string): string | undefined {\n for (const listing of dirs.values()) {\n const hit = listing.entries.find((e) => documentIdOf(e) === documentId);\n if (hit) return hit.full_path;\n }\n return undefined;\n}\n\n// documentIdOf reads the document id a `document` dirent points at.\nexport function documentIdOf(entry: PathEntry): string | undefined {\n if (entry.kind !== \"document\") return undefined;\n return (entry.resource_ref as { document_id?: string } | undefined)?.document_id || undefined;\n}\n\n// landingChunk picks the chunk a freshly loaded document opens on: the one asked\n// for when it is among the loaded rows, else the root. A wanted chunk that is\n// not there (deleted since the edge was written, or past the viewer's row cap)\n// falls back to the root rather than selecting something the tree cannot show.\nexport function landingChunk(rows: ChunkRow[], wanted?: string): string | undefined {\n if (wanted && rows.some((c) => c.id === wanted)) return wanted;\n return rows.find((c) => !c.parent_id)?.id;\n}\n","import { useState } from \"react\";\nimport { collapseTrail, labelOf, type Trail } from \"../lib/docTrail\";\n\n// DocTrail is the breadcrumb over a document reached by following references:\n// every document on the way here, each one a button back to it — and to the\n// chunk that was selected there — plus a Back button for the common single step.\n// It renders nothing until a reference has actually been followed (one entry is\n// just \"the document on screen\").\n//\n// A long trail folds its middle into a \"…\" that expands on demand; a long title\n// is cut with an ellipsis in CSS and carried in full by the tooltip.\nexport interface DocTrailProps {\n trail: Trail;\n // onJump receives the index of the trail entry to return to.\n onJump: (index: number) => void;\n}\n\nexport default function DocTrail({ trail, onJump }: DocTrailProps) {\n const [showAll, setShowAll] = useState(false);\n if (trail.length < 2) return null;\n\n const current = trail.length - 1;\n const previous = trail[current - 1];\n const items = collapseTrail(trail.length, showAll ? trail.length : undefined);\n\n return (\n <nav className=\"doc-trail\" aria-label=\"Documents you came through\">\n <button\n type=\"button\"\n className=\"doc-trail-back\"\n onClick={() => onJump(current - 1)}\n title={`Back to ${labelOf(previous)}`}\n >\n ← Back\n </button>\n <ol className=\"doc-trail-list\">\n {items.map((item) =>\n item.kind === \"gap\" ? (\n <li className=\"doc-trail-item\" key=\"gap\">\n <button\n type=\"button\"\n className=\"doc-trail-gap\"\n onClick={() => setShowAll(true)}\n title={`Show ${item.hidden.length} more: ${item.hidden\n .map((i) => labelOf(trail[i]))\n .join(\" › \")}`}\n aria-label={`Show ${item.hidden.length} hidden documents`}\n >\n …\n </button>\n </li>\n ) : item.index === current ? (\n <li className=\"doc-trail-item\" key={item.index}>\n <span className=\"doc-trail-current\" aria-current=\"page\" title={labelOf(trail[current])}>\n {labelOf(trail[current])}\n </span>\n </li>\n ) : (\n <li className=\"doc-trail-item\" key={item.index}>\n <button\n type=\"button\"\n className=\"doc-trail-crumb\"\n onClick={() => onJump(item.index)}\n title={labelOf(trail[item.index])}\n >\n {labelOf(trail[item.index])}\n </button>\n </li>\n ),\n )}\n </ol>\n </nav>\n );\n}\n","import { useMemo, useState, type FormEvent } from \"react\";\nimport type { BrowseScope, DocScope } from \"../types\";\nimport type { ExplorerDataLayer } from \"../lib/dataLayer\";\nimport {\n transferBlocked,\n transferInput,\n transferProblem,\n transferSummary,\n type TransferOp,\n type TransferRequest,\n type TransferResult,\n} from \"../lib/transfer\";\n\nexport interface TransferModalProps {\n data: ExplorerDataLayer;\n scope: DocScope;\n browse?: BrowseScope;\n // What is being copied or moved: one document by id, or a folder's documents.\n documentId?: string;\n underPath?: string;\n // The selected path, the prefix the new path replaces.\n fromPath: string;\n onClose: () => void;\n // Called after a real copy or move, with what was asked and the answer.\n onDone: (req: TransferRequest, res: TransferResult) => void;\n}\n\n// TransferModal copies or moves a document, or every document under a folder,\n// into another scope. It always runs the dry run first and shows what would\n// happen, what is refused and which relations leave the set; the real call is\n// offered only for the inputs that dry run checked, and a move passes the dry\n// run's count so a set that changed since is refused rather than moved.\nexport default function TransferModal({\n data,\n scope,\n browse,\n documentId,\n underPath,\n fromPath,\n onClose,\n onDone,\n}: TransferModalProps) {\n const [op, setOp] = useState<TransferOp>(\"copy\");\n const [toScope, setToScope] = useState<DocScope>(scope === \"tenant\" ? \"user\" : \"tenant\");\n const [to, setTo] = useState(fromPath);\n const [dropDangling, setDropDangling] = useState(false);\n const [checked, setChecked] = useState<{ key: string; res: TransferResult } | null>(null);\n const [done, setDone] = useState<TransferResult | null>(null);\n const [busy, setBusy] = useState(false);\n const [err, setErr] = useState<string | null>(null);\n\n const req = useMemo<TransferRequest>(\n () => ({ op, scope, toScope, documentId, underPath, from: fromPath, to, dropDangling, dryRun: true }),\n [op, scope, toScope, documentId, underPath, fromPath, to, dropDangling],\n );\n const key = JSON.stringify(transferInput(req));\n const problem = transferProblem(req);\n const current = checked && checked.key === key ? checked.res : null;\n const blocked = current ? transferBlocked(op, current, dropDangling) : false;\n const n = current ? (op === \"move\" ? (current.counts?.documents ?? 0) + (current.to_finish?.length ?? 0) : current.counts?.documents ?? 0) : 0;\n\n const submit = async (e: FormEvent) => {\n e.preventDefault();\n if (done) {\n onClose();\n return;\n }\n if (problem || !data.documentsTransfer) return;\n setBusy(true);\n setErr(null);\n try {\n if (!current) {\n setChecked({ key, res: await data.documentsTransfer(req, browse) });\n } else {\n const real: TransferRequest = { ...req, dryRun: false, expectCount: current.counts?.documents ?? 0 };\n const res = await data.documentsTransfer(real, browse);\n setDone(res);\n onDone(real, res);\n }\n } catch (ex) {\n setErr(ex instanceof Error ? ex.message : String(ex));\n } finally {\n setBusy(false);\n }\n };\n\n const label = done\n ? \"close\"\n : busy\n ? \"working…\"\n : !current\n ? \"check\"\n : `${op} ${n} document${n === 1 ? \"\" : \"s\"}`;\n const shown = done ?? current;\n const what = documentId ? \"document\" : \"documents under\";\n\n return (\n <div className=\"modal-overlay\" onClick={busy ? undefined : onClose}>\n <form className=\"modal\" onClick={(e) => e.stopPropagation()} onSubmit={submit}>\n <div className=\"modal-header sticky-top\">\n <h3>\n Copy or move the {what} {fromPath}\n </h3>\n <div className=\"modal-buttons modal-buttons-top\">\n {!done && (\n <button type=\"button\" onClick={onClose} disabled={busy}>\n cancel\n </button>\n )}\n <button\n type=\"submit\"\n className={current && op === \"move\" && !done ? \"danger\" : \"primary\"}\n disabled={busy || (!done && (!!problem || blocked))}\n >\n {label}\n </button>\n </div>\n </div>\n <p className=\"modal-context\">\n A copy gets new ids and leaves the source as it is. A move keeps every id and removes the\n documents from <code>{scope}</code>. Relations between the documents go with them.\n </p>\n <div className=\"paths-nav-switch\" role=\"group\" aria-label=\"Copy or move\">\n {([\"copy\", \"move\"] as const).map((o) => (\n <button\n key={o}\n type=\"button\"\n aria-pressed={op === o}\n className={op === o ? \"active\" : undefined}\n disabled={busy || !!done}\n onClick={() => setOp(o)}\n >\n {o}\n </button>\n ))}\n </div>\n <label className=\"path-field\">\n <span>To scope</span>\n <select value={toScope} disabled={busy || !!done} onChange={(e) => setToScope(e.target.value as DocScope)}>\n <option value=\"user\">user</option>\n <option value=\"agent\">agent</option>\n <option value=\"tenant\">tenant</option>\n </select>\n </label>\n <label className=\"path-field\">\n <span>New path</span>\n <input\n className=\"path-modal-input\"\n value={to}\n disabled={busy || !!done}\n onChange={(e) => setTo(e.target.value)}\n />\n </label>\n {op === \"move\" && (\n <label className=\"path-field\">\n <span>\n <input\n type=\"checkbox\"\n checked={dropDangling}\n disabled={busy || !!done}\n onChange={(e) => setDropDangling(e.target.checked)}\n />{\" \"}\n Drop relations to documents outside the set\n </span>\n </label>\n )}\n {problem && <div className=\"modal-err\">{problem}</div>}\n {shown && (\n <div className=\"modal-context\" aria-live=\"polite\">\n {transferSummary(op, shown).map((line, i) =>\n line.startsWith(\" \") ? (\n <div key={i}>\n <code>{line.trim()}</code>\n </div>\n ) : (\n <div key={i}>{line}</div>\n ),\n )}\n </div>\n )}\n {err && <div className=\"modal-err\">{err}</div>}\n </form>\n </div>\n );\n}\n","import { useCallback, useEffect, useRef, useState, type ReactNode } from \"react\";\n\n// Splitter wraps two children with a draggable vertical handle\n// between them. The left pane's width is owned in state and (when\n// `storageKey` is set) persisted to localStorage so the operator's\n// layout choice survives reloads.\n//\n// Implementation notes:\n// - CSS Grid with three columns: [left] [handle] [right]. Grid\n// keeps the right pane on a fluid `1fr` regardless of the\n// window width, while the left pane snaps to the dragged size.\n// - Drag uses window-level pointermove + pointerup so the user\n// can drag PAST the handle bounds without losing tracking\n// (common UX pitfall when the listener lives on the handle\n// element). The container ref provides the origin for the\n// fractional clientX calculation.\n// - min/max clamps so the user can't drag a pane into oblivion\n// or off-screen.\n//\n// Self-contained copy (the loomcycle Web UI + @loomcycle/library carry the same\n// component); the explorer package deliberately owns its own copy rather than\n// sharing, so it has no cross-package coupling.\n\nexport interface SplitterProps {\n children: [ReactNode, ReactNode];\n // Initial left-pane width in px. Used until the user drags or a\n // persisted value is restored from localStorage.\n defaultLeftWidth?: number;\n // Lower bound for the left pane in px. Pane content has its own\n // overflow:auto so it survives squeezing, but a too-narrow pane\n // is unusable.\n minLeftWidth?: number;\n // Upper bound for the left pane in px. Prevents the operator from\n // dragging the right pane to zero by accident.\n minRightWidth?: number;\n // localStorage key for persistence. Omit to make the split\n // ephemeral (resets on every page mount).\n storageKey?: string;\n // Extra class on the outer wrapper (the parent .paths-view rules\n // expect a specific class; this lets the caller keep those\n // selectors intact).\n className?: string;\n // Give the left pane the whole width. The right pane stays MOUNTED (hidden),\n // so whatever it holds keeps its state for when it comes back.\n hideRight?: boolean;\n}\n\nconst HANDLE_WIDTH = 6;\n\nexport default function Splitter({\n children,\n defaultLeftWidth = 380,\n minLeftWidth = 180,\n minRightWidth = 240,\n storageKey,\n className,\n hideRight = false,\n}: SplitterProps) {\n const restore = (): number => {\n if (storageKey) {\n const stored = localStorage.getItem(storageKey);\n const n = stored ? parseInt(stored, 10) : NaN;\n if (Number.isFinite(n) && n >= minLeftWidth) return n;\n }\n return defaultLeftWidth;\n };\n const [leftWidth, setLeftWidth] = useState<number>(restore);\n // A host that switches layouts (the explorer's tree vs. star map) passes a\n // different key per layout; each remembers its own width.\n const [widthKey, setWidthKey] = useState(storageKey);\n if (widthKey !== storageKey) {\n setWidthKey(storageKey);\n setLeftWidth(restore());\n }\n const containerRef = useRef<HTMLDivElement | null>(null);\n const [dragging, setDragging] = useState(false);\n\n // Persist on every settled width. Debouncing isn't needed — drag\n // already produces a single final settle via pointerup.\n useEffect(() => {\n if (!storageKey || dragging || widthKey !== storageKey) return;\n localStorage.setItem(storageKey, String(Math.round(leftWidth)));\n }, [storageKey, widthKey, leftWidth, dragging]);\n\n const onPointerDown = useCallback((e: React.PointerEvent) => {\n e.preventDefault();\n setDragging(true);\n (e.target as HTMLElement).setPointerCapture(e.pointerId);\n }, []);\n\n const onPointerMove = useCallback(\n (e: React.PointerEvent) => {\n if (!dragging || !containerRef.current) return;\n const rect = containerRef.current.getBoundingClientRect();\n const raw = e.clientX - rect.left;\n const maxAllowed = rect.width - minRightWidth - HANDLE_WIDTH;\n const clamped = Math.max(minLeftWidth, Math.min(raw, maxAllowed));\n setLeftWidth(clamped);\n },\n [dragging, minLeftWidth, minRightWidth],\n );\n\n const onPointerUp = useCallback((e: React.PointerEvent) => {\n setDragging(false);\n try {\n (e.target as HTMLElement).releasePointerCapture(e.pointerId);\n } catch {\n // Pointer was already released (e.g. capture lost from a\n // browser-internal gesture). Safe to ignore.\n }\n }, []);\n\n return (\n <div\n ref={containerRef}\n className={`splitter ${className ?? \"\"} ${dragging ? \"dragging\" : \"\"}`}\n style={{\n // The drag clamps against the container, but a remembered width can come\n // from a wider host (the document viewer is both a full page and a pane\n // inside the Path console) or a since-narrowed window — so CSS clamps it\n // again against the container as it is now.\n gridTemplateColumns: hideRight\n ? \"1fr 0 0\"\n : `min(${leftWidth}px, calc(100% - ${minRightWidth + HANDLE_WIDTH}px)) ${HANDLE_WIDTH}px 1fr`,\n }}\n >\n <div className=\"splitter-pane splitter-left\">{children[0]}</div>\n <div\n hidden={hideRight}\n className=\"splitter-handle\"\n role=\"separator\"\n aria-orientation=\"vertical\"\n aria-valuenow={Math.round(leftWidth)}\n onPointerDown={onPointerDown}\n onPointerMove={onPointerMove}\n onPointerUp={onPointerUp}\n onPointerCancel={onPointerUp}\n />\n <div className=\"splitter-pane splitter-right\" hidden={hideRight}>\n {children[1]}\n </div>\n </div>\n );\n}\n","// RFC BO image-upload helpers for the explorer authoring UI.\n\n// IMAGE_MEDIA_TYPES is the accepted set — mirrors the backend whitelist\n// (validImageMediaTypes / ValidImageMediaType in document.go). SVG is excluded\n// (script-in-SVG XSS surface on the serving endpoint).\nexport const IMAGE_MEDIA_TYPES = [\"image/png\", \"image/jpeg\", \"image/gif\", \"image/webp\"];\n\n// isSupportedImage reports whether a File/Blob's type is an accepted image.\nexport function isSupportedImage(type: string): boolean {\n return IMAGE_MEDIA_TYPES.includes(type);\n}\n\n// readImageAsBase64 reads a File/Blob into standard base64 (NO data: prefix — the\n// set_asset op wants the raw base64, matching the backend's decode). Rejects an\n// unsupported media type up front so the server never sees it.\nexport function readImageAsBase64(file: File | Blob): Promise<{ mediaType: string; data: string }> {\n return new Promise((resolve, reject) => {\n if (!isSupportedImage(file.type)) {\n reject(new Error(`unsupported image type \"${file.type || \"unknown\"}\" (png, jpeg, gif, webp only)`));\n return;\n }\n const reader = new FileReader();\n reader.onerror = () => reject(reader.error ?? new Error(\"failed to read file\"));\n reader.onload = () => {\n // FileReader.readAsDataURL yields \"data:<type>;base64,<payload>\"; strip the\n // prefix to hand set_asset the raw base64.\n const result = String(reader.result ?? \"\");\n const comma = result.indexOf(\",\");\n if (comma < 0) {\n reject(new Error(\"could not decode image data\"));\n return;\n }\n resolve({ mediaType: file.type, data: result.slice(comma + 1) });\n };\n reader.readAsDataURL(file);\n });\n}\n\n// imageFileFromPaste extracts the first supported image from a paste event's\n// clipboard items, or null if none (so a normal text paste is ignored).\nexport function imageFileFromPaste(items: DataTransferItemList | null | undefined): File | null {\n if (!items) return null;\n for (let i = 0; i < items.length; i++) {\n const it = items[i];\n if (it.kind === \"file\" && isSupportedImage(it.type)) {\n const f = it.getAsFile();\n if (f) return f;\n }\n }\n return null;\n}\n","import type { BrowseScope, DocEdge, DocScope } from \"../types\";\nimport type { ExplorerDataLayer } from \"./dataLayer\";\n\n// EDGE_PAGE_CAP bounds how many get_edges pages one document load follows. The\n// runtime serves 500 edges a page, so the viewer holds up to 10,000 — far past\n// what the References list or the graph can show usefully — and a document\n// with more says so rather than looking complete.\nexport const EDGE_PAGE_CAP = 20;\n\n// loadDocumentEdges collects every edge touching a document, following\n// next_cursor until the runtime reports the list complete or the cap is hit.\n// get_edges orders by kind, so an unfollowed cursor drops whole kinds, not a\n// random sample. `incomplete` is true when the load stopped before the end: the\n// cap, a page marked truncated with no cursor, or a data layer that hands back\n// the cursor it was given (one that ignores `after` would otherwise repeat its\n// first page until the cap).\nexport async function loadDocumentEdges(\n data: Pick<ExplorerDataLayer, \"documentGetEdges\">,\n documentId: string,\n scope: DocScope,\n browse?: BrowseScope,\n maxPages: number = EDGE_PAGE_CAP,\n): Promise<{ edges: DocEdge[]; incomplete: boolean }> {\n const edges: DocEdge[] = [];\n let after: string | undefined;\n for (let page = 0; page < maxPages; page++) {\n const r = await data.documentGetEdges(documentId, scope, browse, after ? { after } : undefined);\n if (after && r.next_cursor === after) return { edges, incomplete: true };\n edges.push(...(r.edges ?? []));\n if (!r.truncated) return { edges, incomplete: false };\n if (!r.next_cursor) return { edges, incomplete: true };\n after = r.next_cursor;\n }\n return { edges, incomplete: true };\n}\n","import type { ChunkRow } from \"../types\";\n\n// chunkAncestors returns the chunks above `id`, root first and its direct parent\n// last — the levels a reader can climb back up through from a selected chunk.\n// It is empty for the root, for an id that is not loaded, and for an orphan whose\n// parent is not in the list (there is nothing on screen to go up to).\n//\n// The walk stops on a repeated id, so a corrupt parent cycle cannot hang the\n// viewer; it then returns the ancestors met before the repeat.\nexport function chunkAncestors(chunks: readonly ChunkRow[], id: string | undefined): ChunkRow[] {\n if (!id) return [];\n const byId = new Map(chunks.map((c) => [c.id, c]));\n const seen = new Set<string>([id]);\n const up: ChunkRow[] = [];\n let parentId = byId.get(id)?.parent_id;\n while (parentId && !seen.has(parentId)) {\n const parent = byId.get(parentId);\n if (!parent) break;\n seen.add(parentId);\n up.push(parent);\n parentId = parent.parent_id;\n }\n return up.reverse();\n}\n","import type { EdgeEvidence, StatementFields } from \"../types\";\n\n// Display helpers for the RFC FN statement envelope an edge carries. Pure, so the\n// rules for what a reference row shows are testable without rendering it.\n\n// Methods that are the ordinary way a link comes to exist in a document — typed\n// by hand or written as a [[wikilink]]. Only the others are worth a label.\nconst ORDINARY_METHODS = new Set([\"manual\", \"wikilink\"]);\n\n// EVIDENCE_PREVIEW is how many quotes a reference row shows; a listing carries at\n// most three anyway.\nexport const EVIDENCE_PREVIEW = 3;\nconst QUOTE_MAX = 280;\n\n// statusLabel is the badge for a statement that does not simply hold: proposed or\n// rejected. An asserted statement — or an older server's edge with no status —\n// gets none.\nexport function statusLabel(s: StatementFields): string | undefined {\n return s.status && s.status !== \"asserted\" ? s.status : undefined;\n}\n\n// methodLabel names how the statement was made, when that is not the ordinary\n// manual / wikilink way (an import, a sync, a canvas, an agent at runtime…).\nexport function methodLabel(s: StatementFields): string | undefined {\n return s.method && !ORDINARY_METHODS.has(s.method) ? s.method : undefined;\n}\n\n// isProposed: the statement waits for an operator's ruling.\nexport function isProposed(s: StatementFields): boolean {\n return s.status === \"proposed\" && !!s.id;\n}\n\n// formatNsDate renders a Unix-nanosecond timestamp as a UTC calendar date.\nexport function formatNsDate(ns: number): string {\n return new Date(Math.floor(ns / 1e6)).toISOString().slice(0, 10);\n}\n\n// validityLabel describes when the related thing holds, from valid_at / invalid_at,\n// or undefined when the statement carries neither.\nexport function validityLabel(s: StatementFields): string | undefined {\n const from = s.valid_at != null ? formatNsDate(s.valid_at) : undefined;\n const until = s.invalid_at != null ? formatNsDate(s.invalid_at) : undefined;\n if (from && until) return `valid ${from} → ${until}`;\n if (from) return `valid from ${from}`;\n if (until) return `valid until ${until}`;\n return undefined;\n}\n\n// verdictHint summarizes a ruling — an operator's or a judge model's — for a\n// tooltip: who judged, when, and why. undefined when nobody has judged it.\nexport function verdictHint(s: StatementFields): string | undefined {\n if (s.judged_at == null) return undefined;\n const head = `judged by ${s.judged_by || \"a judge\"} on ${formatNsDate(s.judged_at)}`;\n return s.judge_reason ? `${head}: ${s.judge_reason}` : head;\n}\n\n// evidencePreview picks the quotes a row shows and how many it leaves out.\n// `more` counts against evidence_count (the total), not the rows the listing\n// happened to carry.\nexport function evidencePreview(\n s: StatementFields,\n max = EVIDENCE_PREVIEW,\n): { rows: EdgeEvidence[]; more: number } {\n const rows = (s.evidence ?? []).slice(0, max);\n const total = Math.max(s.evidence_count ?? 0, s.evidence?.length ?? 0);\n return { rows, more: Math.max(0, total - rows.length) };\n}\n\n// clipQuote shortens a long quote for the row; the full text stays the element's\n// tooltip.\nexport function clipQuote(quote: string, max = QUOTE_MAX): string {\n const q = quote.replace(/\\s+/g, \" \").trim();\n return q.length > max ? q.slice(0, max - 1) + \"…\" : q;\n}\n","// A bulk ruling on proposed statements (POST /v1/_statements/rule), run the one\n// way every surface runs it: dry run first, then the real call carrying the dry\n// run's count, in chunks of at most RULING_CHUNK. The document viewer's\n// Connections panel and the Web UI's Review page both go through runRuling, so\n// the order of calls a reviewer's click makes is decided here alone.\n\n// The most statements one call rules (the runtime's cap).\nexport const RULING_CHUNK = 1000;\n// A queue that keeps changing under a ruling stops being retried after this\n// many fresh dry runs, rather than looping on a busy scope.\nexport const QUEUE_CHANGED_RETRIES = 3;\n// A hard ceiling on calls for one ruling: a million statements.\nconst MAX_CHUNKS = 1000;\n\nexport type RulingAction = \"accept\" | \"reject\";\nexport type RulingScope = \"tenant\" | \"user\";\n\n/** One statement's outcome in a ruling or a revert: the status it was ruled to,\n * or the refusal's code and message. */\nexport interface RulingItem {\n id: string;\n status?: string;\n error?: string;\n message?: string;\n}\n\n/** A rule call's body. `F` is the queue filter's shape. */\nexport interface RulingRequest<F> {\n action: RulingAction;\n ids?: string[];\n filter?: F;\n reason?: string;\n dry_run: boolean;\n expect_count?: number;\n max?: number;\n scope?: RulingScope;\n /** Whose user scope (with scope user): another subject's, for an operator. */\n scope_id?: string;\n}\n\n/** The counts of a rule call's answer that the sequence reads. */\nexport interface RulingCounts {\n dry_run: boolean;\n ruling_id?: string;\n /** What the selection matches that the caller may read; expect_count repeats it. */\n matched: number;\n /** The part this call considers: at most RULING_CHUNK, first in queue order. */\n selected: number;\n /** Of `selected`, the ones the caller may not rule on. */\n skipped: number;\n to_rule: number;\n ruled: number;\n failed: number;\n items?: RulingItem[] | null;\n}\n\nexport interface RulingApi<F, R extends RulingCounts> {\n rule(req: RulingRequest<F>): Promise<R>;\n}\n\nexport interface RulingSelection<F> {\n action: RulingAction;\n ids?: string[];\n filter?: F;\n reason?: string;\n scope?: RulingScope;\n /** Whose user documents, with scope user: the subject a viewer is browsing.\n * Every call of the ruling carries it. */\n scopeId?: string;\n}\n\n/** Why a reviewer is asked to confirm: the first dry run, a dry run after the\n * queue changed under the ruling (`queue_changed`), or one that found more\n * than was confirmed while ruling in chunks. */\nexport type ConfirmReason = \"first\" | \"queue_changed\" | \"grew\";\n\nexport interface RulingProgress {\n ruled: number;\n failed: number;\n /** What the reviewer confirmed: the dry run's match count. */\n total: number;\n chunks: number;\n}\n\nexport interface RulingOutcome {\n /** Each call that ruled made one ruling; undoing the whole ruling reverts each. */\n rulingIds: string[];\n ruled: number;\n failed: number;\n /** The last dry run's count of statements the caller may not rule on. */\n skipped: number;\n /** What the reviewer confirmed (0 when nothing matched). */\n total: number;\n /** The reviewer declined a confirm. */\n cancelled: boolean;\n /** The statements that did not take the ruling, with the runtime's reason. */\n failures: RulingItem[];\n /** A call failed part way; whatever was ruled before it is in rulingIds. */\n error?: unknown;\n}\n\nexport interface RulingHooks<R> {\n /** Asked with each dry run the reviewer has not seen yet; false stops. Omitted\n * (a single row, a hand-picked selection), nothing is asked. */\n confirm?: (dry: R, why: ConfirmReason) => Promise<boolean>;\n onProgress?: (p: RulingProgress) => void;\n}\n\n/** isQueueChanged recognizes the refusal of a real call whose expect_count no\n * longer matches. Read off the error's `code`, which both @loomcycle/client's\n * errors and a host's own carry. */\nexport function isQueueChanged(e: unknown): boolean {\n return !!e && typeof e === \"object\" && (e as { code?: unknown }).code === \"queue_changed\";\n}\n\n/** runRuling rules a selection: ALWAYS a dry run first (the confirm sees its\n * count and sample), then each real call carries that dry run's count as\n * expect_count. Over RULING_CHUNK matches it rules in chunks — dry run, rule,\n * dry run — until the selection is ruled, a chunk rules nothing (what is left\n * cannot be ruled by this caller), or the reviewer stops.\n *\n * A queue that changed between a dry run and its ruling (queue_changed) is\n * dry-run again and confirmed again. So is one that grew past what was\n * confirmed while chunking: \"all matching\" means what the reviewer saw. */\nexport async function runRuling<F, R extends RulingCounts>(\n api: RulingApi<F, R>,\n sel: RulingSelection<F>,\n hooks: RulingHooks<R> = {},\n): Promise<RulingOutcome> {\n const base: Omit<RulingRequest<F>, \"dry_run\"> = {\n action: sel.action,\n ...(sel.ids ? { ids: sel.ids } : { filter: sel.filter ?? ({} as F) }),\n ...(sel.reason ? { reason: sel.reason } : {}),\n ...(sel.scope && sel.scope !== \"tenant\" ? { scope: sel.scope } : {}),\n ...(sel.scope === \"user\" && sel.scopeId ? { scope_id: sel.scopeId } : {}),\n };\n const out: RulingOutcome = { rulingIds: [], ruled: 0, failed: 0, skipped: 0, total: 0, cancelled: false, failures: [] };\n const dryRun = async () => {\n const d = await api.rule({ ...base, dry_run: true });\n out.skipped = d.skipped;\n return d;\n };\n const confirm = async (d: R, why: ConfirmReason) => {\n if (!hooks.confirm || (await hooks.confirm(d, why))) {\n out.total = out.ruled + d.matched;\n return true;\n }\n out.cancelled = true;\n return false;\n };\n\n let dry: R;\n try {\n dry = await dryRun();\n } catch (e) {\n out.error = e;\n return out;\n }\n if (dry.matched === 0 || !(await confirm(dry, \"first\"))) return out;\n\n let retries = 0;\n for (let chunk = 0; chunk < MAX_CHUNKS; chunk++) {\n if (dry.to_rule === 0) break;\n let res: R;\n try {\n res = await api.rule({ ...base, dry_run: false, expect_count: dry.matched });\n } catch (e) {\n if (!isQueueChanged(e) || retries >= QUEUE_CHANGED_RETRIES) {\n out.error = e;\n return out;\n }\n retries++;\n try {\n dry = await dryRun();\n } catch (e2) {\n out.error = e2;\n return out;\n }\n if (dry.matched === 0 || !(await confirm(dry, \"queue_changed\"))) return out;\n continue;\n }\n if (res.ruling_id) out.rulingIds.push(res.ruling_id);\n out.ruled += res.ruled;\n out.failed += res.failed;\n for (const it of res.items ?? []) if (it.error) out.failures.push(it);\n hooks.onProgress?.({ ruled: out.ruled, failed: out.failed, total: out.total, chunks: out.rulingIds.length });\n // Everything the selection matched was in this call's window, or the call\n // ruled nothing: what is left is not this caller's to rule.\n if (res.ruled === 0 || res.matched <= res.selected) break;\n try {\n dry = await dryRun();\n } catch (e) {\n out.error = e;\n return out;\n }\n if (dry.matched === 0) break;\n if (dry.matched > out.total - out.ruled && !(await confirm(dry, \"grew\"))) return out;\n }\n return out;\n}\n\nexport interface UndoOutcome {\n reverted: number;\n changed: number;\n /** Rulings the runtime could not undo (not found, refused), with why. */\n errors: string[];\n}\n\n/** undoRulings reverts each ruling of a bulk ruling, newest first, and adds up\n * what came back. One ruling failing does not stop the others. */\nexport async function undoRulings(\n revert: (rulingId: string) => Promise<{ reverted: number; changed: number }>,\n rulingIds: string[],\n): Promise<UndoOutcome> {\n const out: UndoOutcome = { reverted: 0, changed: 0, errors: [] };\n for (const id of [...rulingIds].reverse()) {\n try {\n const r = await revert(id);\n out.reverted += r.reverted;\n out.changed += r.changed;\n } catch (e) {\n out.errors.push(e instanceof Error ? e.message : String(e));\n }\n }\n return out;\n}\n\n/** chunkCount is how many calls a confirmed ruling of `matched` takes. */\nexport function chunkCount(matched: number): number {\n return Math.max(1, Math.ceil(matched / RULING_CHUNK));\n}\n","// RFC FS — ruling on one document's proposals at once, from the document viewer.\n// The sequence is runRuling's (dry run first, expect_count, chunks); what is\n// here is which documents it is offered for and what it selects.\n\nimport type { BrowseScope, DocEdge, DocScope } from \"../types\";\nimport type { DocRulingAnswer, DocRulingFilter, ExplorerDataLayer } from \"./dataLayer\";\nimport { isProposed } from \"./statement\";\nimport { runRuling, type RulingAction, type RulingHooks, type RulingOutcome, type RulingScope } from \"./ruling\";\n\n// reviewScopeFor is the review scope a document's bulk ruling acts in, or\n// undefined for an agent-scope document, which the review routes do not reach.\n// A user document is reviewed in the scope of the subject being browsed\n// (ruleDocumentProposals sends it as scope_id); the runtime decides whether\n// the caller may name that subject.\nexport function reviewScopeFor(scope: DocScope): RulingScope | undefined {\n return scope === \"tenant\" || scope === \"user\" ? scope : undefined;\n}\n\n// bulkReviewScope is where the document viewer offers bulk review: the review\n// scope, when the data layer can rule in bulk (documentRuleStatements is\n// optional — a custom data layer without it gets no bulk action) and the review\n// routes reach the document.\nexport function bulkReviewScope(\n data: Pick<ExplorerDataLayer, \"documentRuleStatements\">,\n scope: DocScope,\n): RulingScope | undefined {\n return data.documentRuleStatements ? reviewScopeFor(scope) : undefined;\n}\n\n// documentProposals is the document's own proposals among its edges: those\n// filed from it, which is what from_document_id selects on the server.\nexport function documentProposals(edges: DocEdge[], documentId: string): DocEdge[] {\n return edges.filter((e) => isProposed(e) && !!e.id && e.from_document_id === documentId);\n}\n\n// ReviewPanel is what the Connections panel needs to offer bulk review.\nexport interface ReviewPanel {\n proposals: DocEdge[];\n scope: RulingScope;\n // The edge list stopped at its page cap: proposals past it are not listed.\n incomplete: boolean;\n onChanged: () => void;\n}\n\n// reviewPanel decides whether the Connections panel shows bulk review: wherever\n// it can rule (scope), even with nothing listed. Hiding it at zero unmounted it\n// the moment a ruling took the document's last proposal, and with it the\n// ruling's result and its Undo.\nexport function reviewPanel(\n scope: RulingScope | undefined,\n proposals: DocEdge[],\n incomplete: boolean,\n onChanged: () => void,\n): ReviewPanel | undefined {\n return scope ? { proposals, scope, incomplete, onChanged } : undefined;\n}\n\nexport interface DocumentRuling {\n documentId: string;\n action: RulingAction;\n // The statements picked by hand; empty or absent rules every proposal filed\n // from the document.\n ids?: string[];\n reason?: string;\n scope: RulingScope;\n browse?: BrowseScope;\n}\n\n// ruleDocumentProposals rules a document's proposals through the data layer's\n// bulk ruling. Rejects when the data layer has none.\nexport function ruleDocumentProposals(\n data: ExplorerDataLayer,\n r: DocumentRuling,\n hooks?: RulingHooks<DocRulingAnswer>,\n): Promise<RulingOutcome> {\n if (!data.documentRuleStatements) {\n return Promise.reject(new Error(\"this data layer cannot rule in bulk\"));\n }\n return runRuling<DocRulingFilter, DocRulingAnswer>(\n // Called through `data` so a class-based data layer keeps `this`.\n { rule: (req) => data.documentRuleStatements!(req, r.browse) },\n {\n action: r.action,\n ...(r.ids && r.ids.length > 0 ? { ids: r.ids } : { filter: { from_document_id: r.documentId } }),\n ...(r.reason ? { reason: r.reason } : {}),\n scope: r.scope,\n // The browsed subject's user documents: the review routes take it as\n // scope_id, as the document reads take it as browse.scopeId.\n ...(r.scope === \"user\" && r.browse?.scopeId ? { scopeId: r.browse.scopeId } : {}),\n },\n hooks,\n );\n}\n\n// rulingNote is the one line a ruling leaves in the panel.\nexport function rulingNote(action: RulingAction, o: RulingOutcome): string {\n const n = (x: number) => x.toLocaleString(\"en-US\");\n const parts = [`${action === \"accept\" ? \"Accepted\" : \"Rejected\"} ${n(o.ruled)} statement${o.ruled === 1 ? \"\" : \"s\"}`];\n if (o.failed > 0) parts.push(`${n(o.failed)} did not take the ruling`);\n if (o.skipped > 0) parts.push(`${n(o.skipped)} skipped: not yours to rule`);\n return parts.join(\"; \") + \".\";\n}\n","import type { CSSProperties } from \"react\";\n\n// RFC BN per-document color schemes. A document can tint its chunk tiles and its\n// Path-tree row by (document type, state) and (chunk state), so a reader scanning\n// the tree sees kind + progress at a glance. A scheme is a flat map of semantic\n// keys → CSS hex colors, stored in the document's ROOT chunk fields (color_scheme)\n// alongside a color_enabled flag; the backend stores/returns it verbatim and this\n// module is the only place that interprets it.\n\n// ColorScheme maps a semantic key to a CSS hex color. Keys:\n// doc.<type>.<status> — a document tile/row by its ROOT chunk's type + status\n// doc.<type> — fallback for any status of that document type\n// doc.*.<status> — fallback for a type the scheme does not name, by status\n// doc.* — fallback for a type the scheme does not name, any status\n// chunk.<status> — a chunk tile by its own status\n// chunk.inherit — \"false\" (or \"none\" / \"off\") keeps a chunk without a\n// status colour neutral; by default it takes a lighter\n// wash of its document's colour\n// Unknown keys are ignored; a missing key → no tint (neutral). Keys match a type\n// or status ignoring case, so an ontology class type (`Rfc`) finds `doc.rfc.*`.\nexport type ColorScheme = Record<string, string>;\n\n// DocSummary is one row of the document `documents_summary` op (Path-tree color).\nexport interface DocSummary {\n document_id: string;\n title: string;\n root_chunk_id?: string;\n type?: string;\n status?: string;\n color_enabled: boolean;\n color_scheme?: ColorScheme;\n // brief — the document's annotation brief, present only when the document\n // has an annotation (tenant scope). The Path tree shows it under the name.\n brief?: string;\n}\n\n// DocumentMeta is the enriched get_document result (the viewer's own document).\nexport interface DocumentMeta {\n document_id: string;\n title: string;\n root_chunk_id?: string;\n type?: string;\n status?: string;\n color_enabled: boolean;\n color_scheme?: ColorScheme;\n}\n\n// DEFAULT_SCHEME seeds a new document's palette. The hexes are mid-tone so the\n// low-alpha wash reads on BOTH the dark and light explorer themes; the scheme\n// editor starts from this, and the resolver falls back to it when a document has\n// color_enabled but no stored scheme yet.\nexport const DEFAULT_SCHEME: ColorScheme = {\n \"doc.rfc.draft\": \"#c99a3a\",\n \"doc.rfc.review\": \"#6a7bd6\",\n \"doc.rfc.confirmed\": \"#3a9ad6\",\n \"doc.rfc.done\": \"#3aa06a\",\n // plan documents share the RFC lifecycle vocabulary (draft→review→confirmed→done).\n \"doc.plan.draft\": \"#c99a3a\",\n \"doc.plan.review\": \"#6a7bd6\",\n \"doc.plan.confirmed\": \"#3a9ad6\",\n \"doc.plan.done\": \"#3aa06a\",\n \"doc.document.done\": \"#3aa06a\",\n \"doc.research.done\": \"#8a6ad6\",\n \"doc.publication.draft\": \"#c99a3a\",\n // Any other type — an ontology class (Guide, Benchmark, …) or one added later —\n // is coloured by its status alone, so retyping a document never blanks it.\n \"doc.*.draft\": \"#c99a3a\",\n \"doc.*.review\": \"#6a7bd6\",\n \"doc.*.confirmed\": \"#3a9ad6\",\n \"doc.*.done\": \"#3aa06a\",\n \"chunk.draft\": \"#c99a3a\",\n \"chunk.review\": \"#6a7bd6\",\n \"chunk.confirmed\": \"#3a9ad6\",\n \"chunk.done\": \"#3aa06a\",\n // PR-workflow chunk statuses (a plan document's PR chunks): queued → active → done.\n \"chunk.backlog\": \"#8a8f98\",\n \"chunk.implementation\": \"#d1863a\",\n \"chunk.merged\": \"#3aa06a\",\n};\n\n// TINT_ALPHA washes every scheme color into a tile background — a tint, not a\n// fill — so the row text stays readable (the loomcycle tinted-tile pattern).\nconst TINT_ALPHA = 0.16;\n\n// effectiveScheme is what the resolvers read: the stored scheme if present, else\n// the defaults (so color_enabled alone gives a sensible palette before any edit).\nexport function effectiveScheme(scheme: ColorScheme | undefined): ColorScheme {\n return scheme && Object.keys(scheme).length > 0 ? scheme : DEFAULT_SCHEME;\n}\n\n// lookup reads one scheme key: exactly, else ignoring case. Types are written\n// both ways — the built-in lowercase `rfc` and an ontology's class name `Rfc` —\n// and a document retyped from one to the other must keep its colour.\nfunction lookup(scheme: ColorScheme, key: string): string | undefined {\n if (Object.prototype.hasOwnProperty.call(scheme, key) && scheme[key]) return scheme[key];\n const want = key.toLowerCase();\n for (const k of Object.keys(scheme)) {\n if (k.toLowerCase() === want && scheme[k]) return scheme[k];\n }\n return undefined;\n}\n\n// docColor resolves a document's raw tile color from its (type,status): tries\n// doc.<type>.<status>, then doc.<type>, then the any-type keys doc.*.<status> and\n// doc.*. Returns undefined for no match.\nexport function docColor(\n type: string | undefined,\n status: string | undefined,\n scheme: ColorScheme,\n): string | undefined {\n const t = type ?? \"\";\n const s = status ?? \"\";\n return (\n (t && s ? lookup(scheme, `doc.${t}.${s}`) : undefined) ??\n (t ? lookup(scheme, `doc.${t}`) : undefined) ??\n (s ? lookup(scheme, `doc.*.${s}`) : undefined) ??\n lookup(scheme, \"doc.*\")\n );\n}\n\n// chunkColor resolves a chunk tile's raw color from its status (chunk.<status>).\nexport function chunkColor(status: string | undefined, scheme: ColorScheme): string | undefined {\n const s = status ?? \"\";\n return s ? lookup(scheme, `chunk.${s}`) : undefined;\n}\n\n// chunkInheritsDocColor reports whether a chunk with no colour of its own takes\n// its document's colour. Corpus chunks (sections of a law, of a regulation)\n// carry no status, and should not get a placeholder one just to be coloured —\n// status is a meaningful field that search filters on — so by default they wear\n// their document's colour; `chunk.inherit: \"false\"` turns that off.\nexport function chunkInheritsDocColor(scheme: ColorScheme): boolean {\n const v = String(scheme[\"chunk.inherit\"] ?? \"\")\n .trim()\n .toLowerCase();\n return !(v === \"false\" || v === \"none\" || v === \"off\" || v === \"0\");\n}\n\n// hexToTint converts a #rgb / #rrggbb color to an rgba() wash at alpha\n// (TINT_ALPHA by default); undefined for a value it can't parse (→ no tint).\nexport function hexToTint(hex: string, alpha: number = TINT_ALPHA): string | undefined {\n const m = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(hex.trim());\n if (!m) return undefined;\n let h = m[1];\n if (h.length === 3) h = h[0] + h[0] + h[1] + h[1] + h[2] + h[2];\n const r = parseInt(h.slice(0, 2), 16);\n const g = parseInt(h.slice(2, 4), 16);\n const b = parseInt(h.slice(4, 6), 16);\n return `rgba(${r}, ${g}, ${b}, ${alpha})`;\n}\n\n// tintStyle is the inline style for a tinted row/tile: a low-alpha wash\n// background + a full-color left accent. undefined (→ no style) when the color is\n// absent or unparseable, so a caller spreads it unconditionally.\nexport function tintStyle(color: string | undefined): CSSProperties | undefined {\n if (!color) return undefined;\n const bg = hexToTint(color);\n if (!bg) return undefined;\n return { background: bg, borderLeft: `3px solid ${color}` };\n}\n\n// washStyle is the lighter tint a chunk inherits from its document: half the\n// wash and no left accent, so a chunk with a status colour of its own (a\n// passport block's pass / fail) still stands out among its neighbours.\nexport function washStyle(color: string | undefined): CSSProperties | undefined {\n if (!color) return undefined;\n const bg = hexToTint(color, TINT_ALPHA / 2);\n return bg ? { background: bg } : undefined;\n}\n\n// chunkRowStyle is a chunk-tree row's tint. The document's own row (its root\n// chunk) wears the document's colour, as its Path-tree row does; any other\n// chunk its status colour (chunk.<status>), else — unless the scheme turns it\n// off — a lighter wash of the document's colour. scheme null = colouring off.\nexport function chunkRowStyle(opts: {\n status: string | undefined;\n isRoot: boolean;\n documentColor: string | undefined;\n scheme: ColorScheme | null;\n}): CSSProperties | undefined {\n const { status, isRoot, documentColor, scheme } = opts;\n if (!scheme) return undefined;\n if (isRoot) return tintStyle(documentColor) ?? tintStyle(chunkColor(status, scheme));\n return tintStyle(chunkColor(status, scheme)) ?? (chunkInheritsDocColor(scheme) ? washStyle(documentColor) : undefined);\n}\n\n","// copyToClipboard writes text to the system clipboard and returns whether it\n// succeeded. It is a standalone helper (not inlined in the button) so the copy\n// affordance's success/failure branch is unit-testable without a DOM — the UI\n// only needs the boolean. It guards a missing clipboard (an insecure context, an\n// old browser, or a non-browser test env) by returning false rather than\n// throwing, so a copy button can never crash the viewer.\nexport async function copyToClipboard(text: string): Promise<boolean> {\n try {\n if (typeof navigator === \"undefined\" || !navigator.clipboard) return false;\n await navigator.clipboard.writeText(text);\n return true;\n } catch {\n return false;\n }\n}\n","import { useState, type MouseEvent } from \"react\";\nimport { copyToClipboard } from \"../lib/clipboard\";\n\nexport interface IdCopyProps {\n // value is the exact id copied to the clipboard (a document id or a chunk id).\n value: string;\n // label is a short prefix shown before the id in full mode (e.g. \"doc\", \"chunk\").\n label?: string;\n // compact renders the copy glyph ONLY (no visible id text) for dense rows like\n // the chunk tree; the id still rides in the button's title/aria-label.\n compact?: boolean;\n // title overrides the button tooltip (default: `Copy <label>: <value>`).\n title?: string;\n}\n\n// IdCopy surfaces an id with a click-to-copy button. It exists so an operator\n// wiring a document or a specific chunk into an external workflow — n8n over the\n// MCP/HTTP API — can grab the EXACT id the API expects, which the viewer\n// otherwise only uses internally as React keys. The clipboard always receives\n// the full id even when the on-screen value is ellipsized.\nexport default function IdCopy({ value, label, compact, title }: IdCopyProps) {\n const [state, setState] = useState<\"idle\" | \"copied\" | \"error\">(\"idle\");\n\n const copy = async (e: MouseEvent) => {\n // Never let the copy click bubble to the row/tile's own handler (which would\n // select the chunk or toggle the tree).\n e.stopPropagation();\n e.preventDefault();\n const ok = await copyToClipboard(value);\n setState(ok ? \"copied\" : \"error\");\n window.setTimeout(() => setState(\"idle\"), ok ? 1200 : 1500);\n };\n\n const glyph = state === \"copied\" ? \"✓\" : state === \"error\" ? \"✗\" : \"⎘\";\n const btnTitle = title ?? `Copy ${label ?? \"id\"}: ${value}`;\n const button = (\n <button\n type=\"button\"\n className={`id-copy-btn id-copy-${state}`}\n onClick={copy}\n title={btnTitle}\n aria-label={btnTitle}\n >\n {glyph}\n </button>\n );\n\n if (compact) return button;\n\n return (\n <span className=\"id-copy\">\n {label && <span className=\"id-copy-label\">{label}</span>}\n <code className=\"id-copy-value\" title={value}>\n {value}\n </code>\n {button}\n </span>\n );\n}\n","import { useCallback, useEffect, useState } from \"react\";\nimport type { ChunkRow } from \"../types\";\nimport { chunkRowStyle, effectiveScheme, type ColorScheme } from \"../lib/colorScheme\";\nimport IdCopy from \"./IdCopy\";\n\n// DocumentChunkTree renders a document's chunk hierarchy (RFC AK), built from\n// the flat query_chunks list by parent_id + position. A single expand Map owned\n// by the tree, default-expanded, click-to-select.\n\nexport interface ChunkNode {\n row: ChunkRow;\n children: ChunkNode[];\n}\n\n// buildChunkTree groups chunks into parent → children (position-ordered). A\n// chunk whose parent_id is absent or not in the set is a root (the document's\n// root chunk; defensively also any orphan).\nexport function buildChunkTree(chunks: ChunkRow[]): ChunkNode[] {\n const byId = new Map<string, ChunkNode>();\n chunks.forEach((c) => byId.set(c.id, { row: c, children: [] }));\n const roots: ChunkNode[] = [];\n chunks.forEach((c) => {\n const node = byId.get(c.id)!;\n if (c.parent_id && byId.has(c.parent_id)) byId.get(c.parent_id)!.children.push(node);\n else roots.push(node);\n });\n const sortRec = (nodes: ChunkNode[]) => {\n nodes.sort((a, b) => a.row.position - b.row.position);\n nodes.forEach((n) => sortRec(n.children));\n };\n sortRec(roots);\n return roots;\n}\n\n// typeIcon returns a small glyph for a media chunk type (RFC BO) so the tree\n// distinguishes image / diagram chunks at a glance; \"\" for a plain text chunk.\nfunction typeIcon(type: string | undefined): string {\n if (type === \"image\") return \"🖼\";\n if (type === \"mermaid\") return \"📊\";\n return \"\";\n}\n\n// findChunkNode locates a node by id within a chunk forest.\nexport function findChunkNode(nodes: ChunkNode[], id: string): ChunkNode | undefined {\n for (const n of nodes) {\n if (n.row.id === id) return n;\n const hit = findChunkNode(n.children, id);\n if (hit) return hit;\n }\n return undefined;\n}\n\nexport interface DocumentChunkTreeProps {\n tree: ChunkNode[];\n selectedId?: string;\n onSelect: (node: ChunkNode) => void;\n // RFC BN: when colorEnabled, chunk rows are tinted by status via `scheme`\n // (falls back to the default palette). Unset → neutral rows (prior behavior).\n colorEnabled?: boolean;\n scheme?: ColorScheme;\n // The document's own colour (docColor of its type + status). Its row at the\n // top of the tree wears it, and a chunk with no status colour of its own a\n // lighter wash of it (chunkRowStyle). Unset → status colours only.\n documentColor?: string;\n // RFC BN P4: chunk ids that have at least one cross-reference edge — those\n // tiles get a 🔗 badge. Unset → no badges.\n linkedIds?: Set<string>;\n}\n\nexport default function DocumentChunkTree({\n tree,\n selectedId,\n onSelect,\n colorEnabled,\n scheme,\n documentColor,\n linkedIds,\n}: DocumentChunkTreeProps) {\n const [expanded, setExpanded] = useState<Map<string, boolean>>(() => new Map());\n const toggle = useCallback((id: string) => {\n setExpanded((prev) => {\n const next = new Map(prev);\n next.set(id, prev.get(id) === false ? true : false);\n return next;\n });\n }, []);\n\n // Auto-expand ancestors of the selection.\n useEffect(() => {\n if (!selectedId) return;\n const parents = ancestorIds(tree, selectedId);\n if (parents.length === 0) return;\n setExpanded((prev) => {\n let mutated = false;\n const next = new Map(prev);\n for (const id of parents) {\n if (next.get(id) === false) {\n next.set(id, true);\n mutated = true;\n }\n }\n return mutated ? next : prev;\n });\n }, [tree, selectedId]);\n\n // Resolve the palette once (null → no tinting) and thread it down.\n const tintScheme = colorEnabled ? effectiveScheme(scheme) : null;\n\n if (tree.length === 0) {\n return (\n <div className=\"empty\">\n <p>No chunks.</p>\n </div>\n );\n }\n return (\n <ul className=\"tree chunk-tree\">\n {tree.map((n) => (\n <ChunkTreeNode\n key={n.row.id}\n node={n}\n expanded={expanded}\n toggle={toggle}\n selectedId={selectedId}\n onSelect={onSelect}\n tintScheme={tintScheme}\n documentColor={documentColor}\n isRoot\n linkedIds={linkedIds}\n />\n ))}\n </ul>\n );\n}\n\nfunction ancestorIds(roots: ChunkNode[], id: string): string[] {\n const path: string[] = [];\n const walk = (nodes: ChunkNode[], parents: string[]): boolean => {\n for (const n of nodes) {\n if (n.row.id === id) {\n path.push(...parents);\n return true;\n }\n if (walk(n.children, [...parents, n.row.id])) return true;\n }\n return false;\n };\n walk(roots, []);\n return path;\n}\n\ninterface NodeProps {\n node: ChunkNode;\n expanded: Map<string, boolean>;\n toggle: (id: string) => void;\n selectedId?: string;\n onSelect: (node: ChunkNode) => void;\n tintScheme: ColorScheme | null;\n documentColor?: string;\n // A top-level node: the document's root chunk, i.e. the document itself.\n isRoot?: boolean;\n linkedIds?: Set<string>;\n}\n\nfunction ChunkTreeNode({\n node,\n expanded,\n toggle,\n selectedId,\n onSelect,\n tintScheme,\n documentColor,\n isRoot = false,\n linkedIds,\n}: NodeProps) {\n const hasChildren = node.children.length > 0;\n const isOpen = expanded.get(node.row.id) !== false; // default-expanded\n const isSelected = selectedId === node.row.id;\n const rowStyle = chunkRowStyle({ status: node.row.status, isRoot, documentColor, scheme: tintScheme });\n const hasLink = linkedIds?.has(node.row.id);\n return (\n <li className={`node chunk-node ${isSelected ? \"selected\" : \"\"}`}>\n <div className=\"row chunk-row\" style={rowStyle}>\n <button\n type=\"button\"\n className=\"tree-caret\"\n aria-label={isOpen ? \"collapse\" : \"expand\"}\n disabled={!hasChildren}\n onClick={(e) => {\n e.stopPropagation();\n if (hasChildren) toggle(node.row.id);\n }}\n >\n {hasChildren ? (isOpen ? \"▼\" : \"▶\") : \"·\"}\n </button>\n <button\n type=\"button\"\n className=\"chunk-link\"\n onClick={() => onSelect(node)}\n title={node.row.title}\n >\n {typeIcon(node.row.type) && (\n <span className=\"chunk-type-icon\" aria-hidden>\n {typeIcon(node.row.type)}\n </span>\n )}\n <span className=\"chunk-title\">{node.row.title || \"(untitled)\"}</span>\n {node.row.type && <span className=\"chunk-badge\">{node.row.type}</span>}\n {node.row.status && <span className=\"chunk-badge chunk-status\">{node.row.status}</span>}\n {hasLink && (\n <span className=\"chunk-link-badge\" title=\"Has cross-reference links\" aria-label=\"linked\">\n 🔗\n </span>\n )}\n </button>\n {/* Per-chunk copy id — a sibling of the tile button (not nested, which\n would be invalid), so any chunk's id can be grabbed for an external\n workflow without selecting it first. */}\n <IdCopy value={node.row.id} compact title={`Copy chunk id: ${node.row.id}`} />\n </div>\n {hasChildren && isOpen && (\n <ul className=\"children chunk-children\">\n {node.children.map((c) => (\n <ChunkTreeNode\n key={c.row.id}\n node={c}\n expanded={expanded}\n toggle={toggle}\n selectedId={selectedId}\n onSelect={onSelect}\n tintScheme={tintScheme}\n documentColor={documentColor}\n linkedIds={linkedIds}\n />\n ))}\n </ul>\n )}\n </li>\n );\n}\n","import { useState } from \"react\";\nimport type { Annotation, AnnotationLevel } from \"../types\";\nimport {\n ABSTRACT_MAX_CHARS,\n BRIEF_MAX_CHARS,\n annotationDraftProblem,\n codePoints,\n writtenAtLabel,\n writtenByLabel,\n} from \"../lib/annotation\";\n\n// AnnotationBrief is the one-line brief shown under a title. A stale record is\n// still shown, with a muted marker, so the reader can weigh it.\nexport function AnnotationBrief({ record }: { record?: Annotation }) {\n if (!record) return null;\n return (\n <p className=\"annotation-brief\" title=\"Annotation brief\">\n {record.brief}\n {record.stale && <StaleBadge />}\n </p>\n );\n}\n\nfunction StaleBadge() {\n return (\n <span\n className=\"annotation-badge annotation-stale\"\n title=\"The text has changed since this annotation was written\"\n >\n stale\n </span>\n );\n}\n\nexport interface AnnotationPanelProps {\n // The records of one chunk, ordered branch → document → path. Empty → the\n // panel draws only for a reader who can write or regenerate one.\n records: Annotation[];\n // newLevel is the level a hand-written annotation takes when there is none.\n newLevel: AnnotationLevel;\n // onSave writes an edit (always as a manual record); absent → no Edit.\n onSave?: (level: AnnotationLevel, brief: string, abstract: string) => Promise<void>;\n // onRegenerate asks the host to have the annotation rewritten; absent → no\n // Regenerate.\n onRegenerate?: (level: AnnotationLevel) => Promise<void>;\n // Starts expanded (tests and a host that wants the abstract open).\n defaultOpen?: boolean;\n}\n\n// AnnotationPanel shows a chunk's abstract and its provenance — level, language,\n// model, when and by whom it was written, whether a person wrote it, whether it\n// is stale — collapsed under one summary line. The abstract is rendered as plain\n// text: it is model output, never markup.\nexport default function AnnotationPanel({\n records,\n newLevel,\n onSave,\n onRegenerate,\n defaultOpen,\n}: AnnotationPanelProps) {\n const [open, setOpen] = useState(!!defaultOpen);\n const [editing, setEditing] = useState<AnnotationLevel | null>(null);\n // The record being regenerated: every button waits, only its own says so.\n const [busyLevel, setBusyLevel] = useState<AnnotationLevel | null>(null);\n const busy = busyLevel !== null;\n const [err, setErr] = useState<string | null>(null);\n\n if (records.length === 0 && !onSave && !onRegenerate) return null;\n\n const regenerate = async (level: AnnotationLevel) => {\n if (!onRegenerate) return;\n setBusyLevel(level);\n setErr(null);\n try {\n await onRegenerate(level);\n } catch (e) {\n setErr(e instanceof Error ? e.message : String(e));\n } finally {\n setBusyLevel(null);\n }\n };\n\n const anyStale = records.some((r) => r.stale);\n const anyManual = records.some((r) => r.manual);\n\n return (\n <details\n className=\"annotation-panel\"\n open={open || editing !== null}\n onToggle={(e) => setOpen(e.currentTarget.open)}\n >\n <summary>\n <span className=\"annotation-title\">Annotation</span>\n {records.length === 0 ? (\n <span className=\"annotation-none\">none</span>\n ) : (\n records.map((r) => (\n <span className=\"annotation-badge\" key={r.level}>\n {r.level}\n </span>\n ))\n )}\n {anyManual && (\n <span className=\"annotation-badge annotation-manual\" title=\"Written or edited by a person\">\n manual\n </span>\n )}\n {anyStale && <StaleBadge />}\n </summary>\n {records.map((r) =>\n editing === r.level ? (\n <AnnotationEditor\n key={r.level}\n level={r.level}\n brief={r.brief}\n abstract={r.abstract}\n onCancel={() => setEditing(null)}\n onSave={async (b, a) => {\n await onSave!(r.level, b, a);\n setEditing(null);\n }}\n />\n ) : (\n <div className=\"annotation-record\" key={r.level}>\n {records.length > 1 && <p className=\"annotation-brief\">{r.brief}</p>}\n {r.abstract && <p className=\"annotation-abstract\">{r.abstract}</p>}\n <dl className=\"annotation-meta\">\n <dt>level</dt>\n <dd>{r.level}</dd>\n {r.language && (\n <>\n <dt>language</dt>\n <dd>{r.language}</dd>\n </>\n )}\n {r.model && (\n <>\n <dt>model</dt>\n <dd>{r.model}</dd>\n </>\n )}\n {r.written_at && (\n <>\n <dt>written</dt>\n <dd title={r.written_at}>{writtenAtLabel(r.written_at)}</dd>\n </>\n )}\n {r.written_by && (\n <>\n <dt>by</dt>\n <dd>{writtenByLabel(r.written_by)}</dd>\n </>\n )}\n {r.manual && (\n <>\n <dt>source</dt>\n <dd>written by hand</dd>\n </>\n )}\n {r.stale && (\n <>\n <dt>state</dt>\n <dd>stale: the text changed after this was written</dd>\n </>\n )}\n </dl>\n {(onSave || onRegenerate) && (\n <div className=\"annotation-actions\">\n {onSave && (\n <button type=\"button\" disabled={busy} onClick={() => setEditing(r.level)}>\n edit\n </button>\n )}\n {/* The annotation pass never rewrites a person's text, so a\n Regenerate of one would change nothing: edit it instead. */}\n {onRegenerate && !r.manual && (\n <button\n type=\"button\"\n disabled={busy}\n onClick={() => void regenerate(r.level)}\n title=\"Ask for it to be written again from the current text\"\n >\n {busyLevel === r.level ? \"regenerating…\" : \"regenerate\"}\n </button>\n )}\n </div>\n )}\n </div>\n ),\n )}\n {records.length === 0 &&\n (editing !== null && onSave ? (\n <AnnotationEditor\n level={editing}\n brief=\"\"\n abstract=\"\"\n onCancel={() => setEditing(null)}\n onSave={async (b, a) => {\n await onSave(editing, b, a);\n setEditing(null);\n }}\n />\n ) : (\n <div className=\"annotation-record\">\n <p className=\"annotation-empty\">No annotation has been written for this yet.</p>\n <div className=\"annotation-actions\">\n {onSave && (\n <button type=\"button\" disabled={busy} onClick={() => setEditing(newLevel)}>\n write\n </button>\n )}\n {onRegenerate && (\n <button type=\"button\" disabled={busy} onClick={() => void regenerate(newLevel)}>\n {busy ? \"generating…\" : \"generate\"}\n </button>\n )}\n </div>\n </div>\n ))}\n {err && <p className=\"annotation-err\">{err}</p>}\n </details>\n );\n}\n\n// AnnotationEditor is the inline brief + abstract form. It checks the length\n// caps before sending; a refusal from the runtime is shown under the form.\nfunction AnnotationEditor({\n level,\n brief: initialBrief,\n abstract: initialAbstract,\n onSave,\n onCancel,\n}: {\n level: AnnotationLevel;\n brief: string;\n abstract: string;\n onSave: (brief: string, abstract: string) => Promise<void>;\n onCancel: () => void;\n}) {\n const [brief, setBrief] = useState(initialBrief);\n const [abstract, setAbstract] = useState(initialAbstract);\n const [saving, setSaving] = useState(false);\n const [err, setErr] = useState<string | null>(null);\n const problem = annotationDraftProblem(brief, abstract);\n\n const save = async () => {\n if (problem) {\n setErr(problem);\n return;\n }\n setSaving(true);\n setErr(null);\n try {\n await onSave(brief, abstract);\n } catch (e) {\n setErr(e instanceof Error ? e.message : String(e));\n } finally {\n setSaving(false);\n }\n };\n\n return (\n <form\n className=\"annotation-editor\"\n onSubmit={(e) => {\n e.preventDefault();\n void save();\n }}\n >\n <label>\n <span>\n Brief ({level}) · {codePoints(brief)}/{BRIEF_MAX_CHARS}\n </span>\n <input value={brief} onChange={(e) => setBrief(e.target.value)} placeholder=\"One sentence\" />\n </label>\n <label>\n <span>\n Abstract · {codePoints(abstract)}/{ABSTRACT_MAX_CHARS}\n </span>\n <textarea\n rows={6}\n value={abstract}\n onChange={(e) => setAbstract(e.target.value)}\n placeholder=\"One paragraph\"\n />\n </label>\n <p className=\"annotation-hint\">Saved as written by hand: the background walk will not replace it.</p>\n {err && <p className=\"annotation-err\">{err}</p>}\n <div className=\"annotation-actions\">\n <button type=\"button\" onClick={onCancel} disabled={saving}>\n cancel\n </button>\n <button type=\"submit\" className=\"primary\" disabled={saving || !!problem}>\n {saving ? \"saving…\" : \"save\"}\n </button>\n </div>\n </form>\n );\n}\n","import { useEffect, useRef, useState, type ReactNode } from \"react\";\n\n// MermaidDiagram lazily renders a Mermaid definition to SVG. Theme is read from\n// the nearest [data-theme] ancestor (the explorer root / host <html>), defaulting\n// to the explorer's dark palette. It renders with securityLevel:\"strict\" (bundled\n// DOMPurify) — the same posture as the runtime's TeamsView diagram. mermaid is an\n// OPTIONAL peer dep, so a host without it (or a definition that fails to parse)\n// degrades gracefully to the raw code, and a bad diagram never breaks the view.\n// Shared by the Markdown ```mermaid fence (RFC BN P2) and the cross-reference\n// relationship graph (P4).\n\n// mermaidSeq gives each render a unique DOM id (mermaid.render requires one).\n// A module counter is fine in the browser (this never runs in the workflow JS\n// sandbox where Math.random / new Date are disallowed).\nlet mermaidSeq = 0;\n\n// flowchartNode finds the flowchart node a click landed in and returns the id it\n// was DECLARED with. Mermaid wraps that id in its own (`flowchart-<id>-<n>`,\n// behind the render id in newer versions), so it is matched from the right. A\n// click outside any node — or a diagram that is not a flowchart — is undefined.\nexport function flowchartNode(target: Element | null): string | undefined {\n const node = target?.closest(\"g.node\");\n return node ? /flowchart-(.+)-\\d+$/.exec(node.id)?.[1] : undefined;\n}\n\nexport default function MermaidDiagram({\n code,\n onNodeClick,\n}: {\n code: string;\n // Called with a flowchart node's declared id when it is clicked. Makes the\n // nodes read as clickable; omit for a diagram that is only a picture.\n onNodeClick?: (nodeId: string) => void;\n}): ReactNode {\n const ref = useRef<HTMLDivElement>(null);\n const [state, setState] = useState<{ svg?: string; err?: boolean }>({});\n\n useEffect(() => {\n let cancelled = false;\n (async () => {\n try {\n const mermaid = (await import(\"mermaid\")).default;\n const attr = ref.current?.closest(\"[data-theme]\")?.getAttribute(\"data-theme\");\n const dark = attr ? attr === \"dark\" : true; // explorer default is dark\n mermaid.initialize({ startOnLoad: false, theme: dark ? \"dark\" : \"default\", securityLevel: \"strict\" });\n const { svg } = await mermaid.render(`lc-mmd-${mermaidSeq++}`, code);\n if (!cancelled) setState({ svg });\n } catch {\n if (!cancelled) setState({ err: true });\n }\n })();\n return () => {\n cancelled = true;\n };\n }, [code]);\n\n if (state.err) {\n // No ref here: the effect already captured the theme on the first (loading)\n // render, and a <pre> ref would conflict with the <div> ref type below.\n return (\n <pre className=\"md-pre md-mermaid-error\" title=\"diagram failed to render\">\n <code>{code}</code>\n </pre>\n );\n }\n if (state.svg) {\n return (\n <div\n ref={ref}\n className={onNodeClick ? \"md-mermaid md-mermaid-nav\" : \"md-mermaid\"}\n onClick={\n onNodeClick &&\n ((e) => {\n const id = flowchartNode(e.target as Element);\n if (id) onNodeClick(id);\n })\n }\n dangerouslySetInnerHTML={{ __html: state.svg }}\n />\n );\n }\n return (\n <div ref={ref} className=\"md-mermaid md-mermaid-loading\">\n rendering diagram…\n </div>\n );\n}\n","import { useEffect, useState, type FormEvent } from \"react\";\nimport type { BrowseScope, ChunkDetail, DocScope } from \"../types\";\nimport { useExplorerData } from \"../lib/dataLayer\";\nimport MermaidDiagram from \"./Mermaid\";\nimport { readImageAsBase64 } from \"../lib/imageUpload\";\n\n// ChunkEditorModal edits one chunk's content — title, type, status, Markdown\n// body, and (optional) typed fields as JSON. Save is an optimistic-concurrency\n// update_chunk carrying the chunk's revision; a stale revision returns a\n// \"revision conflict\" the modal surfaces with a reload hint. Structural edits\n// (reparent / reorder / link / delete) are NOT here — those are the\n// document-management agent's job.\nexport interface ChunkEditorModalProps {\n chunk: ChunkDetail;\n scope: DocScope;\n // browse (RFC AS) — edit a chunk under the browsed subject's document, not\n // necessarily the caller's own (server re-authorizes). Unset → own subject.\n browse?: BrowseScope;\n onClose: () => void;\n onSaved: (updated: ChunkDetail) => void;\n}\n\nexport default function ChunkEditorModal({ chunk, scope, browse, onClose, onSaved }: ChunkEditorModalProps) {\n const data = useExplorerData();\n const [title, setTitle] = useState(chunk.title);\n const [type, setType] = useState(chunk.type ?? \"\");\n const [status, setStatus] = useState(chunk.status ?? \"\");\n const [body, setBody] = useState(chunk.body ?? \"\");\n const [fieldsText, setFieldsText] = useState(\n chunk.fields ? JSON.stringify(chunk.fields, null, 2) : \"\",\n );\n // Tags (RFC BS) edit as a comma-separated list; the editor is authoritative, so\n // save always replace-sets to this value (empty clears). Nested tags use a slash.\n const [tagsText, setTagsText] = useState((chunk.tags ?? []).join(\", \"));\n const [busy, setBusy] = useState(false);\n const [err, setErr] = useState<string | null>(null);\n const [conflict, setConflict] = useState(false);\n\n const isMermaid = type === \"mermaid\";\n const isImage = type === \"image\" || !!chunk.asset;\n\n // RFC BO — a debounced copy of the body drives the live Mermaid preview so it\n // re-renders as the author edits the source, but not on every keystroke.\n const [preview, setPreview] = useState(body);\n useEffect(() => {\n if (!isMermaid) return;\n const t = setTimeout(() => setPreview(body), 400);\n return () => clearTimeout(t);\n }, [body, isMermaid]);\n\n // RFC BO — replace an image chunk's bytes in place (set_asset bumps the\n // revision, so we hand the updated chunk back and close rather than risk a\n // stale-revision save afterward).\n const replaceImage = async (file: File) => {\n setErr(null);\n setBusy(true);\n try {\n const { mediaType, data: b64 } = await readImageAsBase64(file);\n const updated = await data.documentSetAsset(chunk.id, mediaType, b64, file.name, scope, browse);\n onSaved(updated);\n onClose();\n } catch (ex) {\n setErr(ex instanceof Error ? ex.message : String(ex));\n setBusy(false);\n }\n };\n\n const bodyLabel = isMermaid ? \"Mermaid source\" : isImage ? \"Caption (optional)\" : \"Body (Markdown)\";\n\n const submit = async (e: FormEvent) => {\n e.preventDefault();\n setErr(null);\n setConflict(false);\n const patch: { body: string; title: string; type: string; status: string; tags: string[]; fields?: unknown } = {\n body,\n title,\n type,\n status,\n // Parse the comma-separated list; replace-set is intentional (the box shows\n // the chunk's tags, so saving makes it exactly what's in the box).\n tags: tagsText.split(\",\").map((t) => t.trim()).filter((t) => t !== \"\"),\n };\n // Send fields only when non-empty + valid JSON (a blank box leaves fields\n // untouched rather than clobbering them).\n if (fieldsText.trim() !== \"\") {\n try {\n patch.fields = JSON.parse(fieldsText);\n } catch {\n setErr(\"fields must be valid JSON\");\n return;\n }\n }\n setBusy(true);\n try {\n const updated = await data.documentUpdateChunk(chunk.id, chunk.revision, patch, scope, browse);\n onSaved(updated);\n onClose();\n } catch (ex) {\n const msg = ex instanceof Error ? ex.message : String(ex);\n setErr(msg);\n setConflict(/revision conflict/i.test(msg));\n setBusy(false);\n }\n };\n\n return (\n <div className=\"modal-overlay\" onClick={onClose}>\n <form className=\"modal chunk-editor\" onClick={(e) => e.stopPropagation()} onSubmit={submit}>\n {/* RFC BN P1: Save/Cancel pinned to the top so a long chunk body never\n needs scrolling to reach the save button. */}\n <div className=\"modal-header sticky-top\">\n <h3>Edit chunk</h3>\n <div className=\"modal-buttons modal-buttons-top\">\n <button type=\"button\" onClick={onClose} disabled={busy}>\n cancel\n </button>\n <button type=\"submit\" className=\"primary\" disabled={busy}>\n {busy ? \"saving…\" : \"save\"}\n </button>\n </div>\n </div>\n {err && (\n <div className=\"modal-err\">\n {err}\n {conflict && \" — reopen the chunk to load the latest, then reapply your edit.\"}\n </div>\n )}\n <label className=\"path-field\">\n <span>Title</span>\n <input className=\"path-modal-input\" value={title} onChange={(e) => setTitle(e.target.value)} />\n </label>\n <div className=\"chunk-editor-row\">\n <label className=\"path-field\">\n <span>Type</span>\n <input\n className=\"path-modal-input\"\n value={type}\n placeholder=\"(none)\"\n onChange={(e) => setType(e.target.value)}\n />\n </label>\n <label className=\"path-field\">\n <span>Status</span>\n <input\n className=\"path-modal-input\"\n value={status}\n placeholder=\"(none)\"\n onChange={(e) => setStatus(e.target.value)}\n />\n </label>\n </div>\n <label className=\"path-field\">\n <span>Tags</span>\n <input\n className=\"path-modal-input\"\n value={tagsText}\n placeholder=\"comma-separated, nest with a slash: area/sub, priority/high\"\n onChange={(e) => setTagsText(e.target.value)}\n />\n </label>\n {isImage && (\n <label className=\"path-field\">\n <span>Replace image</span>\n <input\n type=\"file\"\n accept=\"image/png,image/jpeg,image/gif,image/webp\"\n disabled={busy}\n onChange={(e) => {\n const f = e.target.files?.[0];\n if (f) void replaceImage(f);\n }}\n />\n </label>\n )}\n <label className=\"path-field\">\n <span>{bodyLabel}</span>\n <textarea\n className=\"modal-textarea chunk-body-input\"\n rows={isMermaid ? 8 : 12}\n value={body}\n onChange={(e) => setBody(e.target.value)}\n />\n </label>\n {isMermaid && (\n <div className=\"path-field\">\n <span>Preview</span>\n <div className=\"chunk-mermaid-preview\">\n {preview.trim() ? (\n <MermaidDiagram code={preview} />\n ) : (\n <p className=\"doc-empty-body\">(enter Mermaid source above)</p>\n )}\n </div>\n </div>\n )}\n <label className=\"path-field\">\n <span>Fields (JSON, optional)</span>\n <textarea\n className=\"modal-textarea chunk-fields-input\"\n rows={4}\n value={fieldsText}\n placeholder=\"{}\"\n onChange={(e) => setFieldsText(e.target.value)}\n />\n </label>\n </form>\n </div>\n );\n}\n","import { useEffect, useState, type FormEvent } from \"react\";\nimport type { BrowseScope, ChunkDetail, DocScope } from \"../types\";\nimport { useExplorerData } from \"../lib/dataLayer\";\nimport { subjectTypeChoices } from \"../lib/subjectType\";\n\n// SubjectTypeModal changes the kind of a subject: the type of its document's root\n// chunk, picked from the entity types in force. It is an update_chunk like any other\n// edit; the runtime tells subscribers the subject was re-typed, so relations whose\n// kind no longer fits get re-checked. The subject's natural key does not change.\nexport interface SubjectTypeModalProps {\n chunk: ChunkDetail;\n scope: DocScope;\n browse?: BrowseScope;\n onClose: () => void;\n onSaved: (updated: ChunkDetail) => void;\n}\n\nexport default function SubjectTypeModal({ chunk, scope, browse, onClose, onSaved }: SubjectTypeModalProps) {\n const data = useExplorerData();\n const [inForce, setInForce] = useState<string[] | null>(null);\n const [choice, setChoice] = useState(chunk.type ?? \"\");\n const [busy, setBusy] = useState(false);\n const [err, setErr] = useState<string | null>(null);\n // Set when the type was changed but the runtime withheld the announcement.\n const [notice, setNotice] = useState<string | null>(null);\n\n useEffect(() => {\n let cancelled = false;\n data\n .documentEntityTypes?.(scope, browse)\n .then((types) => {\n if (!cancelled) setInForce(types);\n })\n .catch((e) => {\n if (!cancelled) setErr(e instanceof Error ? e.message : String(e));\n });\n return () => {\n cancelled = true;\n };\n }, [data, scope, browse]);\n\n const choices = inForce ? subjectTypeChoices(inForce, chunk.type) : [];\n const unchanged = choice.toLowerCase() === (chunk.type ?? \"\").toLowerCase();\n\n const submit = async (e: FormEvent) => {\n e.preventDefault();\n if (unchanged || busy) return;\n setErr(null);\n setBusy(true);\n try {\n const updated = await data.documentUpdateChunk(chunk.id, chunk.revision, { type: choice }, scope, browse);\n onSaved(updated);\n if (updated.not_announced) {\n setNotice(updated.not_announced);\n setBusy(false);\n return;\n }\n onClose();\n } catch (ex) {\n setErr(ex instanceof Error ? ex.message : String(ex));\n setBusy(false);\n }\n };\n\n return (\n <div className=\"modal-overlay\" onClick={onClose}>\n <form className=\"modal\" onClick={(e) => e.stopPropagation()} onSubmit={submit}>\n <h3>Change type</h3>\n <p className=\"modal-context\">\n “{chunk.title || \"(untitled)\"}” is a subject (<code>{chunk.entity?.natural_key}</code>). Its key\n stays as it is; relations about it are re-checked against the new type.\n </p>\n {err && <div className=\"modal-err\">{err}</div>}\n {notice ? (\n <div className=\"modal-err\">The type was changed, but subscribers were not told: {notice}</div>\n ) : (\n <label className=\"path-field\">\n <span>Type</span>\n {inForce === null ? (\n <span className=\"doc-empty-body\">{err ? \"\" : \"loading types…\"}</span>\n ) : (\n <select\n className=\"path-modal-input\"\n value={choice}\n disabled={busy}\n onChange={(e) => setChoice(e.target.value)}\n >\n {choices.map((t) => (\n <option key={t} value={t}>\n {t}\n </option>\n ))}\n </select>\n )}\n </label>\n )}\n <div className=\"modal-buttons\">\n <button type=\"button\" onClick={onClose} disabled={busy}>\n {notice ? \"close\" : \"cancel\"}\n </button>\n {!notice && (\n <button type=\"submit\" className=\"primary\" disabled={busy || unchanged || inForce === null}>\n {busy ? \"saving…\" : \"change type\"}\n </button>\n )}\n </div>\n </form>\n </div>\n );\n}\n","import type {\n AcceptClassificationAnswer,\n ClassificationRecord,\n ClassifyAnswer,\n ClassifyCandidate,\n ClassifyStep,\n} from \"../types\";\n\n// Display helpers for RFC FO classification (the classify and\n// accept_classification Document ops). Pure, so what the viewer shows is\n// testable without rendering it.\n\n// PendingClassification is what waits in a root chunk's classification record\n// for an operator to accept.\nexport interface PendingClassification {\n proposedType?: string;\n proposedTags: string[];\n statementCount: number;\n}\n\nfunction isStringArray(v: unknown): v is string[] {\n return Array.isArray(v) && v.every((x) => typeof x === \"string\");\n}\n\n// classificationRecord reads `fields.classification` off a root chunk's fields.\n// The record lives in ordinary chunk fields, which any writer of the document may\n// set, so it is read defensively: a field of the wrong shape is dropped rather\n// than trusted, and anything that is not an object reads as no record.\nexport function classificationRecord(fields: unknown): ClassificationRecord | undefined {\n if (!fields || typeof fields !== \"object\") return undefined;\n const raw = (fields as { classification?: unknown }).classification;\n if (!raw || typeof raw !== \"object\" || Array.isArray(raw)) return undefined;\n const r = raw as Record<string, unknown>;\n const rec: ClassificationRecord = {};\n if (typeof r.by === \"string\") rec.by = r.by;\n if (typeof r.at === \"number\") rec.at = r.at;\n if (typeof r.applied_type === \"string\" && r.applied_type) rec.applied_type = r.applied_type;\n if (typeof r.proposed_type === \"string\" && r.proposed_type) rec.proposed_type = r.proposed_type;\n if (r.proposed_fields && typeof r.proposed_fields === \"object\" && !Array.isArray(r.proposed_fields)) {\n rec.proposed_fields = r.proposed_fields as Record<string, unknown>;\n }\n if (isStringArray(r.proposed_tags)) rec.proposed_tags = r.proposed_tags;\n if (isStringArray(r.statements)) rec.statements = r.statements;\n return rec;\n}\n\n// pendingClassification is the runtime's own \"nothing_pending\" test turned\n// around: a record is pending when it proposes a type, names statements, or\n// proposes tags. undefined when nothing waits (an applied-only record included).\nexport function pendingClassification(fields: unknown): PendingClassification | undefined {\n const rec = classificationRecord(fields);\n if (!rec) return undefined;\n const proposedTags = rec.proposed_tags ?? [];\n const statementCount = rec.statements?.length ?? 0;\n if (!rec.proposed_type && proposedTags.length === 0 && statementCount === 0) return undefined;\n return { proposedType: rec.proposed_type, proposedTags, statementCount };\n}\n\n// resultLabel says what a classify answer decided. A `report` answer wrote\n// nothing, so it says what an Apply would do; a `propose` answer says what was\n// done.\nexport function resultLabel(a: Pick<ClassifyAnswer, \"result\" | \"write\">): string {\n const report = a.write === \"report\";\n switch (a.result) {\n case \"classified\":\n return report ? \"would be classified\" : \"classified\";\n case \"proposed\":\n return report ? \"would be proposed for review\" : \"proposed — waits for review\";\n case \"kept\":\n return \"kept — the type was set by hand\";\n case \"unclassified\":\n return \"unclassified — nothing decided\";\n default:\n return String(a.result);\n }\n}\n\n// classDisposition says what became (or would become) of the class: applied to\n// the document live, or only proposed. undefined when no class was chosen. A\n// kept answer still names the class classify would choose, but never applies it.\nexport function classDisposition(\n a: Pick<ClassifyAnswer, \"class\" | \"live\" | \"result\" | \"write\">,\n): string | undefined {\n if (!a.class) return undefined;\n if (a.result === \"kept\") return \"not applied\";\n const report = a.write === \"report\";\n if (a.live) return report ? \"would be applied\" : \"applied\";\n return report ? \"would be proposed\" : \"proposed\";\n}\n\n// canApply: a report answer that a propose run would act on — a class to apply\n// or propose, or concepts / issuers to file. A propose answer has already been\n// applied, and an empty unclassified or kept report has nothing to write.\nexport function canApply(a: ClassifyAnswer): boolean {\n if (a.write !== \"report\") return false;\n if (a.result === \"classified\" || a.result === \"proposed\") return true;\n return (a.concepts?.length ?? 0) > 0 || (a.issued_by?.length ?? 0) > 0;\n}\n\n// formatShare renders a 0..1 share as a whole percentage.\nexport function formatShare(share: number | undefined): string {\n if (share == null || !Number.isFinite(share)) return \"\";\n return `${Math.round(share * 100)}%`;\n}\n\nconst STEP_LABELS: Record<string, string> = {\n rules: \"Rules\",\n vote: \"Neighbourhood vote\",\n model: \"Model\",\n};\n\n// stepLabel names a step; an unknown step name (a newer runtime) shows verbatim.\nexport function stepLabel(step: string): string {\n return STEP_LABELS[step] ?? step;\n}\n\n// candidateDetail is the one-line explanation of a candidate: the quote a rule\n// matched and where, or a vote's count and share.\nexport function candidateDetail(c: ClassifyCandidate): string {\n const parts: string[] = [];\n if (c.quote) parts.push(c.from ? `“${c.quote}” (${c.from})` : `“${c.quote}”`);\n if (c.votes != null) parts.push(`${c.votes} vote${c.votes === 1 ? \"\" : \"s\"}`);\n const share = formatShare(c.share);\n if (share) parts.push(share);\n return parts.join(\" · \");\n}\n\n// StepSummary is one step reduced to what the panel shows on its line; the\n// candidates go behind a collapsible.\nexport interface StepSummary {\n label: string;\n chosen?: string;\n method?: string;\n neighbours?: number;\n reason?: string;\n candidates: { class: string; detail: string }[];\n}\n\nexport function summarizeStep(s: ClassifyStep): StepSummary {\n return {\n label: stepLabel(s.step),\n ...(s.chosen ? { chosen: s.chosen } : {}),\n ...(s.method ? { method: s.method } : {}),\n ...(s.neighbours ? { neighbours: s.neighbours } : {}),\n ...(s.reason ? { reason: s.reason } : {}),\n candidates: (s.candidates ?? []).map((c) => ({ class: c.class, detail: candidateDetail(c) })),\n };\n}\n\n// acceptSummary reduces an accept_classification answer to a headline of what\n// became live, plus a notice per thing that did not: a class left pending or not\n// applied, skipped statements or tags, and the runtime's warnings.\nexport function acceptSummary(a: AcceptClassificationAnswer): { applied: string; notices: string[] } {\n const done: string[] = [];\n if (a.type) done.push(`type ${a.type}`);\n const n = a.accepted_statements?.length ?? 0;\n if (n > 0) done.push(`${n} statement${n === 1 ? \"\" : \"s\"}`);\n if (a.tags && a.tags.length > 0) done.push(`tags ${a.tags.join(\", \")}`);\n const notices: string[] = [];\n if (a.type_pending) {\n notices.push(\"The proposed class stays pending: another document already holds its identity.\");\n }\n if (a.skipped_type) {\n notices.push(`Class ${a.skipped_type} was not applied: it is not a declared document class.`);\n }\n const skipped = a.skipped_statements?.length ?? 0;\n if (skipped > 0) {\n notices.push(\n `${skipped} statement${skipped === 1 ? \" was\" : \"s were\"} skipped (already ruled on, or not this document's proposal).`,\n );\n }\n if (a.skipped_tags && a.skipped_tags.length > 0) {\n notices.push(`Tags not applied (not concepts of the ontology): ${a.skipped_tags.join(\", \")}.`);\n }\n notices.push(...(a.warnings ?? []));\n return { applied: done.length > 0 ? `Accepted ${done.join(\", \")}.` : \"Nothing was accepted.\", notices };\n}\n\n// classifyErrorText turns a refused op into the line the panel shows. The\n// runtime's nothing_pending business error gets plain words; anything else\n// (a permission refusal, an unconfirmed ontology) shows the runtime's own text.\nexport function classifyErrorText(e: unknown): string {\n const msg = e instanceof Error ? e.message : String(e);\n if (msg.includes(\"nothing_pending\")) return \"Nothing is pending for this document — it may already have been accepted.\";\n return msg;\n}\n","import { useEffect, useMemo, useState } from \"react\";\nimport type { AcceptClassificationAnswer, BrowseScope, ClassifyAnswer, DocScope } from \"../types\";\nimport { useExplorerData } from \"../lib/dataLayer\";\nimport {\n acceptSummary,\n canApply,\n classDisposition,\n classifyErrorText,\n formatShare,\n pendingClassification,\n resultLabel,\n summarizeStep,\n} from \"../lib/classify\";\n\n// Classification is the RFC FO classification surface of the document viewer,\n// rendered between the toolbar and the chunk split:\n// - the Classify panel — opened from the toolbar, it first runs classify with\n// write=report (nothing written) and shows the answer; Apply then runs it\n// with write=propose and reloads the document.\n// - a Pending block whenever the root chunk's classification record waits for\n// an operator, with Accept (accept_classification).\n// Every answer string (quotes, class and concept names, warnings) is rendered as\n// a plain text node — never Markdown or HTML. Refusals show inline.\n//\n// The host keys this component by document, so its state never outlives one.\nexport interface ClassificationProps {\n documentId: string;\n scope: DocScope;\n browse?: BrowseScope;\n // The root chunk's fields (undefined until loaded) — the pending record's source.\n rootFields: unknown;\n // Non-zero while the panel is open; each change to a non-zero value (the\n // toolbar's Classify toggle) runs a fresh report. 0 = closed.\n requestKey: number;\n onClose: () => void;\n // Reloads the document after a write (Apply / Accept).\n onChanged: () => void;\n}\n\nexport default function Classification({\n documentId,\n scope,\n browse,\n rootFields,\n requestKey,\n onClose,\n onChanged,\n}: ClassificationProps) {\n const data = useExplorerData();\n const [answer, setAnswer] = useState<ClassifyAnswer | null>(null);\n const [busy, setBusy] = useState(false);\n const [err, setErr] = useState<string | null>(null);\n const [accepting, setAccepting] = useState(false);\n const [acceptErr, setAcceptErr] = useState<string | null>(null);\n const [accepted, setAccepted] = useState<AcceptClassificationAnswer | null>(null);\n\n const pending = useMemo(\n () => (data.documentAcceptClassification ? pendingClassification(rootFields) : undefined),\n [data, rootFields],\n );\n\n // Each opening runs a report — nothing is written until Apply.\n useEffect(() => {\n if (requestKey === 0 || !data.documentClassify) return;\n let cancelled = false;\n setBusy(true);\n setErr(null);\n setAnswer(null);\n data\n .documentClassify(documentId, \"report\", scope, browse)\n .then((a) => !cancelled && setAnswer(a))\n .catch((e) => !cancelled && setErr(classifyErrorText(e)))\n .finally(() => !cancelled && setBusy(false));\n return () => {\n cancelled = true;\n };\n }, [data, documentId, scope, browse, requestKey]);\n\n const apply = async () => {\n if (!data.documentClassify) return;\n setBusy(true);\n setErr(null);\n try {\n setAnswer(await data.documentClassify(documentId, \"propose\", scope, browse));\n onChanged();\n } catch (e) {\n setErr(classifyErrorText(e));\n } finally {\n setBusy(false);\n }\n };\n\n const accept = async () => {\n if (!data.documentAcceptClassification) return;\n setAccepting(true);\n setAcceptErr(null);\n try {\n setAccepted(await data.documentAcceptClassification(documentId, scope, browse));\n onChanged();\n } catch (e) {\n setAcceptErr(classifyErrorText(e));\n } finally {\n setAccepting(false);\n }\n };\n\n const open = requestKey > 0;\n if (!open && !pending && !accepted && !acceptErr) return null;\n const acceptedSummary = accepted ? acceptSummary(accepted) : undefined;\n\n return (\n <div className=\"doc-classify\">\n {pending && (\n <div className=\"doc-classify-pending\">\n <span className=\"doc-classify-label\">Pending classification</span>\n {pending.proposedType && (\n <span>\n class <strong>{pending.proposedType}</strong>\n </span>\n )}\n {pending.proposedTags.length > 0 && (\n <span>\n tags{\" \"}\n {pending.proposedTags.map((t) => (\n <span className=\"chunk-tag\" key={t}>\n {t}\n </span>\n ))}\n </span>\n )}\n {pending.statementCount > 0 && (\n <span>\n {pending.statementCount} proposed statement{pending.statementCount === 1 ? \"\" : \"s\"}\n </span>\n )}\n <button type=\"button\" disabled={accepting} onClick={() => void accept()}>\n {accepting ? \"Accepting…\" : \"Accept\"}\n </button>\n </div>\n )}\n {acceptErr && (\n <div className=\"doc-classify-err\" role=\"alert\">\n {acceptErr}\n <button type=\"button\" className=\"doc-classify-dismiss\" onClick={() => setAcceptErr(null)} aria-label=\"Dismiss\">\n ×\n </button>\n </div>\n )}\n {acceptedSummary && (\n <div className=\"doc-classify-notice\" role=\"status\">\n <span>{acceptedSummary.applied}</span>\n {acceptedSummary.notices.map((n, i) => (\n <span className=\"doc-classify-warn\" key={i}>\n {n}\n </span>\n ))}\n <button type=\"button\" className=\"doc-classify-dismiss\" onClick={() => setAccepted(null)} aria-label=\"Dismiss\">\n ×\n </button>\n </div>\n )}\n {open && (\n <div className=\"doc-classify-panel\">\n <div className=\"doc-classify-head\">\n <h4>Classify</h4>\n {answer && <span className={`doc-classify-result ${answer.result}`}>{resultLabel(answer)}</span>}\n {answer?.write === \"report\" && <span className=\"doc-classify-hint\">report only — nothing written</span>}\n <button type=\"button\" className=\"doc-classify-dismiss\" onClick={onClose} aria-label=\"Close\">\n ×\n </button>\n </div>\n {!answer && !err && <p className=\"doc-classify-hint\">Classifying…</p>}\n {err && (\n <p className=\"doc-classify-err\" role=\"alert\">\n {err}\n </p>\n )}\n {answer && <ClassifyAnswerView answer={answer} />}\n {answer && canApply(answer) && (\n <div className=\"doc-classify-actions\">\n <button\n type=\"button\"\n disabled={busy}\n onClick={() => void apply()}\n title=\"Apply a unique rule match to the document; file everything else for review\"\n >\n {busy ? \"Applying…\" : \"Apply\"}\n </button>\n </div>\n )}\n </div>\n )}\n </div>\n );\n}\n\nexport function ClassifyAnswerView({ answer }: { answer: ClassifyAnswer }) {\n const disposition = classDisposition(answer);\n const fields = Object.entries(answer.fields ?? {});\n const issuers = answer.issued_by ?? [];\n const concepts = answer.concepts ?? [];\n const steps = (answer.steps ?? []).map(summarizeStep);\n const written = answer.statements?.length ?? 0;\n return (\n <>\n <dl className=\"doc-classify-rows\">\n {answer.class && (\n <>\n <dt>class</dt>\n <dd>\n <strong>{answer.class}</strong>\n {disposition && <span className=\"doc-classify-hint\"> ({disposition})</span>}\n </dd>\n </>\n )}\n {answer.work_key && (\n <>\n <dt>work key</dt>\n <dd className=\"doc-classify-mono\">{answer.work_key}</dd>\n </>\n )}\n {fields.length > 0 && (\n <>\n <dt>fields</dt>\n <dd className=\"doc-classify-mono\">\n {fields.map(([k, v]) => `${k}=${typeof v === \"string\" ? v : JSON.stringify(v)}`).join(\" · \")}\n </dd>\n </>\n )}\n {issuers.length > 0 && (\n <>\n <dt>issued by</dt>\n <dd>\n {issuers.map((iss, i) => (\n <span className=\"doc-classify-item\" key={`${iss.instance}-${i}`} title={iss.quote}>\n {iss.instance}\n {iss.quote && <span className=\"doc-classify-hint\"> “{iss.quote}”</span>}\n </span>\n ))}\n </dd>\n </>\n )}\n {concepts.length > 0 && (\n <>\n <dt>concepts</dt>\n <dd>\n {concepts.map((c) => (\n <span className=\"doc-classify-item\" key={c.tag} title={c.tag}>\n {c.concept}\n <span className=\"doc-classify-hint\"> {formatShare(c.share)}</span>\n </span>\n ))}\n </dd>\n </>\n )}\n {written > 0 && (\n <>\n <dt>statements</dt>\n <dd>\n {written} written\n {answer.statements!.some((s) => s.status === \"proposed\") && (\n <span className=\"doc-classify-hint\"> (proposed ones wait for review)</span>\n )}\n </dd>\n </>\n )}\n </dl>\n {steps.length > 0 && (\n <ol className=\"doc-classify-steps\">\n {steps.map((s, i) => (\n <li key={`${s.label}-${i}`}>\n <span className=\"doc-classify-step\">{s.label}</span>\n {s.method && <span className=\"doc-classify-hint\"> [{s.method}]</span>}\n {s.chosen ? <> → <strong>{s.chosen}</strong></> : <span className=\"doc-classify-hint\"> no choice</span>}\n {s.neighbours != null && <span className=\"doc-classify-hint\"> · {s.neighbours} neighbours</span>}\n {s.reason && <span className=\"doc-classify-hint\"> — {s.reason}</span>}\n {s.candidates.length > 0 && (\n <details className=\"doc-classify-candidates\">\n <summary>\n {s.candidates.length} candidate{s.candidates.length === 1 ? \"\" : \"s\"}\n </summary>\n <ul>\n {s.candidates.map((c, j) => (\n <li key={`${c.class}-${j}`}>\n <strong>{c.class}</strong>\n {c.detail && <span className=\"doc-classify-hint\"> {c.detail}</span>}\n </li>\n ))}\n </ul>\n </details>\n )}\n </li>\n ))}\n </ol>\n )}\n {answer.warnings && answer.warnings.length > 0 && (\n <ul className=\"doc-classify-warnings\">\n {answer.warnings.map((w, i) => (\n <li className=\"doc-classify-warn\" key={i}>\n {w}\n </li>\n ))}\n </ul>\n )}\n </>\n );\n}\n","import { useEffect, useMemo, useState } from \"react\";\nimport type { BrowseScope, ChunkDetail, DocScope } from \"../types\";\nimport { useExplorerData } from \"../lib/dataLayer\";\nimport { DEFAULT_SCHEME, type ColorScheme } from \"../lib/colorScheme\";\n\n// ColorSchemeEditor edits a document's RFC BN color settings — the color_enabled\n// flag + the per-(doc-type/status) and per-(chunk-status) palette — persisted in\n// the document's ROOT chunk fields. It fetches the root chunk on open (for the\n// revision + any sibling fields it must preserve) and writes back with\n// update_chunk. A \"copy to all documents of this type\" action stamps the same\n// palette onto every same-type document in scope, so a tree of like documents\n// stays visually consistent without per-doc editing.\nexport interface ColorSchemeEditorProps {\n documentId: string;\n rootChunkId: string;\n docType?: string;\n docStatus?: string;\n // chunkStatuses — the distinct statuses present in this document's chunks, so\n // the editor offers a color for each one actually in use (plus the defaults).\n chunkStatuses: string[];\n scope: DocScope;\n browse?: BrowseScope;\n onClose: () => void;\n // onSaved fires after a successful save so the viewer reloads its color meta +\n // re-tints the tree.\n onSaved: () => void;\n}\n\n// normalizeHex coerces a scheme color to the #rrggbb an <input type=\"color\">\n// requires (it rejects #rgb and names); a bad value falls back to neutral grey.\nfunction normalizeHex(v: string | undefined): string {\n const m = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec((v ?? \"\").trim());\n if (!m) return \"#888888\";\n let h = m[1];\n if (h.length === 3) h = h[0] + h[0] + h[1] + h[1] + h[2] + h[2];\n return \"#\" + h.toLowerCase();\n}\n\nexport default function ColorSchemeEditor({\n documentId,\n rootChunkId,\n docType,\n docStatus,\n chunkStatuses,\n scope,\n browse,\n onClose,\n onSaved,\n}: ColorSchemeEditorProps) {\n const data = useExplorerData();\n const [root, setRoot] = useState<ChunkDetail | null>(null);\n const [enabled, setEnabled] = useState(false);\n const [scheme, setScheme] = useState<ColorScheme>({});\n const [busy, setBusy] = useState(false);\n const [status, setStatus] = useState<string | null>(null);\n const [err, setErr] = useState<string | null>(null);\n\n // The keys the editor exposes: the defaults, plus this document's own doc key\n // and every chunk-status key actually in use — so a document with a bespoke\n // type/status still gets a picker. Stable + grouped (doc.* then chunk.*).\n const keys = useMemo(() => {\n const set = new Set<string>(Object.keys(DEFAULT_SCHEME));\n if (docType) set.add(`doc.${docType}.${docStatus || \"draft\"}`);\n for (const s of chunkStatuses) if (s) set.add(`chunk.${s}`);\n return [...set].sort();\n }, [docType, docStatus, chunkStatuses]);\n\n // Load the root chunk once for its revision + existing fields + stored scheme.\n useEffect(() => {\n let cancelled = false;\n data\n .documentGetChunk(rootChunkId, scope, browse)\n .then((d) => {\n if (cancelled) return;\n setRoot(d);\n const f = (d.fields ?? {}) as Record<string, unknown>;\n setEnabled(f.color_enabled === true);\n const stored = (f.color_scheme as ColorScheme) ?? {};\n // Seed from defaults so every picker shows a sensible starting color,\n // with the document's stored overrides on top.\n setScheme({ ...DEFAULT_SCHEME, ...stored });\n })\n .catch((e) => !cancelled && setErr(e instanceof Error ? e.message : String(e)));\n return () => {\n cancelled = true;\n };\n }, [data, rootChunkId, scope, browse]);\n\n const setColor = (key: string, hex: string) =>\n setScheme((prev) => ({ ...prev, [key]: hex }));\n\n // fieldsWith merges the color settings into an existing chunk's fields, so a\n // save never clobbers other typed fields the root chunk carries.\n const fieldsWith = (existing: unknown): Record<string, unknown> => ({\n ...((existing ?? {}) as Record<string, unknown>),\n color_enabled: enabled,\n color_scheme: scheme,\n });\n\n const save = async () => {\n if (!root) return;\n setBusy(true);\n setErr(null);\n setStatus(null);\n try {\n await data.documentUpdateChunk(\n rootChunkId,\n root.revision,\n { fields: fieldsWith(root.fields) },\n scope,\n browse,\n );\n onSaved();\n onClose();\n } catch (e) {\n setErr(e instanceof Error ? e.message : String(e));\n setBusy(false);\n }\n };\n\n // copyToType stamps THIS palette onto every OTHER document of the same type in\n // scope (best-effort; reports how many were updated). Each target is read for\n // its own root revision + fields so the write is a safe merge.\n const copyToType = async () => {\n if (!docType) {\n setErr(\"this document has no type to match\");\n return;\n }\n setBusy(true);\n setErr(null);\n setStatus(null);\n try {\n const { documents } = await data.documentsSummary({ underPath: \"/\" }, scope, browse);\n const targets = (documents ?? []).filter(\n (d) => d.type === docType && d.document_id !== documentId && d.root_chunk_id,\n );\n let applied = 0;\n for (const t of targets) {\n try {\n const tr = await data.documentGetChunk(t.root_chunk_id as string, scope, browse);\n await data.documentUpdateChunk(\n t.root_chunk_id as string,\n tr.revision,\n { fields: fieldsWith(tr.fields) },\n scope,\n browse,\n );\n applied++;\n } catch {\n // Skip a target that failed (revision race / gone); keep going.\n }\n }\n setStatus(`Applied to ${applied} other ${docType} document(s).`);\n onSaved();\n } catch (e) {\n setErr(e instanceof Error ? e.message : String(e));\n } finally {\n setBusy(false);\n }\n };\n\n const docKeys = keys.filter((k) => k.startsWith(\"doc.\"));\n const chunkKeys = keys.filter((k) => k.startsWith(\"chunk.\"));\n\n return (\n <div className=\"modal-overlay\" onClick={onClose}>\n <div className=\"modal scheme-editor\" onClick={(e) => e.stopPropagation()}>\n <div className=\"scheme-editor-head\">\n <h3>Document colors</h3>\n <div className=\"scheme-editor-actions\">\n <button type=\"button\" onClick={onClose} disabled={busy}>\n cancel\n </button>\n <button type=\"button\" className=\"primary\" onClick={() => void save()} disabled={busy || !root}>\n {busy ? \"saving…\" : \"save\"}\n </button>\n </div>\n </div>\n {err && <div className=\"modal-err\">{err}</div>}\n {!root ? (\n <p className=\"modal-context\">Loading…</p>\n ) : (\n <>\n <label className=\"scheme-toggle\">\n <input\n type=\"checkbox\"\n checked={enabled}\n onChange={(e) => setEnabled(e.target.checked)}\n />\n <span>Enable coloring for this document</span>\n </label>\n <p className=\"modal-context\">\n Document rows are tinted by type + status; chunk tiles by status. Colors apply as a\n semi-transparent wash so text stays readable.\n </p>\n\n <div className=\"scheme-group\">\n <h4>Document (type · status)</h4>\n {docKeys.map((k) => (\n <ColorRow key={k} label={k.slice(\"doc.\".length)} value={scheme[k]} onChange={(hex) => setColor(k, hex)} />\n ))}\n </div>\n <div className=\"scheme-group\">\n <h4>Chunks (status)</h4>\n {chunkKeys.map((k) => (\n <ColorRow key={k} label={k.slice(\"chunk.\".length)} value={scheme[k]} onChange={(hex) => setColor(k, hex)} />\n ))}\n </div>\n\n <div className=\"scheme-editor-foot\">\n <button type=\"button\" onClick={() => void copyToType()} disabled={busy || !docType} title={docType ? `Apply this palette to every other ${docType} document` : \"This document has no type\"}>\n copy to all {docType || \"same-type\"} documents\n </button>\n {status && <span className=\"scheme-status\">{status}</span>}\n </div>\n </>\n )}\n </div>\n </div>\n );\n}\n\nfunction ColorRow({ label, value, onChange }: { label: string; value: string | undefined; onChange: (hex: string) => void }) {\n const hex = normalizeHex(value);\n return (\n <label className=\"scheme-row\">\n <input type=\"color\" value={hex} onChange={(e) => onChange(e.target.value)} />\n <span className=\"scheme-key\">{label}</span>\n <code className=\"scheme-hex\">{hex}</code>\n </label>\n );\n}\n","// ChunkTarget renders the far end of a link — a reference, a backlink, a related\n// chunk, an unlinked mention — as something the reader can follow.\n//\n// A chunk in THIS document selects in place. A chunk in ANOTHER document opens\n// that document at the chunk; it keeps the ↗ mark and the \"another document\"\n// hint, because that click replaces what is on screen and the reader should know\n// before making it. Cross-document targets used to be an inert label: the viewer\n// showed one document and had nowhere to go, so the links the edge list\n// advertised could not be followed at all.\n//\n// With no onOpenDocument (a host that cannot leave its document), a\n// cross-document target stays a label rather than a button that does nothing.\nexport interface ChunkTargetProps {\n // The far chunk, its title, and the document it lives in.\n id: string;\n title?: string;\n targetDocumentId?: string;\n // The document on screen. A target with no document id of its own is treated\n // as belonging to it (an endpoint the runtime could not enrich).\n documentId: string;\n onSelectChunk: (id: string) => void;\n onOpenDocument?: (documentId: string, chunkId: string, title?: string) => void;\n}\n\nexport default function ChunkTarget({\n id,\n title,\n targetDocumentId,\n documentId,\n onSelectChunk,\n onOpenDocument,\n}: ChunkTargetProps) {\n const label = title || id.slice(0, 8);\n if (!targetDocumentId || targetDocumentId === documentId) {\n return (\n <button type=\"button\" className=\"doc-ref-target\" onClick={() => onSelectChunk(id)}>\n {label}\n </button>\n );\n }\n if (!onOpenDocument) {\n return (\n <span className=\"doc-ref-target external\" title=\"In another document\">\n {label} ↗\n </span>\n );\n }\n return (\n <button\n type=\"button\"\n className=\"doc-ref-target external\"\n title=\"In another document — opens it at this chunk\"\n onClick={() => onOpenDocument(targetDocumentId, id, title)}\n >\n {label} ↗\n </button>\n );\n}\n","import { useState } from \"react\";\nimport type { StatementFields } from \"../types\";\nimport {\n clipQuote,\n evidencePreview,\n methodLabel,\n statusLabel,\n validityLabel,\n verdictHint,\n} from \"../lib/statement\";\n\n// StatementRuling is how a reference row hands an operator's ruling on a proposed\n// statement to its host: accept (an optional reason) or reject (a reason). It\n// resolves once the ruling is stored — the host refetches the edges — and rejects\n// with the runtime's refusal, which the row shows inline.\nexport type StatementRuling = (id: string, accept: boolean, reason?: string) => Promise<void>;\n\n// StatementMeta is what a reference row shows of the RFC FN envelope beyond the\n// link itself: a status badge for a statement that does not simply hold, how it\n// was made when that is unusual, whether it has been judged (the reason is the\n// tooltip), when it is valid, and the first evidence quotes. Rendered inside the\n// row's flex container; the quote list wraps onto its own line. Quotes are plain\n// text nodes — never Markdown or HTML.\nexport function StatementMeta({ statement }: { statement: StatementFields }) {\n const status = statusLabel(statement);\n const method = methodLabel(statement);\n const verdict = verdictHint(statement);\n const validity = validityLabel(statement);\n const { rows, more } = evidencePreview(statement);\n return (\n <>\n {status && <span className={`doc-stmt-status ${status}`}>{status}</span>}\n {method && (\n <span className=\"doc-stmt-method\" title=\"how this relation was made\">\n {method}\n </span>\n )}\n {verdict && (\n <span className=\"doc-stmt-verdict\" title={verdict}>\n judged\n </span>\n )}\n {validity && <span className=\"doc-stmt-valid\">{validity}</span>}\n {rows.length > 0 && (\n <ul className=\"doc-stmt-evidence\">\n {rows.map((ev) => (\n <li key={ev.id} title={ev.quote}>\n “{clipQuote(ev.quote)}”\n {ev.part === \"title\" && <span className=\"doc-stmt-part\"> (title)</span>}\n {ev.stale && <span className=\"doc-stmt-stale\"> (source changed)</span>}\n </li>\n ))}\n {more > 0 && <li className=\"doc-stmt-more\">+{more} more</li>}\n </ul>\n )}\n </>\n );\n}\n\n// StatementReview is the Accept / Reject control on a proposed statement.\n// Reject opens an inline reason field (a rejection must say why); a refusal from\n// the runtime is shown next to the buttons.\nexport function StatementReview({ id, onRule }: { id: string; onRule: StatementRuling }) {\n const [rejecting, setRejecting] = useState(false);\n const [reason, setReason] = useState(\"\");\n const [busy, setBusy] = useState(false);\n const [err, setErr] = useState<string | null>(null);\n\n const rule = async (accept: boolean) => {\n setBusy(true);\n setErr(null);\n try {\n await onRule(id, accept, accept ? undefined : reason.trim());\n setRejecting(false);\n setReason(\"\");\n } catch (e) {\n setErr(e instanceof Error ? e.message : String(e));\n } finally {\n setBusy(false);\n }\n };\n\n return (\n <span className=\"doc-stmt-review\">\n {rejecting ? (\n <>\n <input\n type=\"text\"\n aria-label=\"Reason for rejecting\"\n placeholder=\"why reject?\"\n value={reason}\n disabled={busy}\n onChange={(e) => setReason(e.target.value)}\n onKeyDown={(e) => {\n if (e.key === \"Enter\" && reason.trim()) void rule(false);\n if (e.key === \"Escape\") setRejecting(false);\n }}\n autoFocus\n />\n <button\n type=\"button\"\n className=\"danger\"\n disabled={busy || !reason.trim()}\n onClick={() => void rule(false)}\n >\n Reject\n </button>\n <button type=\"button\" disabled={busy} onClick={() => setRejecting(false)}>\n Cancel\n </button>\n </>\n ) : (\n <>\n <button type=\"button\" disabled={busy} onClick={() => void rule(true)}>\n Accept\n </button>\n <button type=\"button\" disabled={busy} onClick={() => setRejecting(true)}>\n Reject…\n </button>\n </>\n )}\n {err && (\n <span className=\"doc-stmt-err\" role=\"alert\">\n {err}\n </span>\n )}\n </span>\n );\n}\n","import { useRef, useState } from \"react\";\nimport type { BrowseScope, DocEdge } from \"../types\";\nimport { useExplorerData } from \"../lib/dataLayer\";\nimport type { DocRulingAnswer } from \"../lib/dataLayer\";\nimport { ruleDocumentProposals, rulingNote } from \"../lib/bulkReview\";\nimport { chunkCount, undoRulings, type RulingAction, type RulingOutcome, type RulingScope } from \"../lib/ruling\";\nimport ChunkTarget from \"./ChunkTarget\";\nimport { StatementMeta } from \"./Statement\";\n\n// ProposalReview is the Connections panel's bulk review of one document's\n// proposals (RFC FS P1): pick rows, or take every proposal filed from the\n// document, and accept or reject them in one ruling. Every ruling counts\n// first (a dry run) and asks before it rules; a rejection needs a reason; the\n// result offers an undo when the data layer can revert.\nexport interface ProposalReviewProps {\n documentId: string;\n proposals: DocEdge[];\n // The document's edge list stopped at its page cap, so proposals past it are\n // not listed here (the \"all\" actions still reach them).\n incomplete?: boolean;\n scope: RulingScope;\n browse?: BrowseScope;\n // Called after a ruling or an undo changed statements: the host refetches.\n onChanged: () => void;\n onSelectChunk: (id: string) => void;\n onOpenDocument?: (documentId: string, chunkId: string, title?: string) => void;\n}\n\n// SAMPLE is how many of the dry run's sample the confirm lists.\nconst SAMPLE = 3;\n\ntype Step =\n | { kind: \"idle\" }\n | { kind: \"reason\"; action: RulingAction; all: boolean }\n | { kind: \"counting\"; action: RulingAction; all: boolean }\n | { kind: \"confirm\"; action: RulingAction; all: boolean; dry: DocRulingAnswer; changed: boolean }\n | { kind: \"ruling\"; action: RulingAction; ruled?: number; total?: number };\n\ninterface Result {\n text: string;\n rulingIds: string[];\n undone?: boolean;\n}\n\nexport default function ProposalReview({\n documentId,\n proposals,\n incomplete,\n scope,\n browse,\n onChanged,\n onSelectChunk,\n onOpenDocument,\n}: ProposalReviewProps) {\n const data = useExplorerData();\n const [selected, setSelected] = useState<ReadonlySet<string>>(new Set());\n const [step, setStep] = useState<Step>({ kind: \"idle\" });\n const [reason, setReason] = useState(\"\");\n const [err, setErr] = useState<string | null>(null);\n const [result, setResult] = useState<Result | null>(null);\n const confirmRef = useRef<((ok: boolean) => void) | null>(null);\n\n // Only rows still listed count as picked: a reload drops the ruled ones.\n const listed = new Set(proposals.map((p) => p.id!));\n const picked = [...selected].filter((id) => listed.has(id));\n const busy = step.kind !== \"idle\" && step.kind !== \"reason\";\n\n const begin = (action: RulingAction, all: boolean) => {\n setErr(null);\n setResult(null);\n if (action === \"reject\") setStep({ kind: \"reason\", action, all });\n else void rule(action, all, \"\");\n };\n\n const rule = async (action: RulingAction, all: boolean, why: string) => {\n setStep({ kind: \"counting\", action, all });\n let out: RulingOutcome;\n try {\n out = await ruleDocumentProposals(\n data,\n { documentId, action, ids: all ? undefined : picked, reason: why.trim() || undefined, scope, browse },\n {\n confirm: (dry, reasonFor) =>\n new Promise<boolean>((resolve) => {\n confirmRef.current = resolve;\n setStep({ kind: \"confirm\", action, all, dry, changed: reasonFor !== \"first\" });\n }),\n onProgress: (p) => setStep({ kind: \"ruling\", action, ruled: p.ruled, total: p.total }),\n },\n );\n } catch (e) {\n out = { rulingIds: [], ruled: 0, failed: 0, skipped: 0, total: 0, cancelled: false, failures: [], error: e };\n }\n confirmRef.current = null;\n setStep({ kind: \"idle\" });\n setReason(\"\");\n if (out.rulingIds.length > 0) {\n setSelected(new Set());\n setResult({ text: rulingNote(action, out), rulingIds: out.rulingIds });\n onChanged();\n } else if (out.error === undefined && !out.cancelled) {\n setResult({ text: \"Nothing to rule: no proposals match.\", rulingIds: [] });\n }\n if (out.error !== undefined) setErr(out.error instanceof Error ? out.error.message : String(out.error));\n };\n\n const answer = (ok: boolean) => {\n if (ok && step.kind === \"confirm\") setStep({ kind: \"ruling\", action: step.action });\n confirmRef.current?.(ok);\n };\n\n const undo = async () => {\n if (!result || !data.documentRevertRuling) return;\n const r = result;\n const u = await undoRulings((id) => data.documentRevertRuling!(id, scope, browse), r.rulingIds);\n const parts = [`${u.reverted} came back to review`];\n if (u.changed > 0) parts.push(`${u.changed} changed since and left as ruled`);\n if (u.errors.length > 0) parts.push(`not undone: ${u.errors.join(\"; \")}`);\n setResult({ ...r, undone: true, text: parts.join(\"; \") + \".\" });\n onChanged();\n };\n\n const toggle = (id: string) =>\n setSelected((cur) => {\n const next = new Set(cur);\n if (next.has(id)) next.delete(id);\n else next.add(id);\n return next;\n });\n const allPicked = proposals.length > 0 && picked.length === proposals.length;\n // Nothing listed and nothing past the list: no \"all\" to rule.\n const noneToRule = proposals.length === 0 && !incomplete;\n\n return (\n <div className=\"doc-conn-group doc-bulk\">\n <h5>Proposals from this document ({proposals.length})</h5>\n <div className=\"doc-bulk-bar\">\n <label>\n <input\n type=\"checkbox\"\n aria-label=\"select every proposal shown\"\n checked={allPicked}\n disabled={busy || proposals.length === 0}\n onChange={() => setSelected(allPicked ? new Set() : new Set(listed))}\n />{\" \"}\n all shown\n </label>\n <button type=\"button\" disabled={busy || picked.length === 0} onClick={() => begin(\"accept\", false)}>\n Accept selected ({picked.length})\n </button>\n <button type=\"button\" className=\"danger\" disabled={busy || picked.length === 0} onClick={() => begin(\"reject\", false)}>\n Reject selected…\n </button>\n <button type=\"button\" disabled={busy || noneToRule} onClick={() => begin(\"accept\", true)}>\n Accept all from this document\n </button>\n <button type=\"button\" className=\"danger\" disabled={busy || noneToRule} onClick={() => begin(\"reject\", true)}>\n Reject all…\n </button>\n </div>\n\n {step.kind === \"reason\" && (\n <form\n className=\"doc-bulk-step\"\n onSubmit={(e) => {\n e.preventDefault();\n if (reason.trim()) void rule(step.action, step.all, reason);\n }}\n >\n <input\n type=\"text\"\n aria-label=\"Reason for rejecting\"\n placeholder=\"why reject?\"\n value={reason}\n onChange={(e) => setReason(e.target.value)}\n autoFocus\n />\n <button type=\"submit\" className=\"danger\" disabled={!reason.trim()}>\n Count\n </button>\n <button type=\"button\" onClick={() => setStep({ kind: \"idle\" })}>\n Cancel\n </button>\n </form>\n )}\n {step.kind === \"counting\" && <p className=\"doc-conn-empty\">counting…</p>}\n {step.kind === \"confirm\" && <BulkConfirm step={step} onAnswer={answer} />}\n {step.kind === \"ruling\" && (\n <p className=\"doc-conn-empty\">\n {step.total ? `ruled ${step.ruled ?? 0} of ${step.total}…` : \"ruling…\"}\n </p>\n )}\n {err && (\n <p className=\"doc-stmt-err\" role=\"alert\">\n {err}\n </p>\n )}\n {result && (\n <p className=\"doc-bulk-result\" role=\"status\">\n {result.text}\n {result.rulingIds.length > 0 && !result.undone && data.documentRevertRuling && (\n <button type=\"button\" onClick={() => void undo()}>\n Undo\n </button>\n )}\n </p>\n )}\n\n {proposals.length === 0 ? (\n <p className=\"doc-conn-empty\">none</p>\n ) : (\n <ul className=\"doc-conn-list\">\n {proposals.map((e) => (\n <li className=\"doc-conn-row\" key={e.id}>\n <input\n type=\"checkbox\"\n aria-label={`select ${e.from_title ?? e.from_id} ${e.kind} ${e.to_title ?? e.to_id}`}\n checked={selected.has(e.id!)}\n disabled={busy}\n onChange={() => toggle(e.id!)}\n />\n <ChunkTarget\n id={e.from_id}\n title={e.from_title}\n targetDocumentId={e.from_document_id}\n documentId={documentId}\n onSelectChunk={onSelectChunk}\n onOpenDocument={onOpenDocument}\n />\n <span className=\"doc-ref-kind\">{e.kind}</span>\n <ChunkTarget\n id={e.to_id}\n title={e.to_title}\n targetDocumentId={e.to_document_id}\n documentId={documentId}\n onSelectChunk={onSelectChunk}\n onOpenDocument={onOpenDocument}\n />\n <StatementMeta statement={e} />\n </li>\n ))}\n </ul>\n )}\n </div>\n );\n}\n\n// BulkConfirm is the dry run before a document's ruling: how many, a sample,\n// what will be skipped.\nexport function BulkConfirm({\n step,\n onAnswer,\n}: {\n step: { action: RulingAction; all: boolean; dry: DocRulingAnswer; changed: boolean };\n onAnswer: (ok: boolean) => void;\n}) {\n const { dry } = step;\n const verb = step.action === \"accept\" ? \"Accept\" : \"Reject\";\n const chunks = chunkCount(dry.matched);\n return (\n <div className=\"doc-bulk-step doc-bulk-confirm\">\n {step.changed && <p className=\"doc-bulk-warn\">The proposals changed since the last count; counted again.</p>}\n <p>\n {verb} {dry.matched} statement{dry.matched === 1 ? \"\" : \"s\"}\n {step.all ? \" filed from this document\" : \"\"}\n {chunks > 1 ? `, in ${chunks} rulings of up to 1,000` : \"\"}?\n {dry.skipped > 0 && ` ${dry.skipped} of them are not yours to rule and will be skipped.`}\n </p>\n {(dry.sample ?? []).length > 0 && (\n <ul className=\"doc-bulk-sample\">\n {(dry.sample ?? []).slice(0, SAMPLE).map((s) => (\n <li key={s.id}>\n {s.from_title || s.from_id} <span className=\"doc-ref-kind\">{s.kind}</span> {s.to_title || s.to_id}\n </li>\n ))}\n </ul>\n )}\n <button type=\"button\" className={step.action === \"reject\" ? \"danger\" : undefined} onClick={() => onAnswer(true)}>\n {verb} {dry.matched}\n </button>\n <button type=\"button\" onClick={() => onAnswer(false)}>\n Cancel\n </button>\n </div>\n );\n}\n","import { useEffect, useState } from \"react\";\nimport type {\n Backlink,\n BrowseScope,\n DocScope,\n RelatedChunk,\n UnlinkedMention,\n} from \"../types\";\nimport { useExplorerData } from \"../lib/dataLayer\";\nimport type { ReviewPanel } from \"../lib/bulkReview\";\nimport ChunkTarget from \"./ChunkTarget\";\nimport ProposalReview from \"./ProposalReview\";\nimport { StatementMeta } from \"./Statement\";\n\n// Connections is the RFC BS per-chunk connection surface, a collapsible companion\n// to CrossReferences. It shows three lists for the SELECTED chunk, each fetched\n// lazily (only once the section is expanded, and refetched when the selection\n// changes while open — collapsed keeps the viewer quiet):\n// - Backlinks — chunks that link TO this one (\"what links here\").\n// - Related — semantic neighbours (vector similarity). REFUSES with no\n// embedder configured → a muted note, not an error.\n// - Unlinked mentions — chunks that name this one but don't link it (candidates).\n// Every target is clickable: a same-document one selects in place (onSelectChunk),\n// a cross-document one (↗) opens that document at the chunk (onOpenDocument) —\n// the same rule CrossReferences uses, through the same ChunkTarget.\n//\n// With `review` (RFC FS), the panel also lists the document's own proposals —\n// whichever chunk is selected — with row selection and bulk Accept / Reject.\n// The host passes it only when its data layer can rule in bulk.\nexport type ConnectionsReview = ReviewPanel;\n\nexport interface ConnectionsProps {\n documentId: string;\n selectedId?: string;\n scope: DocScope;\n browse?: BrowseScope;\n onSelectChunk: (id: string) => void;\n onOpenDocument?: (documentId: string, chunkId: string, title?: string) => void;\n // Bumped by the host when the document's edges changed (an operator ruled on a\n // proposal) so an open panel refetches its backlinks.\n refreshKey?: number;\n review?: ConnectionsReview;\n}\n\nconst RELATED_LIMIT = 8;\nconst MENTIONS_LIMIT = 20;\n\n// isEmbedderError recognizes the `related` op's refusal when the deployment has no\n// embedder/vector backend, so the UI can say \"not configured\" rather than surface\n// a raw error — related is a best-effort enhancement, never load-bearing.\nfunction isEmbedderError(msg: string): boolean {\n return /embedder|embedding|vector|semantic|not configured/i.test(msg);\n}\n\nexport default function Connections({\n documentId,\n selectedId,\n scope,\n browse,\n onSelectChunk,\n onOpenDocument,\n refreshKey,\n review,\n}: ConnectionsProps) {\n const data = useExplorerData();\n const [open, setOpen] = useState(false);\n const [loading, setLoading] = useState(false);\n const [loadedId, setLoadedId] = useState<string | undefined>(undefined);\n const [backlinks, setBacklinks] = useState<Backlink[]>([]);\n const [related, setRelated] = useState<RelatedChunk[]>([]);\n const [relatedNote, setRelatedNote] = useState<string | null>(null);\n const [mentions, setMentions] = useState<UnlinkedMention[]>([]);\n const [mentionsTruncated, setMentionsTruncated] = useState(false);\n\n // Fetch only while expanded AND a chunk is selected; the three reads are\n // independent (allSettled) so a `related` refusal never blanks backlinks/\n // mentions. Cancelled on unmount / re-selection so a stale resolution can't\n // clobber the newer one.\n useEffect(() => {\n if (!open || !selectedId) return;\n const id = selectedId;\n let cancelled = false;\n setLoading(true);\n Promise.allSettled([\n data.documentBacklinks(id, scope, browse),\n data.documentRelated(id, scope, browse, RELATED_LIMIT),\n data.documentUnlinkedMentions(id, scope, browse, MENTIONS_LIMIT),\n ]).then(([b, r, m]) => {\n if (cancelled) return;\n setBacklinks(b.status === \"fulfilled\" ? b.value.backlinks ?? [] : []);\n if (r.status === \"fulfilled\") {\n setRelated(r.value.related ?? []);\n setRelatedNote(null);\n } else {\n setRelated([]);\n const msg = r.reason instanceof Error ? r.reason.message : String(r.reason);\n setRelatedNote(isEmbedderError(msg) ? \"semantic search not configured\" : msg);\n }\n if (m.status === \"fulfilled\") {\n setMentions(m.value.unlinked_mentions ?? []);\n setMentionsTruncated(!!m.value.truncated);\n } else {\n setMentions([]);\n setMentionsTruncated(false);\n }\n setLoadedId(id);\n setLoading(false);\n });\n return () => {\n cancelled = true;\n };\n }, [data, open, selectedId, scope, browse, refreshKey]);\n\n // The three lists differ only in which fields name the far chunk.\n const target = (id: string, title?: string, targetDocumentId?: string) => (\n <ChunkTarget\n id={id}\n title={title}\n targetDocumentId={targetDocumentId}\n documentId={documentId}\n onSelectChunk={onSelectChunk}\n onOpenDocument={onOpenDocument}\n />\n );\n // Data is current only when it was fetched for THIS selection and no fetch is in\n // flight — otherwise show \"loading…\" (this also covers the first frame after\n // expanding, before the effect sets loading, so no stale \"none\" flashes).\n const ready = !!(open && selectedId && !loading && loadedId === selectedId);\n\n return (\n <div className=\"doc-conn\">\n <button\n type=\"button\"\n className=\"doc-conn-toggle\"\n onClick={() => setOpen((o) => !o)}\n >\n {open ? \"▼\" : \"▶\"} Connections\n </button>\n {open && (\n <div className=\"doc-conn-body\">\n {review && (\n <ProposalReview\n documentId={documentId}\n proposals={review.proposals}\n incomplete={review.incomplete}\n scope={review.scope}\n browse={browse}\n onChanged={review.onChanged}\n onSelectChunk={onSelectChunk}\n onOpenDocument={onOpenDocument}\n />\n )}\n {!selectedId ? (\n <p className=\"doc-conn-empty\">Select a chunk.</p>\n ) : !ready ? (\n <p className=\"doc-conn-empty\">loading…</p>\n ) : (\n <>\n <div className=\"doc-conn-group\">\n <h5>Backlinks</h5>\n {backlinks.length === 0 ? (\n <p className=\"doc-conn-empty\">none</p>\n ) : (\n <ul className=\"doc-conn-list\">\n {backlinks.map((e, i) => (\n <li className=\"doc-conn-row\" key={`${e.from_id}-${e.kind}-${i}`}>\n {target(e.from_id, e.from_title, e.from_document_id)}\n <span className=\"doc-ref-kind\">{e.kind}</span>\n {e.auto && (\n <span className=\"doc-conn-auto\" title=\"Auto-linked from a [[wikilink]]\">\n auto\n </span>\n )}\n <StatementMeta statement={e} />\n </li>\n ))}\n </ul>\n )}\n </div>\n\n <div className=\"doc-conn-group\">\n <h5>Related</h5>\n {relatedNote ? (\n <p className=\"doc-conn-empty\">{relatedNote}</p>\n ) : related.length === 0 ? (\n <p className=\"doc-conn-empty\">none</p>\n ) : (\n <ul className=\"doc-conn-list\">\n {related.map((r, i) => (\n <li className=\"doc-conn-row\" key={`${r.chunk_id}-${i}`}>\n {target(r.chunk_id, r.title, r.document_id)}\n <span className=\"doc-conn-score\" title=\"similarity score\">\n {r.score.toFixed(2)}\n </span>\n </li>\n ))}\n </ul>\n )}\n </div>\n\n <div className=\"doc-conn-group\">\n <h5>Unlinked mentions</h5>\n {mentions.length === 0 ? (\n <p className=\"doc-conn-empty\">none</p>\n ) : (\n <ul className=\"doc-conn-list\">\n {mentions.map((m, i) => (\n <li className=\"doc-conn-row\" key={`${m.chunk_id}-${i}`}>\n {target(m.chunk_id, m.title, m.document_id)}\n </li>\n ))}\n {mentionsTruncated && (\n <li className=\"doc-conn-more\" aria-hidden>\n (more…)\n </li>\n )}\n </ul>\n )}\n </div>\n </>\n )}\n </div>\n )}\n </div>\n );\n}\n","import { useState } from \"react\";\nimport type { DocEdge } from \"../types\";\nimport { isProposed } from \"../lib/statement\";\nimport ChunkTarget from \"./ChunkTarget\";\nimport MermaidDiagram from \"./Mermaid\";\nimport { StatementMeta, StatementReview, type StatementRuling } from \"./Statement\";\n\n// CrossReferences renders the RFC BN P4 cross-reference surface for a document:\n// - a References list for the SELECTED chunk (its outgoing + incoming edges),\n// each target clickable: a same-document one selects in place, a\n// cross-document one (↗) opens that document at the chunk.\n// - a collapsible whole-document relationship GRAPH (a Mermaid flowchart of the\n// document's edges), capped to the first N with a \"show all\" expand so a\n// heavily cross-linked document doesn't render an unreadable diagram. Its\n// nodes follow the same rule as the list.\n// Fed by the paged get_edges load (all edges touching the document); renders\n// nothing when the document has no edges. Since RFC FN each edge is a statement: a row\n// also shows its status / method / verdict / validity / evidence, and a proposed\n// one gets Accept / Reject when the host passes onRuleStatement.\nexport interface CrossReferencesProps {\n edges: DocEdge[];\n documentId: string;\n selectedId?: string;\n onSelectChunk: (id: string) => void;\n // Opens ANOTHER document at a chunk. Omitted → cross-document targets are\n // labels only.\n onOpenDocument?: (documentId: string, chunkId: string, title?: string) => void;\n // Rules on a proposed statement, then refetches the edges. Omitted → proposals\n // are shown but not reviewable here.\n onRuleStatement?: StatementRuling;\n // The edge list stopped before the end (the load's page cap): both the list\n // and the graph may be missing links, so the panel says so.\n incomplete?: boolean;\n}\n\n// GRAPH_CAP is the default number of edges the relationship graph draws before\n// requiring an explicit \"show all\" (keeps a big graph readable + cheap).\nconst GRAPH_CAP = 24;\n\nexport default function CrossReferences({\n edges,\n documentId,\n selectedId,\n onSelectChunk,\n onOpenDocument,\n onRuleStatement,\n incomplete,\n}: CrossReferencesProps) {\n const [showGraph, setShowGraph] = useState(false);\n const [showAll, setShowAll] = useState(false);\n\n if (edges.length === 0) return null;\n\n const refs = selectedId\n ? edges.filter((e) => e.from_id === selectedId || e.to_id === selectedId)\n : [];\n const graphEdges = showAll ? edges : edges.slice(0, GRAPH_CAP);\n const graphDef = buildGraph(graphEdges);\n const followNode = (node: string) => {\n const hit = graphEndpoint(graphEdges, node);\n if (!hit) return;\n if (!hit.documentId || hit.documentId === documentId) onSelectChunk(hit.id);\n else onOpenDocument?.(hit.documentId, hit.id, hit.title);\n };\n\n return (\n <div className=\"doc-refs\">\n {incomplete && (\n <p className=\"doc-refs-incomplete\">\n Showing the first {edges.length} links of this document; it has more, which are not shown\n here or in the graph.\n </p>\n )}\n {selectedId && (\n <div className=\"doc-refs-list-wrap\">\n <h4>References</h4>\n {refs.length === 0 ? (\n <p className=\"doc-refs-empty\">This chunk has no links.</p>\n ) : (\n <ul className=\"doc-refs-list\">\n {refs.map((e, i) => (\n <RefRow\n key={`${e.from_id}-${e.to_id}-${e.kind}-${i}`}\n edge={e}\n selectedId={selectedId}\n documentId={documentId}\n onSelectChunk={onSelectChunk}\n onOpenDocument={onOpenDocument}\n onRuleStatement={onRuleStatement}\n />\n ))}\n </ul>\n )}\n </div>\n )}\n\n <div className=\"doc-graph\">\n <button type=\"button\" className=\"doc-graph-toggle\" onClick={() => setShowGraph((s) => !s)}>\n {showGraph ? \"▼\" : \"▶\"} relationship graph ({edges.length})\n </button>\n {showGraph && (\n <>\n <MermaidDiagram code={graphDef} onNodeClick={followNode} />\n {edges.length > GRAPH_CAP && (\n <button type=\"button\" className=\"doc-graph-more\" onClick={() => setShowAll((s) => !s)}>\n {showAll ? `show top ${GRAPH_CAP}` : `show all ${edges.length}`}\n </button>\n )}\n </>\n )}\n </div>\n </div>\n );\n}\n\nexport function RefRow({\n edge,\n selectedId,\n documentId,\n onSelectChunk,\n onOpenDocument,\n onRuleStatement,\n}: {\n edge: DocEdge;\n selectedId: string;\n documentId: string;\n onSelectChunk: (id: string) => void;\n onOpenDocument?: (documentId: string, chunkId: string, title?: string) => void;\n onRuleStatement?: StatementRuling;\n}) {\n const outgoing = edge.from_id === selectedId;\n const otherId = outgoing ? edge.to_id : edge.from_id;\n const otherTitle = outgoing ? edge.to_title : edge.from_title;\n const otherDoc = outgoing ? edge.to_document_id : edge.from_document_id;\n return (\n <li className=\"doc-ref\">\n <span className=\"doc-ref-kind\">{edge.kind}</span>\n <span className=\"doc-ref-arrow\" aria-hidden>\n {outgoing ? \"→\" : \"←\"}\n </span>\n <ChunkTarget\n id={otherId}\n title={otherTitle}\n targetDocumentId={otherDoc}\n documentId={documentId}\n onSelectChunk={onSelectChunk}\n onOpenDocument={onOpenDocument}\n />\n <StatementMeta statement={edge} />\n {onRuleStatement && isProposed(edge) && (\n <StatementReview id={edge.id!} onRule={onRuleStatement} />\n )}\n </li>\n );\n}\n\n// buildGraph renders the document's edges as a Mermaid left-to-right flowchart.\n// Node ids are the chunk ids (prefixed + stripped to mermaid-safe chars); labels\n// are the endpoint titles, sanitized of mermaid metacharacters and truncated.\n// Mermaid dedups nodes by id, so re-declaring a node's label across edges is fine.\n// A statement that does not hold yet (proposed) is drawn dotted.\nexport function buildGraph(edges: DocEdge[]): string {\n const lines = [\"graph LR\"];\n for (const e of edges) {\n const from = `${nodeId(e.from_id)}[\"${label(e.from_title, e.from_id)}\"]`;\n const to = `${nodeId(e.to_id)}[\"${label(e.to_title, e.to_id)}\"]`;\n const kind = (e.kind || \"link\").replace(/[|\"]/g, \" \");\n const arrow = e.status === \"proposed\" ? \"-.->\" : \"-->\";\n lines.push(` ${from} ${arrow}|${kind}| ${to}`);\n }\n return lines.join(\"\\n\");\n}\n\n// graphEndpoint maps a drawn node back to the chunk it stands for, with the\n// document that chunk lives in — what a click on the node needs to follow it.\nexport function graphEndpoint(\n edges: DocEdge[],\n node: string,\n): { id: string; documentId?: string; title?: string } | undefined {\n for (const e of edges) {\n if (nodeId(e.from_id) === node) {\n return { id: e.from_id, documentId: e.from_document_id, title: e.from_title };\n }\n if (nodeId(e.to_id) === node) {\n return { id: e.to_id, documentId: e.to_document_id, title: e.to_title };\n }\n }\n return undefined;\n}\n\nexport function nodeId(id: string): string {\n return \"n\" + id.replace(/[^a-zA-Z0-9]/g, \"\");\n}\n\nfunction label(title: string | undefined, id: string): string {\n const base = (title ?? \"\").replace(/[\"[\\]{}|<>]/g, \" \").replace(/\\s+/g, \" \").trim();\n const text = base || id.slice(0, 6);\n return text.length > 30 ? text.slice(0, 29) + \"…\" : text;\n}\n","import { useCallback, useEffect, useRef, useState, type ReactNode } from \"react\";\n\n// StackSplitter is Splitter turned on its side: two children stacked, with a\n// draggable horizontal handle between them. The BOTTOM pane's height is owned\n// in state and (with `storageKey`) remembered per browser. The top pane takes\n// the rest, so when the column grows it is the top pane that grows.\n//\n// Used in the document viewer between a chunk's text and its links: a chunk\n// with many references used to push its own text down to a sliver, since the\n// links took their full height and only the text scrolled.\n\nexport interface StackSplitterProps {\n children: [ReactNode, ReactNode];\n /** Initial bottom-pane height in px, until the reader drags or a remembered\n * value is restored. */\n defaultBottomHeight?: number;\n /** Neither pane is dragged smaller than these. */\n minTopHeight?: number;\n minBottomHeight?: number;\n /** localStorage key; omit for a split that resets on every mount. */\n storageKey?: string;\n className?: string;\n}\n\nconst HANDLE_HEIGHT = 6;\n\n/** clampBottom keeps a dragged bottom height inside a container of `total` px:\n * at least minBottom, and never so tall that the top pane drops below minTop. */\nexport function clampBottom(want: number, total: number, minTop: number, minBottom: number): number {\n const max = Math.max(minBottom, total - minTop - HANDLE_HEIGHT);\n return Math.round(Math.max(minBottom, Math.min(want, max)));\n}\n\nexport default function StackSplitter({\n children,\n defaultBottomHeight = 240,\n minTopHeight = 96,\n minBottomHeight = 48,\n storageKey,\n className,\n}: StackSplitterProps) {\n const [bottom, setBottom] = useState<number>(() => {\n if (storageKey) {\n try {\n const n = parseInt(localStorage.getItem(storageKey) ?? \"\", 10);\n if (Number.isFinite(n) && n >= minBottomHeight) return n;\n } catch {\n // storage blocked: the default stands for this page\n }\n }\n return defaultBottomHeight;\n });\n const containerRef = useRef<HTMLDivElement | null>(null);\n const [dragging, setDragging] = useState(false);\n\n useEffect(() => {\n if (!storageKey || dragging) return;\n try {\n localStorage.setItem(storageKey, String(bottom));\n } catch {\n // storage blocked: the split lasts for this page only\n }\n }, [storageKey, bottom, dragging]);\n\n const onPointerDown = useCallback((e: React.PointerEvent) => {\n e.preventDefault();\n setDragging(true);\n (e.target as HTMLElement).setPointerCapture(e.pointerId);\n }, []);\n\n const onPointerMove = useCallback(\n (e: React.PointerEvent) => {\n if (!dragging || !containerRef.current) return;\n const rect = containerRef.current.getBoundingClientRect();\n setBottom(clampBottom(rect.bottom - e.clientY, rect.height, minTopHeight, minBottomHeight));\n },\n [dragging, minTopHeight, minBottomHeight],\n );\n\n const onPointerUp = useCallback((e: React.PointerEvent) => {\n setDragging(false);\n try {\n (e.target as HTMLElement).releasePointerCapture(e.pointerId);\n } catch {\n // capture already lost; nothing to release\n }\n }, []);\n\n return (\n <div\n ref={containerRef}\n className={`stack-splitter ${className ?? \"\"} ${dragging ? \"dragging\" : \"\"}`}\n style={{\n // CSS clamps a remembered height again against the container as it is\n // now (a since-shrunk window, or the viewer embedded in a smaller pane).\n gridTemplateRows: `minmax(${minTopHeight}px, 1fr) ${HANDLE_HEIGHT}px min(${bottom}px, calc(100% - ${minTopHeight + HANDLE_HEIGHT}px))`,\n }}\n >\n <div className=\"stack-splitter-pane stack-splitter-top\">{children[0]}</div>\n <div\n className=\"stack-splitter-handle\"\n role=\"separator\"\n aria-orientation=\"horizontal\"\n aria-valuenow={bottom}\n title=\"Drag to share the space between the text and its links\"\n onPointerDown={onPointerDown}\n onPointerMove={onPointerMove}\n onPointerUp={onPointerUp}\n onPointerCancel={onPointerUp}\n />\n <div className=\"stack-splitter-pane stack-splitter-bottom\">{children[1]}</div>\n </div>\n );\n}\n","// DocUnavailable stands in for a document that could not be read: deleted, in a\n// scope other than the one being browsed, or not the reader's to see. It is\n// reached most easily by following a reference — an edge outlives the document\n// it points at — and it has to say so in place, because the alternative is an\n// empty pane that looks like a viewer bug. The host's trail stays above it, so\n// the way back is still there.\nexport interface DocUnavailableProps {\n documentId: string;\n scope: string;\n // The runtime's own reason, when it gave one.\n detail?: string;\n}\n\nexport default function DocUnavailable({ documentId, scope, detail }: DocUnavailableProps) {\n return (\n <div className=\"doc-unavailable\" role=\"alert\">\n <p className=\"doc-unavailable-lead\">This document can’t be opened.</p>\n <p>\n It may have been deleted, live in a scope other than <code>{scope}</code>, or not be\n yours to read.\n </p>\n <p className=\"doc-unavailable-detail\">\n <code>{documentId}</code>\n {detail && <> — {detail}</>}\n </p>\n </div>\n );\n}\n","import { useCallback, useEffect, useId, useRef, useState, type KeyboardEvent } from \"react\";\nimport type { BrowseScope, DocScope } from \"../types\";\nimport { useExplorerData, type ExplorerDataLayer } from \"../lib/dataLayer\";\nimport { fileStem, saveBlob, type RenderFormat } from \"../lib/download\";\n\n/** One entry of the document's download menu. */\nexport type DownloadKind = \"pdf\" | \"docx\" | \"odt\" | \"epub\" | \"html\" | \"md\" | \"canvas\";\n\ninterface DownloadEntry {\n kind: DownloadKind;\n label: string;\n title: string;\n // rendered: the runtime renders the file (RFC GR) — needs documentExportFile.\n rendered: boolean;\n}\n\nconst ENTRIES: DownloadEntry[] = [\n { kind: \"pdf\", label: \"PDF\", title: \"Render the whole document as a PDF file\", rendered: true },\n { kind: \"docx\", label: \"Word (.docx)\", title: \"Render the whole document as a Word document\", rendered: true },\n { kind: \"odt\", label: \"OpenDocument (.odt)\", title: \"Render the whole document as an OpenDocument text file\", rendered: true },\n { kind: \"epub\", label: \"E-book (.epub)\", title: \"Render the whole document as an EPUB e-book\", rendered: true },\n { kind: \"html\", label: \"HTML\", title: \"Render the whole document as a web page\", rendered: true },\n {\n kind: \"md\",\n label: \"Markdown (.md)\",\n title: \"Download the whole document as Markdown, with the metadata comments that let it be imported back\",\n rendered: false,\n },\n {\n kind: \"canvas\",\n label: \"Canvas (.canvas)\",\n title: \"Download the whole document as a node/edge canvas graph (.canvas)\",\n rendered: false,\n },\n];\n\n/** The entries the menu offers for a data layer: the rendered formats only when\n * it can fetch a rendered file. */\nexport function downloadEntries(data: Pick<ExplorerDataLayer, \"documentExportFile\">): DownloadEntry[] {\n return ENTRIES.filter((e) => !e.rendered || !!data.documentExportFile);\n}\n\n/** Fetch one download through the data layer and hand it to the browser.\n * .md and .canvas keep their own exports (the round-trippable Markdown with\n * metadata comments, the canvas graph); the rest are rendered by the runtime. */\nexport async function runDownload(\n data: ExplorerDataLayer,\n kind: DownloadKind,\n documentId: string,\n scope: DocScope,\n browse: BrowseScope | undefined,\n title: string | undefined,\n save: (blob: Blob, filename: string) => void = saveBlob,\n): Promise<void> {\n if (kind === \"md\") {\n const r = await data.documentExportMd(documentId, scope, true, browse);\n save(new Blob([r.markdown], { type: \"text/markdown\" }), fileStem(r.title) + \".md\");\n return;\n }\n if (kind === \"canvas\") {\n const r = await data.documentExportCanvas(documentId, scope, browse);\n save(new Blob([JSON.stringify(r.canvas, null, 2)], { type: \"application/json\" }), fileStem(title) + \".canvas\");\n return;\n }\n if (!data.documentExportFile) throw new Error(\"this connection cannot download rendered files\");\n const format: RenderFormat = kind;\n const r = await data.documentExportFile(documentId, scope, format, browse);\n // The server names the file; without a name, the title and the format.\n save(r.blob, r.filename || fileStem(title) + \".\" + format);\n}\n\nexport interface DownloadMenuProps {\n documentId: string;\n scope: DocScope;\n browse?: BrowseScope;\n /** The document's title, for a file name the server does not supply. */\n title?: string;\n onError: (message: string) => void;\n}\n\n// DownloadMenu is the document toolbar's one \"download\" control: a menu button\n// listing every file the document can be downloaded as.\n//\n// Follows the ARIA menu-button pattern: Enter / Space / ArrowDown open onto the\n// first item (ArrowUp onto the last), the arrows wrap, Home / End jump, Escape\n// closes and returns focus to the button, Tab and an outside click close it.\n// While a download runs (a PDF render can take seconds) the button is disabled\n// and names what it is fetching.\nexport default function DownloadMenu({ documentId, scope, browse, title, onError }: DownloadMenuProps) {\n const data = useExplorerData();\n const entries = downloadEntries(data);\n // null = closed; otherwise the index to focus on opening.\n const [openAt, setOpenAt] = useState<number | null>(null);\n const open = openAt !== null;\n const [busy, setBusy] = useState<DownloadKind | null>(null);\n const rootRef = useRef<HTMLDivElement>(null);\n const buttonRef = useRef<HTMLButtonElement>(null);\n const itemRefs = useRef<(HTMLButtonElement | null)[]>([]);\n const menuId = useId();\n\n useEffect(() => {\n if (openAt !== null) itemRefs.current[openAt]?.focus();\n }, [openAt]);\n\n useEffect(() => {\n if (!open) return;\n const onDown = (e: MouseEvent) => {\n if (rootRef.current && !rootRef.current.contains(e.target as Node)) setOpenAt(null);\n };\n document.addEventListener(\"mousedown\", onDown);\n return () => document.removeEventListener(\"mousedown\", onDown);\n }, [open]);\n\n const choose = useCallback(\n async (kind: DownloadKind) => {\n setOpenAt(null);\n buttonRef.current?.focus();\n setBusy(kind);\n try {\n await runDownload(data, kind, documentId, scope, browse, title);\n } catch (e) {\n onError(e instanceof Error ? e.message : String(e));\n } finally {\n setBusy(null);\n }\n },\n [data, documentId, scope, browse, title, onError],\n );\n\n const focusItem = (i: number) => itemRefs.current[(i + entries.length) % entries.length]?.focus();\n\n const onItemKeyDown = (e: KeyboardEvent<HTMLButtonElement>, i: number) => {\n switch (e.key) {\n case \"ArrowDown\":\n e.preventDefault();\n focusItem(i + 1);\n break;\n case \"ArrowUp\":\n e.preventDefault();\n focusItem(i - 1);\n break;\n case \"Home\":\n e.preventDefault();\n focusItem(0);\n break;\n case \"End\":\n e.preventDefault();\n focusItem(entries.length - 1);\n break;\n case \"Escape\":\n e.preventDefault();\n setOpenAt(null);\n buttonRef.current?.focus();\n break;\n case \"Tab\":\n setOpenAt(null);\n break;\n }\n };\n\n const busyLabel = busy ? ENTRIES.find((e) => e.kind === busy)?.label : undefined;\n\n return (\n <div className=\"doc-download-menu\" ref={rootRef}>\n <button\n ref={buttonRef}\n type=\"button\"\n className={open ? \"active\" : \"\"}\n title={busyLabel ? `Preparing ${busyLabel}…` : \"Download the whole document as a file\"}\n aria-haspopup=\"menu\"\n aria-expanded={open}\n aria-controls={open ? menuId : undefined}\n aria-busy={busy !== null}\n disabled={busy !== null}\n onClick={() => setOpenAt(open ? null : 0)}\n onKeyDown={(e) => {\n if (e.key === \"ArrowDown\") {\n e.preventDefault();\n setOpenAt(0);\n } else if (e.key === \"ArrowUp\") {\n e.preventDefault();\n setOpenAt(entries.length - 1);\n } else if (e.key === \"Escape\" && open) {\n e.preventDefault();\n setOpenAt(null);\n }\n }}\n >\n {busyLabel ? `↓ ${busyLabel}…` : \"↓ download ▾\"}\n </button>\n {open && (\n <div className=\"doc-download-list\" role=\"menu\" id={menuId} aria-label=\"Download as\">\n {entries.map((entry, i) => (\n <button\n key={entry.kind}\n ref={(el) => {\n itemRefs.current[i] = el;\n }}\n type=\"button\"\n role=\"menuitem\"\n tabIndex={-1}\n title={entry.title}\n data-kind={entry.kind}\n onClick={() => void choose(entry.kind)}\n onKeyDown={(e) => onItemKeyDown(e, i)}\n >\n {entry.label}\n </button>\n ))}\n </div>\n )}\n </div>\n );\n}\n","import { useEffect, useState } from \"react\";\nimport type { BrowseScope, ChunkRevision, DocScope } from \"../types\";\nimport { useExplorerData } from \"../lib/dataLayer\";\n\n// HistoryModal is the RFC BS read-only edit-history surface for one chunk. It\n// lists the chunk's revisions (number + time + actor); clicking a revision shows\n// that version's body verbatim, and a from→to picker renders a unified diff\n// between any two. Restore is deliberately NOT here (this pass is read-only) —\n// mirroring ChunkEditorModal, which owns the write path.\nexport interface HistoryModalProps {\n chunkId: string;\n chunkTitle?: string;\n scope: DocScope;\n // browse (RFC AS) — read the history under the browsed subject's document.\n browse?: BrowseScope;\n onClose: () => void;\n}\n\n// Which output pane is showing: a single version's body, or a two-revision diff.\ntype OutputMode = \"none\" | \"version\" | \"diff\";\n\n// formatTs renders a revision timestamp. `created_at` is Unix NANOSECONDS (RFC BS\n// history), so divide by 1e6 for a JS Date; a stray string is tolerated via\n// Date.parse. Falls back to the raw value when it isn't a usable instant.\nfunction formatTs(createdAt: number): string {\n const ms = typeof createdAt === \"number\" ? createdAt / 1e6 : Date.parse(String(createdAt));\n if (!Number.isFinite(ms) || ms <= 0) return String(createdAt ?? \"\");\n return new Date(ms).toLocaleString();\n}\n\nexport default function HistoryModal({\n chunkId,\n chunkTitle,\n scope,\n browse,\n onClose,\n}: HistoryModalProps) {\n const data = useExplorerData();\n const [revisions, setRevisions] = useState<ChunkRevision[]>([]);\n const [loading, setLoading] = useState(true);\n const [err, setErr] = useState<string | null>(null);\n\n const [mode, setMode] = useState<OutputMode>(\"none\");\n const [selectedRev, setSelectedRev] = useState<number | null>(null);\n const [body, setBody] = useState<string>(\"\");\n const [busy, setBusy] = useState(false); // a version/diff fetch is in flight\n\n const [fromRev, setFromRev] = useState<number | null>(null);\n const [toRev, setToRev] = useState<number | null>(null);\n const [diff, setDiff] = useState<string>(\"\");\n\n // Load the revision list on open. Default the diff picker to the full span\n // (oldest → newest) so a single \"diff\" click is meaningful without fiddling.\n useEffect(() => {\n let cancelled = false;\n setLoading(true);\n setErr(null);\n data\n .documentHistory(chunkId, scope, browse)\n .then((r) => {\n if (cancelled) return;\n const revs = r.revisions ?? [];\n setRevisions(revs);\n if (revs.length >= 2) {\n const nums = revs.map((x) => x.revision);\n setFromRev(Math.min(...nums));\n setToRev(Math.max(...nums));\n }\n })\n .catch((e) => !cancelled && setErr(e instanceof Error ? e.message : String(e)))\n .finally(() => !cancelled && setLoading(false));\n return () => {\n cancelled = true;\n };\n }, [data, chunkId, scope, browse]);\n\n const viewVersion = async (rev: number) => {\n setErr(null);\n setBusy(true);\n setSelectedRev(rev);\n setMode(\"version\");\n try {\n const r = await data.documentGetVersion(chunkId, rev, scope, browse);\n setBody(r.body ?? \"\");\n } catch (e) {\n setErr(e instanceof Error ? e.message : String(e));\n } finally {\n setBusy(false);\n }\n };\n\n const runDiff = async () => {\n if (fromRev === null || toRev === null) return;\n setErr(null);\n setBusy(true);\n setMode(\"diff\");\n try {\n const r = await data.documentDiff(chunkId, fromRev, toRev, scope, browse);\n setDiff(r.diff ?? \"\");\n } catch (e) {\n setErr(e instanceof Error ? e.message : String(e));\n } finally {\n setBusy(false);\n }\n };\n\n return (\n <div className=\"modal-overlay\" onClick={onClose}>\n <div className=\"modal history-modal\" onClick={(e) => e.stopPropagation()}>\n <div className=\"modal-header sticky-top\">\n <h3>History{chunkTitle ? ` — ${chunkTitle}` : \"\"}</h3>\n <div className=\"modal-buttons modal-buttons-top\">\n <button type=\"button\" onClick={onClose}>\n close\n </button>\n </div>\n </div>\n {err && <div className=\"modal-err\">{err}</div>}\n\n {loading ? (\n <p className=\"doc-empty-body\">loading…</p>\n ) : revisions.length === 0 ? (\n <p className=\"doc-empty-body\">No history recorded for this chunk.</p>\n ) : (\n <>\n <div className=\"doc-hist-revs\">\n {revisions.map((rev) => (\n <button\n key={rev.revision}\n type=\"button\"\n className={\n \"doc-hist-rev\" +\n (mode === \"version\" && selectedRev === rev.revision ? \" active\" : \"\")\n }\n onClick={() => void viewVersion(rev.revision)}\n >\n <span className=\"doc-hist-rev-num\">rev {rev.revision}</span>\n <span className=\"doc-hist-rev-time\">{formatTs(rev.created_at)}</span>\n <span className=\"doc-hist-rev-actor\">{rev.actor || \"unknown\"}</span>\n </button>\n ))}\n </div>\n\n {revisions.length >= 2 && (\n <div className=\"doc-hist-diffbar\">\n <span>Compare</span>\n <select\n value={fromRev ?? \"\"}\n onChange={(e) => setFromRev(e.target.value === \"\" ? null : Number(e.target.value))}\n aria-label=\"diff from revision\"\n >\n {revisions.map((r) => (\n <option key={r.revision} value={r.revision}>\n rev {r.revision}\n </option>\n ))}\n </select>\n <span aria-hidden>→</span>\n <select\n value={toRev ?? \"\"}\n onChange={(e) => setToRev(e.target.value === \"\" ? null : Number(e.target.value))}\n aria-label=\"diff to revision\"\n >\n {revisions.map((r) => (\n <option key={r.revision} value={r.revision}>\n rev {r.revision}\n </option>\n ))}\n </select>\n <button\n type=\"button\"\n onClick={() => void runDiff()}\n disabled={busy || fromRev === null || toRev === null}\n >\n diff\n </button>\n </div>\n )}\n\n <div className=\"doc-hist-output\">\n {busy ? (\n <p className=\"doc-empty-body\">loading…</p>\n ) : mode === \"diff\" ? (\n <DiffView text={diff} />\n ) : mode === \"version\" ? (\n <pre className=\"md-pre doc-hist-version\">\n <code>{body || \"(empty)\"}</code>\n </pre>\n ) : (\n <p className=\"doc-empty-body\">\n Select a revision to view it, or compare two.\n </p>\n )}\n </div>\n </>\n )}\n </div>\n </div>\n );\n}\n\n// DiffView renders a unified diff, coloring added (+) / removed (-) / hunk (@@)\n// lines. `+++`/`---` file headers stay neutral so they don't read as content\n// changes. Line breaks come from the explicit \"\\n\" text nodes inside the <pre>,\n// so spacing stays single (a per-line <div> would double it).\nfunction DiffView({ text }: { text: string }) {\n if (!text.trim()) return <p className=\"doc-empty-body\">(no differences)</p>;\n const lines = text.split(\"\\n\");\n return (\n <pre className=\"md-pre doc-hist-diff\">\n {lines.map((ln, i) => {\n const cls =\n ln.startsWith(\"+\") && !ln.startsWith(\"+++\")\n ? \"diff-add\"\n : ln.startsWith(\"-\") && !ln.startsWith(\"---\")\n ? \"diff-del\"\n : ln.startsWith(\"@@\")\n ? \"diff-hunk\"\n : \"\";\n return (\n <span key={i} className={cls}>\n {ln}\n {\"\\n\"}\n </span>\n );\n })}\n </pre>\n );\n}\n","// remarkBareBreak turns a bare <br> in a chunk body into a line break. An\n// extraction writes one between a table cell's paragraphs, the only break a\n// GFM cell can hold. react-markdown renders no raw HTML (no rehype-raw), so\n// it would otherwise drop the tag and run the paragraphs together. Only the\n// bare tag is read: any other HTML, a <br> with attributes included, stays\n// as react-markdown leaves it. The runtime's renderer reads the same tag the\n// same way (internal/files/render isBareBreak).\n\ntype MdNode = { type: string; value?: string; children?: MdNode[] };\n\nconst BARE_BREAK = /^<br\\s*\\/?>$/i;\n\nfunction walk(node: MdNode): void {\n const kids = node.children;\n if (!kids) return;\n for (let i = 0; i < kids.length; i++) {\n const k = kids[i];\n if (k.type === \"html\" && BARE_BREAK.test(k.value ?? \"\")) {\n kids[i] = { type: \"break\" };\n } else {\n walk(k);\n }\n }\n}\n\nexport default function remarkBareBreak() {\n return (tree: MdNode) => walk(tree);\n}\n","import ReactMarkdown from \"react-markdown\";\nimport remarkGfm from \"remark-gfm\";\nimport type { Components } from \"react-markdown\";\nimport MermaidDiagram from \"./Mermaid\";\nimport remarkBareBreak from \"../lib/remarkBareBreak\";\n\n// Markdown renders a chunk body as GitHub-flavored Markdown (RFC BN): headings,\n// paragraphs, inline styles, links, fenced code, blockquotes, lists, TABLES, and\n// ```mermaid diagrams. It uses react-markdown + remark-gfm; react-markdown is\n// safe by default (it does not emit raw HTML — no rehype-raw — and its default\n// urlTransform strips javascript:/other dangerous hrefs). ```mermaid fences\n// render through the shared MermaidDiagram (lazy, securityLevel:\"strict\",\n// graceful fallback to a code block). A bare <br> (a table cell's paragraph\n// break, as an extraction writes it) is a line break (remarkBareBreak).\n\nexport default function Markdown({ source }: { source: string }) {\n return (\n <div className=\"md\">\n <ReactMarkdown remarkPlugins={[remarkGfm, remarkBareBreak]} components={MD_COMPONENTS}>\n {source}\n </ReactMarkdown>\n </div>\n );\n}\n\nconst MD_COMPONENTS: Components = {\n // react-markdown already sanitized the href; add target/rel for external links.\n a({ href, children }) {\n const url = href ?? \"\";\n const external = /^https?:\\/\\//i.test(url);\n return (\n <a href={url} target={external ? \"_blank\" : undefined} rel={external ? \"noopener noreferrer\" : undefined}>\n {children}\n </a>\n );\n },\n // Let the code renderer own the block wrapper so a mermaid fence isn't wrapped\n // in a <pre> (and a normal code block gets exactly one <pre>).\n pre({ children }) {\n return <>{children}</>;\n },\n code({ className, children }) {\n const lang = /language-(\\w+)/.exec(className ?? \"\")?.[1];\n const raw = String(children ?? \"\");\n if (lang === \"mermaid\") {\n return <MermaidDiagram code={raw.replace(/\\n$/, \"\")} />;\n }\n // Fenced block (has a language) or a multi-line block without one → <pre>.\n if (lang || raw.includes(\"\\n\")) {\n return (\n <pre className=\"md-pre\">\n <code className={className}>{children}</code>\n </pre>\n );\n }\n return <code>{children}</code>; // inline\n },\n};\n","import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from \"react\";\nimport type {\n Annotation,\n AnnotationLevel,\n AnnotationTarget,\n AssistantContext,\n BrowseScope,\n ChunkDetail,\n ChunkRow,\n DocEdge,\n DocScope,\n Principal,\n} from \"../types\";\nimport { readImageAsBase64, imageFileFromPaste } from \"../lib/imageUpload\";\nimport { useExplorerData } from \"../lib/dataLayer\";\nimport { loadDocumentEdges } from \"../lib/edgePages\";\nimport { landingChunk, type DocLocation } from \"../lib/docTrail\";\nimport { chunkAncestors } from \"../lib/chunkAncestry\";\nimport { isSubjectRoot } from \"../lib/subjectType\";\nimport { bulkReviewScope, documentProposals, reviewPanel } from \"../lib/bulkReview\";\nimport { annotationLevelFor, annotationsApply, loadAnnotations } from \"../lib/annotation\";\nimport {\n docColor,\n effectiveScheme,\n tintStyle,\n type DocumentMeta,\n} from \"../lib/colorScheme\";\nimport DocumentChunkTree, {\n buildChunkTree,\n findChunkNode,\n type ChunkNode,\n} from \"./DocumentChunkTree\";\nimport AnnotationPanel, { AnnotationBrief } from \"./AnnotationPanel\";\nimport ChunkEditorModal from \"./ChunkEditorModal\";\nimport SubjectTypeModal from \"./SubjectTypeModal\";\nimport Classification from \"./Classification\";\nimport ColorSchemeEditor from \"./ColorSchemeEditor\";\nimport IdCopy from \"./IdCopy\";\nimport Connections from \"./Connections\";\nimport CrossReferences from \"./CrossReferences\";\nimport StackSplitter from \"./StackSplitter\";\nimport DocUnavailable from \"./DocUnavailable\";\nimport DownloadMenu from \"./DownloadMenu\";\nimport HistoryModal from \"./HistoryModal\";\nimport Markdown from \"./Markdown\";\nimport MermaidDiagram from \"./Mermaid\";\nimport Splitter from \"./Splitter\";\n\n// imageAlt derives an image chunk's alt text: the fields.alt override, else the\n// chunk title, else a generic label (RFC BO).\nfunction imageAlt(chunk: ChunkDetail): string {\n const f = (chunk.fields ?? {}) as { alt?: unknown };\n if (typeof f.alt === \"string\" && f.alt.trim() !== \"\") return f.alt;\n return chunk.title || \"image\";\n}\n\n// DocumentViewerBody is the read-mostly surface for one chunked-graph document\n// (RFC AK). The chunk tree stays on the left for navigation; the right pane\n// renders the SELECTED chunk in one of two views, toggled per selection:\n// - chunk — the selected chunk's own body (structured, per-chunk).\n// - markdown — the selected chunk + its sub-chunks assembled into one Markdown\n// document. Selecting the ROOT chunk therefore renders the whole\n// document; selecting a section renders just that part.\n// Structural editing (move / link / delete chunks) is deliberately NOT here.\n//\n// This is the context-consuming body: it reads the injected ExplorerDataLayer\n// via useExplorerData() and is embedded by both the standalone <DocumentViewer>\n// root and the <PathExplorer> tree — neither re-wraps it in a data provider.\nexport interface DocumentViewerBodyProps {\n documentId: string;\n scope: DocScope;\n // titleHint shows immediately (e.g. the Path-tree name) until the root chunk\n // title loads.\n titleHint?: string;\n // browse (RFC AS) selects whose subject's document to read — threaded into the\n // off-run document calls. Unset → the caller's own subject (default).\n browse?: BrowseScope;\n // principal — only `subject` is read; passed into the renderAssistant context.\n principal?: Principal;\n // renderAssistant — an OPTIONAL host-provided Document Assistant slot. When\n // provided, an \"assistant\" toggle appears and this renders into the panel;\n // when omitted, no assistant affordance is shown and no run-stream machinery\n // is pulled in. The host owns the run: it reads {documentId, scope, subject}.\n renderAssistant?: (ctx: AssistantContext) => ReactNode;\n // initialChunkId — the chunk to land on instead of the root, for a document\n // opened AT a chunk (a followed reference, or a return along the trail). It is\n // read when the document loads; the host remounts the body to land again.\n initialChunkId?: string;\n // onOpenDocument — the host's \"leave this document\" handler. `target` is the\n // referenced document + chunk; `from` is this document as the reader leaves it\n // (the selected chunk and the loaded title), which is what a way back needs.\n // Omitted → cross-document targets are labels only.\n onOpenDocument?: (target: DocLocation, from: DocLocation) => void;\n // onTitle reports this document's title once its root chunk has loaded, so a\n // host that opened it by id can name it.\n onTitle?: (documentId: string, title: string) => void;\n // onChunkSelect reports the chunk the reader is on as it changes (undefined =\n // the document's root), so a host navigator can follow the chunk tree.\n onChunkSelect?: (chunkId: string | undefined) => void;\n // focusChunk moves the selection inside the mounted document without a\n // remount: each new `seq` selects `chunkId` (absent = the root). A host\n // navigator uses it when the reader picks another chunk of the open document.\n focusChunk?: { chunkId?: string; seq: number };\n // onRegenerateAnnotation — the host's way to have an annotation written again\n // (it owns the run). Omitted → no Regenerate. Its promise settling reloads the\n // annotation; a rejection is shown in the panel.\n onRegenerateAnnotation?: (target: AnnotationTarget) => void | Promise<void>;\n // canEditAnnotations — whether to offer Edit (the operator plane writes\n // annotations by hand; the runtime refuses anyone else). Default false.\n canEditAnnotations?: boolean;\n // onAnnotationChanged — told after an edit or a regenerate settles, so a host\n // showing briefs elsewhere (the Path tree) can read them again.\n onAnnotationChanged?: () => void;\n}\n\n// View mode for the selected-chunk pane (not the whole document).\ntype Mode = \"chunks\" | \"markdown\";\n\nexport default function DocumentViewerBody({\n documentId,\n scope,\n titleHint,\n browse: browseProp,\n principal,\n renderAssistant,\n initialChunkId,\n onOpenDocument,\n onTitle,\n onChunkSelect,\n focusChunk,\n onRegenerateAnnotation,\n canEditAnnotations,\n onAnnotationChanged,\n}: DocumentViewerBodyProps) {\n const data = useExplorerData();\n\n // Memoize browse on its primitives so a parent passing an inline object\n // literal (`browse={{scopeId}}`) doesn't churn the fetch effects every render.\n const browse = useMemo<BrowseScope | undefined>(\n () =>\n browseProp && (browseProp.scopeId || browseProp.tenant)\n ? { scopeId: browseProp.scopeId, tenant: browseProp.tenant }\n : undefined,\n [browseProp?.scopeId, browseProp?.tenant],\n );\n\n const [chunks, setChunks] = useState<ChunkRow[]>([]);\n const [selectedId, setSelectedId] = useState<string | undefined>(undefined);\n const [selectedDetail, setSelectedDetail] = useState<ChunkDetail | null>(null);\n const [mode, setMode] = useState<Mode>(\"chunks\");\n const [subtreeMd, setSubtreeMd] = useState<string | null>(null);\n // RFC BO — an image chunk's blob object-URL (fetched with auth) + a load error.\n const [imageUrl, setImageUrl] = useState<string | null>(null);\n const [imageErr, setImageErr] = useState<string | null>(null);\n const fileInputRef = useRef<HTMLInputElement>(null); // hidden upload input (RFC BO)\n const [editing, setEditing] = useState<ChunkDetail | null>(null);\n const [retyping, setRetyping] = useState<ChunkDetail | null>(null);\n const [historyOpen, setHistoryOpen] = useState(false); // RFC BS chunk history modal\n const [confirmDelete, setConfirmDelete] = useState(false); // RFC BP delete confirm\n const [err, setErr] = useState<string | null>(null);\n const [loading, setLoading] = useState(false);\n // Which document the chunk list on hand belongs to, and why a load failed —\n // together they tell \"still loading\" from \"cannot be read\".\n const [loadedFor, setLoadedFor] = useState<string | undefined>(undefined);\n const [loadErr, setLoadErr] = useState<string | null>(null);\n const [reload, setReload] = useState(0);\n const [assistantOpen, setAssistantOpen] = useState(false);\n const [meta, setMeta] = useState<DocumentMeta | null>(null);\n const [colorsOpen, setColorsOpen] = useState(false);\n const [edges, setEdges] = useState<DocEdge[]>([]);\n // The edge load stopped before the end of the list (its page cap).\n const [edgesIncomplete, setEdgesIncomplete] = useState(false);\n // Bumped after an operator rules on a proposed statement: refetches the edges\n // (and an open Connections panel) without reloading the whole document.\n const [edgesReload, setEdgesReload] = useState(0);\n // RFC FO — the Classify panel: 1 open (each opening runs a fresh report), 0\n // closed. rootFields is the root chunk's fields, where a pending\n // classification waits.\n const [classifyKey, setClassifyKey] = useState(0);\n const [rootFields, setRootFields] = useState<unknown>(undefined);\n // The annotations of the document (its root chunk's records) and of the\n // selected chunk when that is not the root. Tenant scope only; otherwise\n // they stay empty and nothing is fetched.\n const [docAnnotations, setDocAnnotations] = useState<Annotation[]>([]);\n const [chunkAnnotations, setChunkAnnotations] = useState<Annotation[]>([]);\n const [annotationReload, setAnnotationReload] = useState(0);\n\n const refresh = useCallback(() => setReload((n) => n + 1), []);\n\n // Host callbacks + the landing chunk through refs: none of them should re-run\n // a fetch effect when a host passes a fresh closure each render.\n const initialChunkRef = useRef(initialChunkId);\n initialChunkRef.current = initialChunkId;\n const onTitleRef = useRef(onTitle);\n onTitleRef.current = onTitle;\n\n const tree = useMemo(() => buildChunkTree(chunks), [chunks]);\n const rootTitle = useMemo(() => {\n const root = chunks.find((c) => !c.parent_id);\n return root?.title || titleHint || \"document\";\n }, [chunks, titleHint]);\n const selectedIsRoot = useMemo(\n () => !!selectedDetail && !selectedDetail.parent_id,\n [selectedDetail],\n );\n // The levels above the selected chunk, root first. The ↑/↓ buttons reorder a\n // chunk among its siblings, so climbing back up gets its own breadcrumb.\n const ancestors = useMemo(\n () => chunkAncestors(chunks, selectedDetail?.id),\n [chunks, selectedDetail],\n );\n\n // Color (RFC BN). rootChunkId comes from the meta (or the loaded root chunk);\n // chunkStatuses seeds the editor's per-status pickers; the toolbar tints to the\n // document's own doc.<type>.<status> color when coloring is enabled.\n const rootChunkId = useMemo(\n () => meta?.root_chunk_id ?? chunks.find((c) => !c.parent_id)?.id,\n [meta, chunks],\n );\n // Report the chunk the reader is on; the root reads as the document itself.\n const onChunkSelectRef = useRef(onChunkSelect);\n onChunkSelectRef.current = onChunkSelect;\n useEffect(() => {\n if (!selectedId) return;\n onChunkSelectRef.current?.(selectedId === rootChunkId ? undefined : selectedId);\n }, [selectedId, rootChunkId]);\n\n const chunkStatuses = useMemo(\n () => [...new Set(chunks.map((c) => c.status).filter((s): s is string => !!s))],\n [chunks],\n );\n const colorEnabled = !!meta?.color_enabled;\n // Chunk ids with at least one edge → a 🔗 badge on those tiles.\n const linkedIds = useMemo(() => {\n const s = new Set<string>();\n for (const e of edges) {\n s.add(e.from_id);\n s.add(e.to_id);\n }\n return s;\n }, [edges]);\n // The document's own colour: the toolbar's tint, the root row's in the chunk\n // tree, and the wash a chunk without a status colour inherits.\n const documentColor = useMemo(\n () => (colorEnabled ? docColor(meta?.type, meta?.status, effectiveScheme(meta?.color_scheme)) : undefined),\n [colorEnabled, meta?.type, meta?.status, meta?.color_scheme],\n );\n const toolbarTint = useMemo(() => tintStyle(documentColor), [documentColor]);\n\n // Load the chunk list when the document / scope / reload changes. Default the\n // selection to the root chunk.\n useEffect(() => {\n let cancelled = false;\n setLoading(true);\n setErr(null);\n setLoadErr(null);\n data\n .documentQueryChunks(documentId, scope, browse)\n .then((resp) => {\n if (cancelled) return;\n const rows = resp.chunks ?? [];\n setChunks(rows);\n setLoadedFor(`${scope}:${documentId}`);\n setSelectedId((cur) => cur ?? landingChunk(rows, initialChunkRef.current));\n })\n .catch((e) => {\n if (cancelled) return;\n // Drop the previous document's chunks: a failed load must not leave them\n // on screen under the new document's name.\n setChunks([]);\n setLoadErr(e instanceof Error ? e.message : String(e));\n })\n .finally(() => !cancelled && setLoading(false));\n return () => {\n cancelled = true;\n };\n }, [data, documentId, scope, reload, browse]);\n\n // A document always has a root chunk, so a load that failed — or answered with\n // no chunks at all — is a document that is not there to read (deleted, another\n // scope, no access). Said in place rather than left as an empty pane.\n const unavailable =\n !loading &&\n (loadErr !== null || (loadedFor === `${scope}:${documentId}` && chunks.length === 0));\n\n // Report the title once THIS document's root chunk is on hand (the list still\n // holds the previous document's rows until the new load lands).\n const loadedTitle = useMemo(\n () => chunks.find((c) => !c.parent_id && c.document_id === documentId)?.title,\n [chunks, documentId],\n );\n useEffect(() => {\n if (loadedTitle) onTitleRef.current?.(documentId, loadedTitle);\n }, [documentId, loadedTitle]);\n\n // Load the document's color metadata (RFC BN) alongside the chunk list. It\n // drives the chunk-tree tint, the toolbar tint, and seeds the color editor.\n // Best-effort — a failure just leaves the document uncolored.\n useEffect(() => {\n let cancelled = false;\n data\n .documentGet(documentId, scope, browse)\n .then((m) => !cancelled && setMeta(m))\n .catch(() => !cancelled && setMeta(null));\n return () => {\n cancelled = true;\n };\n }, [data, documentId, scope, reload, browse]);\n\n // Load the cross-reference edges (RFC BN P4), every page up to the cap —\n // powers the 🔗 tile badge, the References list, and the relationship graph.\n // Best-effort.\n useEffect(() => {\n let cancelled = false;\n loadDocumentEdges(data, documentId, scope, browse)\n .then((r) => {\n if (cancelled) return;\n setEdges(r.edges);\n setEdgesIncomplete(r.incomplete);\n })\n .catch(() => {\n if (cancelled) return;\n setEdges([]);\n setEdgesIncomplete(false);\n });\n return () => {\n cancelled = true;\n };\n }, [data, documentId, scope, reload, browse, edgesReload]);\n\n // RFC FO — the root chunk's fields, for the pending-classification block. The\n // chunk list carries no fields, so the root is fetched on its own — and only\n // when the data layer can accept a classification (nothing to act on\n // otherwise). Best-effort: a failure just shows no pending block.\n useEffect(() => {\n if (!rootChunkId || !data.documentAcceptClassification) {\n setRootFields(undefined);\n return;\n }\n let cancelled = false;\n data\n .documentGetChunk(rootChunkId, scope, browse)\n .then((d) => !cancelled && setRootFields(d.document_id === documentId ? d.fields : undefined))\n .catch(() => !cancelled && setRootFields(undefined));\n return () => {\n cancelled = true;\n };\n }, [data, documentId, rootChunkId, scope, reload, browse]);\n\n // The document's annotation, read from its root chunk. Best-effort: a failed\n // read shows no annotation rather than an error over the document.\n useEffect(() => {\n if (!rootChunkId || !annotationsApply(scope)) {\n setDocAnnotations([]);\n return;\n }\n let cancelled = false;\n loadAnnotations(data, rootChunkId, scope, browse)\n .then((r) => !cancelled && setDocAnnotations(r))\n .catch(() => !cancelled && setDocAnnotations([]));\n return () => {\n cancelled = true;\n };\n }, [data, rootChunkId, scope, reload, browse, annotationReload]);\n\n // The selected chunk's own branch annotation (the root's is the document's,\n // above).\n useEffect(() => {\n if (!selectedId || selectedId === rootChunkId || !annotationsApply(scope)) {\n setChunkAnnotations([]);\n return;\n }\n let cancelled = false;\n setChunkAnnotations([]);\n loadAnnotations(data, selectedId, scope, browse)\n .then((r) => !cancelled && setChunkAnnotations(r))\n .catch(() => !cancelled && setChunkAnnotations([]));\n return () => {\n cancelled = true;\n };\n }, [data, selectedId, rootChunkId, scope, reload, browse, annotationReload]);\n\n // Edit and Regenerate. Edit needs a data layer that can write one; Regenerate\n // needs the host's callback. Neither is offered outside the tenant scope.\n const saveAnnotation = useMemo(() => {\n if (!canEditAnnotations || !data.documentSetAnnotation || !annotationsApply(scope)) return undefined;\n return (chunkId: string) => async (level: AnnotationLevel, brief: string, abstract: string) => {\n await data.documentSetAnnotation!({ id: chunkId, level, brief, abstract }, scope, browse);\n setAnnotationReload((n) => n + 1);\n onAnnotationChanged?.();\n };\n }, [data, scope, browse, canEditAnnotations, onAnnotationChanged]);\n const regenerateAnnotation = useMemo(() => {\n if (!onRegenerateAnnotation || !annotationsApply(scope)) return undefined;\n return (chunkId: string) => async (level: AnnotationLevel) => {\n // A folder's record names its folder: that, not this document, is what a\n // path-level Regenerate rewrites.\n const folder = [...docAnnotations, ...chunkAnnotations].find(\n (a) => a.chunk_id === chunkId && a.level === level,\n )?.folder;\n try {\n await onRegenerateAnnotation({ documentId, chunkId, level, scope, ...(folder ? { folder } : {}) });\n } finally {\n setAnnotationReload((n) => n + 1);\n onAnnotationChanged?.();\n }\n };\n }, [onRegenerateAnnotation, documentId, scope, docAnnotations, chunkAnnotations, onAnnotationChanged]);\n // The brief under the title is the document record's; a path record on the\n // same root describes the folder, and shows only in the panel.\n // A folder's _annotation document has only the path record: that is its brief.\n const documentBrief =\n docAnnotations.find((a) => a.level === \"document\") ?? docAnnotations.find((a) => a.level === \"path\");\n // The selected chunk's records, matched by id: the detail can still be the\n // previous chunk's for a moment after the selection moves.\n const selectedAnnotations = useMemo(\n () => chunkAnnotations.filter((a) => a.chunk_id === selectedDetail?.id),\n [chunkAnnotations, selectedDetail?.id],\n );\n\n // RFC FN — the operator's ruling on a proposed statement. Offered only when the\n // data layer implements both rulings (they are optional on a custom one). A\n // refusal propagates to the row, which shows it inline.\n // Called through `data` (not detached) so a class-based data layer keeps `this`.\n const ruleStatement = useMemo(() => {\n if (!data.documentAcceptStatement || !data.documentRejectStatement) return undefined;\n return async (id: string, ok: boolean, reason?: string) => {\n if (ok) await data.documentAcceptStatement!(id, scope, browse, reason);\n else await data.documentRejectStatement!(id, reason ?? \"\", scope, browse);\n setEdgesReload((n) => n + 1);\n };\n }, [data, scope, browse]);\n\n // RFC FS — bulk review of this document's proposals in the Connections panel:\n // offered when the data layer can rule in bulk and the review routes reach\n // this document's scope (reviewPanel).\n const reviewScope = useMemo(() => bulkReviewScope(data, scope), [data, scope]);\n const proposals = useMemo(() => documentProposals(edges, documentId), [edges, documentId]);\n const onReviewChanged = useCallback(() => setEdgesReload((n) => n + 1), []);\n const review = useMemo(\n () => reviewPanel(reviewScope, proposals, edgesIncomplete, onReviewChanged),\n [reviewScope, proposals, edgesIncomplete, onReviewChanged],\n );\n\n // A host's focus request for the open document. Declared before the reset\n // below on purpose: on a document change the reset runs after it and the\n // landing chunk (initialChunkId) decides instead.\n const focusSeq = focusChunk?.seq;\n const focusRef = useRef(focusChunk);\n focusRef.current = focusChunk;\n const rootRef = useRef(rootChunkId);\n rootRef.current = rootChunkId;\n const chunksRef = useRef(chunks);\n chunksRef.current = chunks;\n useEffect(() => {\n if (focusSeq === undefined) return;\n const wanted = focusRef.current?.chunkId;\n // Once the chunk list is in, an id that is not one of this document's\n // chunks (another document's, a deleted one) lands on the root rather than\n // selecting nothing; before it is in, the request is taken as given.\n const target =\n chunksRef.current.length > 0 ? landingChunk(chunksRef.current, wanted) : (wanted ?? rootRef.current);\n if (target) setSelectedId(target);\n }, [focusSeq]);\n\n // Reset selection + view when the document changes.\n useEffect(() => {\n setSelectedId(undefined);\n setSelectedDetail(null);\n setSubtreeMd(null);\n setMode(\"chunks\");\n setMeta(null);\n setEdges([]);\n setEdgesIncomplete(false);\n setClassifyKey(0);\n setRootFields(undefined);\n setDocAnnotations([]);\n setChunkAnnotations([]);\n }, [documentId, scope]);\n\n // Fetch the selected chunk's body.\n useEffect(() => {\n if (!selectedId) {\n setSelectedDetail(null);\n return;\n }\n let cancelled = false;\n data\n .documentGetChunk(selectedId, scope, browse)\n .then((d) => !cancelled && setSelectedDetail(d))\n .catch((e) => !cancelled && setErr(e instanceof Error ? e.message : String(e)));\n return () => {\n cancelled = true;\n };\n }, [data, selectedId, scope, reload, browse]);\n\n // RFC BO — for an image chunk, fetch its bytes WITH auth into a blob object-URL\n // for <img src> (a bare <img src=/v1/...> can't carry a bearer). Revoke the URL\n // on change/unmount so blobs don't leak.\n useEffect(() => {\n const isImage = selectedDetail?.type === \"image\" || !!selectedDetail?.asset;\n if (!selectedDetail || !isImage || !data.documentAssetObjectUrl) {\n setImageUrl(null);\n setImageErr(null);\n return;\n }\n let cancelled = false;\n let url: string | null = null;\n setImageErr(null);\n data\n .documentAssetObjectUrl(selectedDetail.id, scope, browse)\n .then((u) => {\n if (cancelled) {\n URL.revokeObjectURL(u);\n return;\n }\n url = u;\n setImageUrl(u);\n })\n .catch((e) => !cancelled && setImageErr(e instanceof Error ? e.message : String(e)));\n return () => {\n cancelled = true;\n if (url) URL.revokeObjectURL(url);\n };\n }, [data, selectedDetail, scope, browse]);\n\n // Assemble the selected chunk + its sub-chunks into one Markdown string for the\n // markdown view (fetches each descendant's body; heading depth is relative to\n // the selected chunk, so it reads as a standalone part — or the whole document\n // when the root is selected). Only runs while the markdown view is active.\n useEffect(() => {\n if (mode !== \"markdown\" || !selectedId) {\n setSubtreeMd(null);\n return;\n }\n const node = findChunkNode(tree, selectedId);\n if (!node) return;\n let cancelled = false;\n const items: { node: ChunkNode; depth: number }[] = [];\n const walk = (n: ChunkNode, depth: number) => {\n items.push({ node: n, depth });\n n.children.forEach((c) => walk(c, depth + 1));\n };\n walk(node, 0);\n Promise.all(items.map((it) => data.documentGetChunk(it.node.row.id, scope, browse)))\n .then((details) => {\n if (cancelled) return;\n const md = items\n .map((it, idx) => {\n const lvl = Math.min(it.depth + 1, 6);\n const d = details[idx];\n const heading = \"#\".repeat(lvl) + \" \" + it.node.row.title;\n // RFC BO — render media child chunks correctly in the assembled view:\n // a mermaid chunk's body becomes a ```mermaid fence (so it draws);\n // an image chunk shows a placeholder (its bytes need the auth'd asset\n // GET, which the plain-string assembler can't inline).\n if (d.type === \"mermaid\" && d.body) {\n return heading + \"\\n\\n```mermaid\\n\" + d.body + \"\\n```\\n\";\n }\n if (d.type === \"image\" || d.asset) {\n const cap = d.body ? \" — \" + d.body : \"\";\n return heading + \"\\n\\n_🖼 image chunk_\" + cap + \"\\n\";\n }\n return heading + (d.body ? \"\\n\\n\" + d.body : \"\") + \"\\n\";\n })\n .join(\"\\n\");\n setSubtreeMd(md);\n })\n .catch((e) => !cancelled && setErr(e instanceof Error ? e.message : String(e)));\n return () => {\n cancelled = true;\n };\n }, [data, mode, selectedId, tree, scope, reload, browse]);\n\n const onSelect = useCallback((n: ChunkNode) => setSelectedId(n.row.id), []);\n\n // Leaving for another document: hand the host the target and a snapshot of\n // where the reader is now. The target's title is the CHUNK's — a stand-in until\n // that document loads and reports its own.\n const openDocument = useCallback(\n (targetDocumentId: string, chunkId: string, title?: string) =>\n onOpenDocument?.(\n { documentId: targetDocumentId, chunkId, title },\n { documentId, chunkId: selectedId, title: rootTitle },\n ),\n [onOpenDocument, documentId, selectedId, rootTitle],\n );\n\n // RFC BO authoring — create a media chunk under the selected chunk (or the\n // root). The runtime marks type=image via set_asset; a diagram is a plain\n // type=mermaid chunk whose body is the source.\n const canCreate = !!data.documentCreateChunk && !!rootChunkId;\n const addImageFile = useCallback(\n async (file: File) => {\n if (!data.documentCreateChunk || !data.documentSetAsset) return;\n const parent = selectedId || rootChunkId;\n if (!parent) return;\n setErr(null);\n try {\n const { mediaType, data: b64 } = await readImageAsBase64(file);\n const created = await data.documentCreateChunk(\n documentId,\n parent,\n { title: file.name || \"image\", type: \"image\" },\n scope,\n browse,\n );\n await data.documentSetAsset(created.id, mediaType, b64, file.name, scope, browse);\n refresh();\n setSelectedId(created.id);\n } catch (e) {\n setErr(e instanceof Error ? e.message : String(e));\n }\n },\n [data, documentId, scope, browse, selectedId, rootChunkId, refresh],\n );\n const addDiagram = useCallback(async () => {\n if (!data.documentCreateChunk) return;\n const parent = selectedId || rootChunkId;\n if (!parent) return;\n setErr(null);\n try {\n const created = await data.documentCreateChunk(\n documentId,\n parent,\n { title: \"Diagram\", type: \"mermaid\", body: \"graph TD\\n A[Start] --> B[End]\" },\n scope,\n browse,\n );\n refresh();\n setSelectedId(created.id);\n setEditing(created); // open the editor (with live preview) on the new diagram\n } catch (e) {\n setErr(e instanceof Error ? e.message : String(e));\n }\n }, [data, documentId, scope, browse, selectedId, rootChunkId, refresh]);\n\n // RFC BP — \"+ text\": a plain text chunk immediately AFTER the selected chunk\n // (via after_id) when a non-root chunk is selected; otherwise appended under\n // the root. Opens the editor on the new chunk.\n const addText = useCallback(async () => {\n if (!data.documentCreateChunk) return;\n const insertAfter = selectedId && !selectedIsRoot ? selectedId : undefined;\n const parent = selectedId || rootChunkId;\n if (!parent) return;\n setErr(null);\n try {\n const created = await data.documentCreateChunk(\n documentId,\n insertAfter ? \"\" : parent, // after_id resolves the parent server-side\n { title: \"Text\", body: \"\" },\n scope,\n browse,\n insertAfter,\n );\n refresh();\n setSelectedId(created.id);\n setEditing(created);\n } catch (e) {\n setErr(e instanceof Error ? e.message : String(e));\n }\n }, [data, documentId, scope, browse, selectedId, selectedIsRoot, rootChunkId, refresh]);\n\n // \"+ child\": a chunk NESTED UNDER the selected one.\n //\n // The viewer had no way to do this. \"+ text\" inserts a SIBLING (after_id), which is\n // right for prose flow and wrong for structure — so a document's hierarchy could only\n // ever be created by import_md or by an agent, and every attempt to nest something\n // through the UI silently produced a sibling instead. That made the ontology's\n // subclasses (a child chunk is a subclass) unauthorable by the operator who owns them:\n // selecting `project` and adding a type put it BESIDE project, at the top level.\n //\n // Passing parent_id with no after_id appends it as the selection's last child.\n const addChild = useCallback(async () => {\n if (!data.documentCreateChunk || !selectedId) return;\n setErr(null);\n try {\n const created = await data.documentCreateChunk(\n documentId,\n selectedId,\n { title: \"Text\", body: \"\" },\n scope,\n browse,\n );\n refresh();\n setSelectedId(created.id);\n setEditing(created);\n } catch (e) {\n setErr(e instanceof Error ? e.message : String(e));\n }\n }, [data, documentId, scope, browse, selectedId, refresh]);\n\n // RFC BP — the selected chunk's siblings (same parent) in position order, to\n // gate the up/down buttons at the level boundaries.\n const siblingBounds = useMemo(() => {\n if (!selectedDetail || selectedIsRoot) return { canUp: false, canDown: false };\n const parent = selectedDetail.parent_id ?? \"\";\n const sibs = chunks\n .filter((c) => (c.parent_id ?? \"\") === parent)\n .sort((a, b) => a.position - b.position || a.id.localeCompare(b.id));\n const i = sibs.findIndex((c) => c.id === selectedDetail.id);\n return { canUp: i > 0, canDown: i >= 0 && i < sibs.length - 1 };\n }, [chunks, selectedDetail, selectedIsRoot]);\n\n const reorderSelected = useCallback(\n async (direction: \"up\" | \"down\") => {\n if (!data.documentReorderChunk || !selectedId) return;\n setErr(null);\n try {\n await data.documentReorderChunk(selectedId, direction, scope, browse);\n refresh();\n } catch (e) {\n setErr(e instanceof Error ? e.message : String(e));\n }\n },\n [data, selectedId, scope, browse, refresh],\n );\n\n const deleteSelected = useCallback(async () => {\n if (!data.documentDeleteChunk || !selectedDetail) return;\n setErr(null);\n const parentId = selectedDetail.parent_id;\n try {\n await data.documentDeleteChunk(selectedDetail.id, scope, browse);\n setConfirmDelete(false);\n setSelectedId(parentId || rootChunkId);\n refresh();\n } catch (e) {\n setErr(e instanceof Error ? e.message : String(e));\n setConfirmDelete(false);\n }\n }, [data, selectedDetail, scope, browse, rootChunkId, refresh]);\n\n // Paste a screenshot anywhere in the viewer → a new image chunk. Ignored while\n // a modal or a text field is focused (so an editor paste isn't hijacked).\n useEffect(() => {\n if (!canCreate) return;\n const onPaste = (e: ClipboardEvent) => {\n if (editing || colorsOpen) return;\n const ae = document.activeElement;\n const tag = ae?.tagName;\n if (tag === \"INPUT\" || tag === \"TEXTAREA\" || (ae as HTMLElement)?.isContentEditable) return;\n const file = imageFileFromPaste(e.clipboardData?.items);\n if (file) {\n e.preventDefault();\n void addImageFile(file);\n }\n };\n window.addEventListener(\"paste\", onPaste);\n return () => window.removeEventListener(\"paste\", onPaste);\n }, [canCreate, editing, colorsOpen, addImageFile]);\n\n return (\n <div className=\"doc-viewer\">\n <input\n ref={fileInputRef}\n type=\"file\"\n accept=\"image/png,image/jpeg,image/gif,image/webp\"\n style={{ display: \"none\" }}\n onChange={(e) => {\n const f = e.target.files?.[0];\n e.target.value = \"\"; // allow re-selecting the same file\n if (f) void addImageFile(f);\n }}\n />\n <div className=\"doc-toolbar\" style={toolbarTint}>\n <strong className=\"doc-title\" title={rootTitle}>\n {rootTitle}\n </strong>\n {/* The document id — surfaced + copyable so it can be wired into an\n external workflow (e.g. n8n over the MCP/HTTP API), which the viewer\n otherwise only uses internally. */}\n <IdCopy value={documentId} label=\"doc\" />\n <div className=\"doc-toolbar-actions\">\n {canCreate && (\n <>\n <button\n type=\"button\"\n onClick={() => void addText()}\n title=\"Add a text chunk AFTER the selected chunk, at the same level\"\n >\n + text\n </button>\n <button\n type=\"button\"\n onClick={() => void addChild()}\n disabled={!selectedId}\n title={\n selectedId\n ? \"Add a chunk NESTED UNDER the selected chunk (in the ontology, a child is a subclass)\"\n : \"Select a chunk first — this nests a new chunk under it\"\n }\n >\n + child\n </button>\n <button\n type=\"button\"\n onClick={() => fileInputRef.current?.click()}\n title=\"Add an image chunk (upload — or paste a screenshot into the view)\"\n >\n + image\n </button>\n <button\n type=\"button\"\n onClick={() => void addDiagram()}\n title=\"Add a Mermaid diagram chunk\"\n >\n + diagram\n </button>\n </>\n )}\n <button\n type=\"button\"\n className={colorEnabled ? \"active\" : \"\"}\n onClick={() => setColorsOpen(true)}\n disabled={!rootChunkId}\n title=\"Colors — tint chunk tiles + the Path tree by type/status\"\n >\n colors\n </button>\n {data.documentClassify && (\n <button\n type=\"button\"\n className={classifyKey > 0 ? \"active\" : \"\"}\n onClick={() => setClassifyKey((n) => (n > 0 ? 0 : 1))}\n title=\"Classify — what this document is, by the confirmed ontology (a report first; nothing is written until Apply)\"\n >\n classify\n </button>\n )}\n <DownloadMenu documentId={documentId} scope={scope} browse={browse} title={rootTitle} onError={setErr} />\n {renderAssistant && (\n <button\n type=\"button\"\n className={assistantOpen ? \"active\" : \"\"}\n onClick={() => setAssistantOpen((o) => !o)}\n title=\"Document Assistant — instruct an agent to restructure/import/link chunks\"\n >\n assistant\n </button>\n )}\n <button type=\"button\" onClick={refresh} title=\"Reload\">\n ↻\n </button>\n </div>\n </div>\n {!unavailable && rootChunkId && (docAnnotations.length > 0 || saveAnnotation || regenerateAnnotation) && (\n <div className=\"doc-annotation\">\n <AnnotationBrief record={documentBrief} />\n <AnnotationPanel\n key={rootChunkId}\n records={docAnnotations}\n newLevel={annotationLevelFor(true)}\n onSave={saveAnnotation?.(rootChunkId)}\n onRegenerate={regenerateAnnotation?.(rootChunkId)}\n />\n </div>\n )}\n {err && <div className=\"paths-err\">{err}</div>}\n {!unavailable && (\n <Classification\n key={`${scope}:${documentId}`}\n documentId={documentId}\n scope={scope}\n browse={browse}\n rootFields={rootFields}\n requestKey={classifyKey}\n onClose={() => setClassifyKey(0)}\n onChanged={refresh}\n />\n )}\n {unavailable ? (\n <DocUnavailable documentId={documentId} scope={scope} detail={loadErr ?? undefined} />\n ) : (\n // The tree/chunk border is draggable; the width is remembered per browser.\n <Splitter\n className=\"doc-split\"\n defaultLeftWidth={320}\n minLeftWidth={160}\n minRightWidth={320}\n storageKey=\"loomcycle.explorer.split.doc\"\n >\n <div className=\"doc-chunktree\">\n {loading && chunks.length === 0 ? (\n <div className=\"empty\">\n <p>Loading…</p>\n </div>\n ) : (\n <DocumentChunkTree\n tree={tree}\n selectedId={selectedId}\n onSelect={onSelect}\n colorEnabled={colorEnabled}\n scheme={meta?.color_scheme}\n documentColor={documentColor}\n linkedIds={linkedIds}\n />\n )}\n </div>\n <div className=\"doc-content\">\n {selectedDetail ? (\n <>\n <div className=\"doc-content-head\">\n {ancestors.length > 0 && (\n <nav className=\"chunk-ancestry\" aria-label=\"Chunks above this one\">\n <button\n type=\"button\"\n className=\"chunk-ancestry-up\"\n onClick={() => setSelectedId(ancestors[ancestors.length - 1].id)}\n title={`Up to ${ancestors[ancestors.length - 1].title || \"(untitled)\"}`}\n >\n ↰ Up\n </button>\n <ol className=\"doc-trail-list\">\n {ancestors.map((a) => (\n <li className=\"doc-trail-item\" key={a.id}>\n <button\n type=\"button\"\n className=\"doc-trail-crumb\"\n onClick={() => setSelectedId(a.id)}\n title={a.title || \"(untitled)\"}\n >\n {a.title || \"(untitled)\"}\n </button>\n </li>\n ))}\n <li className=\"doc-trail-item\">\n <span\n className=\"doc-trail-current\"\n aria-current=\"location\"\n title={selectedDetail.title || \"(untitled)\"}\n >\n {selectedDetail.title || \"(untitled)\"}\n </span>\n </li>\n </ol>\n </nav>\n )}\n <h3>{selectedDetail.title || \"(untitled)\"}</h3>\n {!selectedIsRoot && <AnnotationBrief record={selectedAnnotations[0]} />}\n <div className=\"doc-content-meta\">\n {selectedDetail.type && <span className=\"chunk-badge\">{selectedDetail.type}</span>}\n {selectedDetail.status && (\n <span className=\"chunk-badge chunk-status\">{selectedDetail.status}</span>\n )}\n <span className=\"chunk-rev\">rev {selectedDetail.revision}</span>\n {/* RFC BS — read-only tag chips (editing lives in ChunkEditorModal).\n Nested tags (area/sub) are shown verbatim. */}\n {selectedDetail.tags?.map((t) => (\n <span className=\"chunk-tag\" key={t}>\n {t}\n </span>\n ))}\n {/* The selected chunk's id — copyable for external workflows. */}\n <IdCopy value={selectedDetail.id} label=\"chunk\" />\n </div>\n {!selectedIsRoot && selectedDetail.document_id === documentId && (\n <AnnotationPanel\n key={selectedDetail.id}\n records={selectedAnnotations}\n newLevel={annotationLevelFor(false)}\n onSave={saveAnnotation?.(selectedDetail.id)}\n onRegenerate={regenerateAnnotation?.(selectedDetail.id)}\n />\n )}\n <div className=\"doc-content-controls\">\n {/* The chunk/markdown switch is per-selected-chunk: markdown\n assembles this chunk + its sub-chunks (the root → the whole\n document). */}\n <div className=\"doc-mode-toggle\">\n <button\n type=\"button\"\n className={mode === \"chunks\" ? \"active\" : \"\"}\n onClick={() => setMode(\"chunks\")}\n title=\"This chunk's own content\"\n >\n chunk\n </button>\n <button\n type=\"button\"\n className={mode === \"markdown\" ? \"active\" : \"\"}\n onClick={() => setMode(\"markdown\")}\n title={\n selectedIsRoot\n ? \"Whole document as Markdown\"\n : \"This chunk + its sub-chunks as Markdown\"\n }\n >\n markdown\n </button>\n </div>\n <button\n type=\"button\"\n className=\"chunk-edit\"\n onClick={() => setEditing(selectedDetail)}\n >\n edit\n </button>\n {/* A subject's kind, picked from the types in force rather than typed\n free-hand in the editor, which would accept any word. */}\n {data.documentEntityTypes && isSubjectRoot(selectedDetail) && (\n <button\n type=\"button\"\n onClick={() => setRetyping(selectedDetail)}\n title=\"Change this subject's type to another type in force\"\n >\n change type\n </button>\n )}\n {/* RFC BS — read-only edit history (revisions + version view + diff). */}\n <button\n type=\"button\"\n onClick={() => setHistoryOpen(true)}\n title=\"View this chunk's edit history + diffs\"\n >\n history\n </button>\n {/* RFC BP — reorder within the level + delete (not for the root). */}\n {!selectedIsRoot && (\n <>\n <button\n type=\"button\"\n onClick={() => void reorderSelected(\"up\")}\n disabled={!siblingBounds.canUp}\n title=\"Move this chunk up within its level\"\n >\n ↑\n </button>\n <button\n type=\"button\"\n onClick={() => void reorderSelected(\"down\")}\n disabled={!siblingBounds.canDown}\n title=\"Move this chunk down within its level\"\n >\n ↓\n </button>\n </>\n )}\n {!selectedIsRoot && (\n <button\n type=\"button\"\n className=\"danger\"\n onClick={() => setConfirmDelete(true)}\n title=\"Delete this chunk and its sub-chunks\"\n >\n delete\n </button>\n )}\n </div>\n </div>\n {/* The chunk's text above, its links below, with a handle between:\n many references used to push the text down to a sliver. */}\n <StackSplitter storageKey=\"loomcycle.explorer.doc-links-height\" className=\"doc-content-split\">\n <div className=\"doc-content-body\">\n {selectedDetail.type === \"mermaid\" ? (\n // RFC BO — a diagram chunk: body IS the Mermaid source.\n selectedDetail.body ? (\n <>\n <MermaidDiagram code={selectedDetail.body} />\n {mode === \"markdown\" && (\n <pre className=\"md-pre doc-mermaid-source\">\n <code>{selectedDetail.body}</code>\n </pre>\n )}\n </>\n ) : (\n <p className=\"doc-empty-body\">(empty diagram)</p>\n )\n ) : selectedDetail.type === \"image\" || selectedDetail.asset ? (\n // RFC BO — an image chunk: bytes come from the auth'd asset GET.\n imageErr ? (\n <p className=\"doc-empty-body\">Image failed to load: {imageErr}</p>\n ) : imageUrl ? (\n <figure className=\"doc-image\">\n <img src={imageUrl} alt={imageAlt(selectedDetail)} />\n {selectedDetail.body && <figcaption>{selectedDetail.body}</figcaption>}\n </figure>\n ) : (\n <p className=\"doc-empty-body\">Loading image…</p>\n )\n ) : mode === \"markdown\" ? (\n subtreeMd !== null ? (\n <Markdown source={subtreeMd} />\n ) : (\n <p className=\"doc-empty-body\">Assembling Markdown…</p>\n )\n ) : selectedDetail.body ? (\n <Markdown source={selectedDetail.body} />\n ) : (\n <p className=\"doc-empty-body\">(empty chunk)</p>\n )}\n </div>\n <div className=\"doc-links-pane\">\n <CrossReferences\n edges={edges}\n incomplete={edgesIncomplete}\n documentId={documentId}\n selectedId={selectedId}\n onSelectChunk={setSelectedId}\n onOpenDocument={onOpenDocument ? openDocument : undefined}\n onRuleStatement={ruleStatement}\n />\n {/* RFC BS — backlinks / related / unlinked mentions for the selected\n chunk, lazily fetched when its section is expanded. */}\n <Connections\n documentId={documentId}\n selectedId={selectedId}\n scope={scope}\n browse={browse}\n onSelectChunk={setSelectedId}\n onOpenDocument={onOpenDocument ? openDocument : undefined}\n refreshKey={edgesReload}\n review={review}\n />\n </div>\n </StackSplitter>\n </>\n ) : (\n <div className=\"empty\">\n <p>Select a chunk on the left.</p>\n </div>\n )}\n </div>\n </Splitter>\n )}\n {assistantOpen && renderAssistant && (\n <div className=\"doc-assistant\">\n {renderAssistant({\n documentId,\n scope,\n subject: principal?.subject,\n // Pass the viewer's own reload so the injected assistant can refresh\n // the tree + selected chunk after a turn mutates the document.\n onChanged: refresh,\n })}\n </div>\n )}\n {editing && (\n <ChunkEditorModal\n chunk={editing}\n scope={scope}\n browse={browse}\n onClose={() => setEditing(null)}\n onSaved={refresh}\n />\n )}\n {retyping && (\n <SubjectTypeModal\n chunk={retyping}\n scope={scope}\n browse={browse}\n onClose={() => setRetyping(null)}\n onSaved={refresh}\n />\n )}\n {historyOpen && selectedDetail && (\n <HistoryModal\n chunkId={selectedDetail.id}\n chunkTitle={selectedDetail.title}\n scope={scope}\n browse={browse}\n onClose={() => setHistoryOpen(false)}\n />\n )}\n {colorsOpen && rootChunkId && (\n <ColorSchemeEditor\n documentId={documentId}\n rootChunkId={rootChunkId}\n docType={meta?.type}\n docStatus={meta?.status}\n chunkStatuses={chunkStatuses}\n scope={scope}\n browse={browse}\n onClose={() => setColorsOpen(false)}\n onSaved={refresh}\n />\n )}\n {confirmDelete && selectedDetail && (\n <div className=\"modal-overlay\" onClick={() => setConfirmDelete(false)}>\n <div className=\"modal chunk-delete-confirm\" onClick={(e) => e.stopPropagation()}>\n <h3>Delete chunk</h3>\n <p className=\"modal-context\">\n Delete “{selectedDetail.title || \"(untitled)\"}” and all of its sub-chunks? This\n cannot be undone.\n </p>\n <div className=\"modal-buttons\">\n <button type=\"button\" onClick={() => setConfirmDelete(false)}>\n cancel\n </button>\n <button type=\"button\" className=\"danger\" onClick={() => void deleteSelected()}>\n delete\n </button>\n </div>\n </div>\n </div>\n )}\n </div>\n );\n}\n","import type { ReactNode } from \"react\";\nimport type { DirListing, DirMap } from \"../lib/lazyPathTree\";\nimport { ANNOTATION_ENTRY } from \"../lib/annotation\";\nimport {\n docColor,\n effectiveScheme,\n tintStyle,\n type DocSummary,\n} from \"../lib/colorScheme\";\n\n// PathTree renders the RFC AL dirent tree from per-directory listings (see\n// lib/lazyPathTree): a directory's children exist only once it has been opened\n// and listed. The expand set, the loading and the paging are owned by the\n// caller; this component only draws them — a caret per directory, a status row\n// while a directory loads / is empty / failed, and a \"load more\" row while a\n// directory has pages left.\n\nexport interface PathNode {\n name: string;\n fullPath: string;\n kind: string; // directory | document | volume_mount | memory_entry\n resourceRef?: unknown;\n // hasChildren: a non-directory (a document) that also has names beneath it,\n // so it opens like a directory while its name still opens the document.\n hasChildren?: boolean;\n // listing is this node's children's load state; undefined = never listed\n // (and always undefined for a node that cannot be opened).\n listing?: DirListing;\n children: PathNode[];\n}\n\n// buildLazyTree turns the listings into a hierarchy rooted at `dir` (\"\" =\n// root). A one-level listing already includes implicit directories (the runtime\n// synthesizes them from deeper descendants), so nothing is synthesized here.\nexport function buildLazyTree(dirs: DirMap, dir = \"\"): PathNode[] {\n const listing = dirs.get(dir);\n if (!listing) return [];\n const nodes = listing.entries.map((e): PathNode => {\n // The prefix check keeps a malformed entry (a child spelled like its own\n // directory) from recursing forever.\n const hasChildren = e.kind !== \"directory\" && e.has_children === true;\n const opens = (e.kind === \"directory\" || hasChildren) && e.full_path.startsWith(`${dir}/`);\n return {\n name: e.name,\n fullPath: e.full_path,\n kind: e.kind,\n resourceRef: e.resource_ref,\n ...(hasChildren ? { hasChildren } : {}),\n listing: opens ? dirs.get(e.full_path) : undefined,\n children: opens ? buildLazyTree(dirs, e.full_path) : [],\n };\n });\n nodes.sort((a, b) => {\n const ad = a.kind === \"directory\";\n const bd = b.kind === \"directory\";\n if (ad !== bd) return ad ? -1 : 1; // directories first\n return a.name.localeCompare(b.name);\n });\n return nodes;\n}\n\nconst KIND_ICON: Record<string, string> = {\n directory: \"📁\",\n document: \"📄\",\n volume_mount: \"💾\",\n memory_entry: \"🧠\",\n};\n\n// A folder's annotation document gets its own icon, so it reads as the\n// folder's description rather than one more document in it.\nconst ANNOTATION_ICON = \"📝\";\n\n// isAnnotationEntry: the reserved `_annotation` document of a folder.\nexport function isAnnotationEntry(node: Pick<PathNode, \"kind\" | \"name\">): boolean {\n return node.kind === \"document\" && node.name === ANNOTATION_ENTRY;\n}\n\n// nodeBrief is the brief a row shows under its name: a document's own, and for\n// a folder the brief of its `_annotation` document — known only once the\n// folder has been listed, which is when its children's summaries arrive. No\n// extra call is made for it.\nexport function nodeBrief(node: PathNode, summaries?: Map<string, DocSummary>): string | undefined {\n if (node.kind === \"directory\") {\n const ann = node.children.find(isAnnotationEntry);\n return ann ? documentSummaryOf(ann, summaries)?.brief || undefined : undefined;\n }\n if (isAnnotationEntry(node)) return undefined; // its brief is the folder's\n return documentSummaryOf(node, summaries)?.brief || undefined;\n}\n\nexport interface PathTreeProps {\n tree: PathNode[];\n // root is the root directory's listing (its status/paging rows).\n root?: DirListing;\n expanded: ReadonlySet<string>;\n onToggle: (dir: string) => void;\n // onLoadMore fetches a directory's next page (\"\" = root); onRetry re-tries a\n // directory whose listing failed.\n onLoadMore: (dir: string) => void;\n onRetry: (dir: string) => void;\n selectedPath?: string;\n onSelect: (node: PathNode) => void;\n // RFC BN: per-document display metadata keyed by document_id, used to color a\n // document row + badge its type/status. Unset → neutral rows (prior behavior).\n summaries?: Map<string, DocSummary>;\n}\n\nexport default function PathTree(props: PathTreeProps) {\n const { tree, root } = props;\n if (!root || (!root.loaded && root.loading)) {\n return (\n <div className=\"empty\">\n <p>Loading…</p>\n </div>\n );\n }\n if (root.loaded && tree.length === 0 && !root.nextCursor) {\n return (\n <div className=\"empty\">\n <p>This tree is empty. Create a folder or document to begin.</p>\n </div>\n );\n }\n return (\n <ul className=\"tree path-tree\">\n {tree.map((n) => (\n <PathTreeNode key={n.fullPath} node={n} {...props} />\n ))}\n <ListingRows dir=\"\" listing={root} {...props} />\n </ul>\n );\n}\n\n// ListingRows draws the trailing rows of a directory's children: its status\n// (loading / empty / failed) and, while pages remain, a \"load more\" button.\n// Entries are never dropped silently — a clipped directory always ends in one.\nfunction ListingRows({\n dir,\n listing,\n onLoadMore,\n onRetry,\n}: { dir: string; listing?: DirListing } & PathTreeProps) {\n const rows: ReactNode[] = [];\n if (!listing || (listing.loading && listing.entries.length === 0)) {\n rows.push(\n <li key=\"status\" className=\"node path-status\">\n <span className=\"path-implicit\">loading…</span>\n </li>,\n );\n } else if (listing.error) {\n rows.push(\n <li key=\"status\" className=\"node path-status\">\n {/* The root's failure is already the banner above the tree. */}\n {dir !== \"\" && <span className=\"path-err\">failed to load: {listing.error}</span>}{\" \"}\n <button type=\"button\" className=\"path-more\" onClick={() => onRetry(dir)}>\n retry\n </button>\n </li>,\n );\n } else if (listing.loaded && listing.entries.length === 0 && dir !== \"\") {\n rows.push(\n <li key=\"status\" className=\"node path-status\">\n <span className=\"path-implicit\">empty</span>\n </li>,\n );\n }\n if (listing?.nextCursor && !listing.error) {\n rows.push(\n <li key=\"more\" className=\"node path-status\">\n <button\n type=\"button\"\n className=\"path-more\"\n disabled={listing.loading}\n onClick={() => onLoadMore(dir)}\n >\n {listing.loading\n ? \"loading…\"\n : `Load more (${listing.entries.length} shown)`}\n </button>\n </li>,\n );\n }\n return <>{rows}</>;\n}\n\n// documentSummaryOf returns the summary for a `document` node (by its dirent's\n// document_id), or undefined for a non-document node / missing summary.\nfunction documentSummaryOf(node: PathNode, summaries?: Map<string, DocSummary>): DocSummary | undefined {\n if (node.kind !== \"document\" || !summaries) return undefined;\n const ref = node.resourceRef as { document_id?: string } | undefined;\n return ref?.document_id ? summaries.get(ref.document_id) : undefined;\n}\n\nfunction PathTreeNode(props: { node: PathNode } & PathTreeProps) {\n const { node, expanded, onToggle, selectedPath, onSelect, summaries } = props;\n // A directory opens, and so does a document with names beneath it (RFC GC):\n // its caret lists them while its name still opens the document. Children are\n // unknown until listed, so the caret is live even before then.\n const isDir = node.kind === \"directory\" || node.hasChildren === true;\n const isOpen = isDir && expanded.has(node.fullPath);\n const isSelected = selectedPath === node.fullPath;\n const summary = documentSummaryOf(node, summaries);\n const brief = nodeBrief(node, summaries);\n const rowStyle =\n summary && summary.color_enabled\n ? tintStyle(docColor(summary.type, summary.status, effectiveScheme(summary.color_scheme)))\n : undefined;\n return (\n <li className={`node path-node kind-${node.kind} ${isSelected ? \"selected\" : \"\"}`}>\n <div className=\"row path-row\" style={rowStyle}>\n <button\n type=\"button\"\n className=\"tree-caret\"\n aria-label={isOpen ? \"collapse\" : \"expand\"}\n aria-expanded={isDir ? isOpen : undefined}\n disabled={!isDir}\n onClick={(e) => {\n e.stopPropagation();\n if (isDir) onToggle(node.fullPath);\n }}\n >\n {isDir ? (isOpen ? \"▼\" : \"▶\") : \"·\"}\n </button>\n <button\n type=\"button\"\n className=\"path-link\"\n onClick={() => onSelect(node)}\n title={brief ? `${node.fullPath}\\n${brief}` : node.fullPath}\n >\n <span className=\"path-kind-icon\" aria-hidden>\n {isAnnotationEntry(node) ? ANNOTATION_ICON : (KIND_ICON[node.kind] ?? \"•\")}\n </span>\n <span className=\"path-name\">{node.name}</span>\n {summary?.type && <span className=\"chunk-badge\">{summary.type}</span>}\n {summary?.status && <span className=\"chunk-badge chunk-status\">{summary.status}</span>}\n </button>\n {/* The brief wraps onto its own line inside the row box. */}\n {brief && <span className=\"path-brief\">{brief}</span>}\n </div>\n {isOpen && (\n <ul className=\"children path-children\">\n {node.children.map((c) => (\n <PathTreeNode key={c.fullPath} {...props} node={c} />\n ))}\n <ListingRows {...props} dir={node.fullPath} listing={node.listing} />\n </ul>\n )}\n </li>\n );\n}\n","import {\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n useSyncExternalStore,\n type FormEvent,\n type ReactNode,\n} from \"react\";\nimport type {\n AnnotationTarget,\n AssistantContext,\n BrowseScope,\n NavigatorContext,\n NavigatorSelection,\n PathScope,\n Principal,\n} from \"./types\";\nimport { readNavigatorMode, writeNavigatorMode, type NavigatorMode } from \"./lib/navigator\";\nimport { useExplorerData, type ExplorerDataLayer } from \"./lib/dataLayer\";\nimport type { DocSummary } from \"./lib/colorScheme\";\nimport {\n LazyPathTree,\n LS_PAGE_LIMIT,\n ancestorsOf,\n documentIdsOf,\n listSubtree,\n parentPathOf,\n} from \"./lib/lazyPathTree\";\nimport {\n ExplorerRoot,\n useResolvedDataLayer,\n type ExplorerDataSource,\n} from \"./components/ExplorerRoot\";\nimport {\n amendCurrent,\n findDocumentPath,\n followReference,\n jumpTo,\n labelOf,\n type DocLocation,\n type Trail,\n} from \"./lib/docTrail\";\nimport DocTrail from \"./components/DocTrail\";\nimport TransferModal from \"./components/TransferModal\";\nimport type { TransferRequest } from \"./lib/transfer\";\nimport Splitter from \"./components/Splitter\";\nimport DocumentViewerBody from \"./components/DocumentViewerBody\";\nimport PathTree, { buildLazyTree, type PathNode } from \"./components/PathTree\";\n\n// PathExplorer is the embeddable Path VFS console (RFC AL): the unified dirent\n// tree with directory + document CRUD, and an inline DocumentViewer for document\n// dirents. Identity (tenant + subject) is resolved server-side from the\n// authenticated principal — the component sends only `scope` (the subtree\n// SELECTOR) + the optional RFC AS `browse` override, never an authority grant.\n//\n// This is the decoupled port of the loomcycle Web UI's PathTreeView: routing is\n// replaced by internal selection state (with optional controlled\n// `path`/`onPathChange`), the runtime is reached through an injected data layer\n// (connection → client → dataLayer), and browse / principal arrive as props\n// instead of context hooks. Styles ship separately:\n// `import \"@loomcycle/explorer/styles.css\"`.\n\nconst NAME_RE = /^[A-Za-z0-9._-]+$/;\n\n// joinPath appends a leaf segment to a canonical parent dir (\"\" = root).\nfunction joinPath(dir: string, name: string): string {\n return `${dir}/${name}`;\n}\n\nfunction findNode(tree: PathNode[], fullPath: string): PathNode | undefined {\n for (const n of tree) {\n if (n.fullPath === fullPath) return n;\n const hit = findNode(n.children, fullPath);\n if (hit) return hit;\n }\n return undefined;\n}\n\nexport interface PathExplorerProps extends ExplorerDataSource {\n // ---- Theming. When set, the root carries data-theme; when omitted the\n // component inherits an ancestor's data-theme (dark is the default palette).\n theme?: \"light\" | \"dark\";\n\n // ---- Scope. The initial tree scope; the toolbar select lets the operator\n // switch it at runtime (internal state). Default \"user\".\n defaultScope?: PathScope;\n\n // ---- Selection. `path` + `onPathChange` make the selected path controlled\n // (so a host that routes can bridge URL ↔ selection); omit both for internal\n // state. On a scope switch the selection clears (onPathChange fires with\n // undefined). Mirrors the library's tab/onTabChange controlled pattern.\n path?: string;\n onPathChange?: (path: string | undefined) => void;\n\n // ---- RFC AS browse-by-subject override threaded into every path/document\n // call. Unset → the caller's own subject.\n browse?: BrowseScope;\n\n // ---- Authenticated principal — only `subject` is read (passed to\n // renderAssistant). Optional.\n principal?: Principal;\n\n // ---- Optional Document Assistant slot, forwarded to the embedded\n // DocumentViewer. Provide it to show an \"assistant\" toggle; omit → none.\n renderAssistant?: (ctx: AssistantContext) => ReactNode;\n\n // ---- Optional: have an annotation written again (tenant-scope documents),\n // forwarded to the embedded DocumentViewer. The host owns how (typically by\n // starting the annotating agent's run). Omit → no Regenerate.\n onRegenerateAnnotation?: (target: AnnotationTarget) => void | Promise<void>;\n // Whether the reader may edit annotations by hand (the operator plane; the\n // runtime refuses anyone else). Default false: no Edit is offered.\n canEditAnnotations?: boolean;\n\n // ---- Optional second navigator beside the Path tree (the @loomcycle/universe\n // star map). Provide it to show a `tree | stars` switch in the toolbar; the\n // tree stays the default. Omit → tree only, and nothing else is loaded.\n renderNavigator?: (ctx: NavigatorContext) => ReactNode;\n // Ask for a navigator: when set, and whenever it changes, the explorer\n // switches to it and remembers the choice as the toggle does. A host opening\n // a saved star-map view passes \"stars\". Ignored without renderNavigator.\n navigator?: NavigatorMode;\n\n // ---- Errors. Called on a tree-load failure (in addition to the inline\n // banner). The component NEVER redirects on 401 — the host owns the auth flow.\n onError?: (e: unknown) => void;\n}\n\nexport default function PathExplorer(props: PathExplorerProps) {\n const {\n theme,\n defaultScope,\n path,\n onPathChange,\n browse,\n principal,\n renderAssistant,\n renderNavigator,\n navigator,\n onError,\n onRegenerateAnnotation,\n canEditAnnotations,\n } = props;\n const resolved = useResolvedDataLayer(props);\n return (\n <ExplorerRoot theme={theme} dataLayer={resolved}>\n <PathExplorerBody\n defaultScope={defaultScope}\n path={path}\n onPathChange={onPathChange}\n browse={browse}\n principal={principal}\n renderAssistant={renderAssistant}\n renderNavigator={renderNavigator}\n navigator={navigator}\n onError={onError}\n onRegenerateAnnotation={onRegenerateAnnotation}\n canEditAnnotations={canEditAnnotations}\n />\n </ExplorerRoot>\n );\n}\n\ntype PathExplorerBodyProps = Omit<PathExplorerProps, keyof ExplorerDataSource | \"theme\">;\n\ninterface ModalField {\n key: string;\n label: string;\n placeholder?: string;\n value?: string;\n}\ninterface ModalState {\n title: string;\n message?: string;\n fields: ModalField[];\n submitLabel: string;\n danger?: boolean;\n onSubmit: (vals: Record<string, string>) => Promise<void>;\n}\n\nfunction PathExplorerBody({\n defaultScope,\n path: pathProp,\n onPathChange,\n browse: browseProp,\n principal,\n renderAssistant,\n renderNavigator,\n navigator: navigatorProp,\n onError,\n onRegenerateAnnotation,\n canEditAnnotations,\n}: PathExplorerBodyProps) {\n const data: ExplorerDataLayer = useExplorerData();\n\n const [scope, setScope] = useState<PathScope>(defaultScope ?? \"user\");\n const [internalSelected, setInternalSelected] = useState<string | undefined>(undefined);\n const [err, setErr] = useState<string | null>(null);\n const [modal, setModal] = useState<ModalState | null>(null);\n // The copy / move dialog: one document by id, or a folder's documents.\n const [transfer, setTransfer] = useState<\n { documentId?: string; underPath?: string; fromPath: string } | null\n >(null);\n // Directories the operator has opened. Collapsed by default: opening one is\n // what lists it, so nothing below the root is fetched until it is wanted.\n const [expanded, setExpanded] = useState<ReadonlySet<string>>(() => new Set());\n\n // Effective selection: controlled `path` prop overrides the internal state.\n const selectedPath = pathProp !== undefined ? pathProp : internalSelected;\n\n // onPathChange through a ref so the selection setter + scope-reset effect stay\n // stable (a parent passing an inline callback each render doesn't churn them).\n const onPathChangeRef = useRef(onPathChange);\n useEffect(() => {\n onPathChangeRef.current = onPathChange;\n }, [onPathChange]);\n const onErrorRef = useRef(onError);\n useEffect(() => {\n onErrorRef.current = onError;\n }, [onError]);\n\n // The trail of documents reached by following references (see lib/docTrail).\n // While it has entries, its LAST one is the document on screen — it may have\n // no path at all, so the tree selection cannot be what picks the document.\n const [trail, setTrail] = useState<Trail>([]);\n // navSeq numbers each navigation, so a path lookup that answers after the\n // reader has moved on is dropped instead of yanking the selection back.\n const navSeq = useRef(0);\n // The last path this component reported, to tell a controlled host's echo of\n // it from a path the host chose itself.\n const emittedPath = useRef<string | undefined>(undefined);\n\n // applySelection moves the tree selection without touching the trail — the\n // trail's own navigation uses it so the tree follows the opened document.\n const applySelection = useCallback((p: string | undefined) => {\n emittedPath.current = p;\n onPathChangeRef.current?.(p);\n setInternalSelected(p); // harmless when controlled; drives display when not\n }, []);\n\n // setSelected is a FRESH navigation — a tree click, a create/rename/delete, a\n // scope switch — and starts over: the trail records a chain of followed\n // references, and picking a document some other way is not a link in it.\n const setSelected = useCallback(\n (p: string | undefined) => {\n navSeq.current++;\n setTrail((t) => (t.length > 0 ? [] : t));\n applySelection(p);\n },\n [applySelection],\n );\n\n // A controlled host that moves `path` on its own (not echoing ours) is a fresh\n // navigation too.\n useEffect(() => {\n if (pathProp === undefined || pathProp === emittedPath.current) return;\n navSeq.current++;\n setTrail((t) => (t.length > 0 ? [] : t));\n }, [pathProp]);\n\n // Memoize browse on its primitives so an inline `browse={{...}}` doesn't churn\n // the fetch effect every render.\n const browse = useMemo<BrowseScope | undefined>(\n () =>\n browseProp && (browseProp.scopeId || browseProp.tenant)\n ? { scopeId: browseProp.scopeId, tenant: browseProp.tenant }\n : undefined,\n [browseProp?.scopeId, browseProp?.tenant],\n );\n\n // One listing cache per (scope, subject): a new instance on a switch is also\n // what makes a previous subject's in-flight pages land nowhere.\n const lazy = useMemo(() => new LazyPathTree(data, scope, browse), [data, scope, browse]);\n const dirs = useSyncExternalStore(lazy.subscribe, lazy.getSnapshot);\n\n // report hands a listing failure to the host. The tree already shows it\n // inline (root: the banner; a directory: its own row), so this never throws.\n const report = useCallback((e: unknown) => {\n onErrorRef.current?.(e);\n }, []);\n\n // The navigator slot (renderNavigator): which navigator shows, whether it has\n // the whole explorer, and what it is told. navReload bumps on every change the\n // explorer makes to the tree, so the star map reloads with it.\n const [navMode, setNavModeState] = useState<NavigatorMode>(() =>\n renderNavigator ? readNavigatorMode(globalThis.localStorage) : \"tree\",\n );\n const starsOn = !!renderNavigator && navMode === \"stars\";\n const setNavMode = useCallback((m: NavigatorMode) => {\n setNavModeState(m);\n writeNavigatorMode(globalThis.localStorage, m);\n if (m === \"tree\") setMaximized(false);\n }, []);\n const [maximized, setMaximized] = useState(false);\n const [navReload, setNavReload] = useState(0);\n useEffect(() => {\n if (renderNavigator && navigatorProp) setNavMode(navigatorProp);\n // Only a change of the request switches; a reader's later toggle stands.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [navigatorProp]);\n // The chunk the viewer is on (reported by it), and a pending request to move\n // it (a star picked inside the open document, or the landing chunk of one\n // being opened).\n const [liveChunk, setLiveChunk] = useState<\n { documentId: string; chunkId?: string } | undefined\n >();\n const [focus, setFocus] = useState<\n { documentId: string; chunkId?: string; seq: number } | undefined\n >();\n const invalidate = useCallback(\n (p: string, opts?: { dropSubtree?: boolean }) => {\n setNavReload((n) => n + 1);\n return lazy.invalidate(p, opts);\n },\n [lazy],\n );\n\n // RFC BN: per-document type/status + color settings, so PathTree can color +\n // badge document rows. Fetched per listed page (≤ one page of ids per call —\n // the bound documents_summary is sized for) and merged, rather than once for a\n // whole tree that is no longer loaded at once. Best-effort — a failure just\n // leaves those rows neutral. `requested` keeps a page from being re-asked on\n // every listing change; summaryGen drops answers from before a reset.\n const [summaries, setSummaries] = useState<Map<string, DocSummary>>(() => new Map());\n const requested = useRef<Set<string>>(new Set());\n const summaryGen = useRef(0);\n const resetSummaries = useCallback(() => {\n summaryGen.current++;\n requested.current = new Set();\n setSummaries(new Map());\n }, []);\n\n // Start over whenever the scope/browse changes (and on mount). Clear the\n // selection on a CHANGE (not on mount) so a stale path from the previous\n // scope/subject doesn't drive the detail pane — but the first run must respect\n // a controlled parent's initial `path` (clearing on mount would fire\n // onPathChange(undefined) and clobber it).\n const firstLoad = useRef(true);\n useEffect(() => {\n if (firstLoad.current) {\n firstLoad.current = false;\n } else {\n setSelected(undefined);\n setErr(null);\n setExpanded(new Set());\n resetSummaries();\n }\n lazy.loadDir(\"\").catch(report);\n }, [lazy, setSelected, resetSummaries, report]);\n\n // An opened directory that has never been listed gets listed. Keyed on the\n // listings too, so a directory whose cache was dropped (moved away and back)\n // while it stayed open re-lists instead of sitting empty. A FAILED listing is\n // left for its retry row, so an outage doesn't turn into a request loop.\n useEffect(() => {\n for (const d of expanded) {\n if (!dirs.has(d)) lazy.loadDir(d).catch(report);\n }\n }, [lazy, expanded, dirs, report]);\n\n // Deep link / post-mutation selection: open the selection's ancestors and list\n // them — paging a directory until the selected entry shows, since it may sit\n // past the first page. Skipped on a scope/subject switch: that render still\n // carries the previous selection, which the effect above is clearing.\n const revealedIn = useRef<LazyPathTree | null>(null);\n useEffect(() => {\n const switched = revealedIn.current !== null && revealedIn.current !== lazy;\n revealedIn.current = lazy;\n if (!selectedPath || switched) return;\n const ancestors = ancestorsOf(selectedPath).filter((d) => d !== \"\");\n setExpanded((prev) => {\n if (ancestors.every((d) => prev.has(d))) return prev;\n const next = new Set(prev);\n ancestors.forEach((d) => next.add(d));\n return next;\n });\n lazy.reveal(selectedPath).catch(report);\n }, [lazy, selectedPath, report]);\n\n useEffect(() => {\n const fresh: string[] = [];\n for (const listing of dirs.values()) {\n for (const id of documentIdsOf(listing.entries)) {\n if (!requested.current.has(id)) {\n requested.current.add(id);\n fresh.push(id);\n }\n }\n }\n const gen = summaryGen.current;\n for (let i = 0; i < fresh.length; i += LS_PAGE_LIMIT) {\n data\n .documentsSummary({ documentIds: fresh.slice(i, i + LS_PAGE_LIMIT) }, scope, browse)\n .then((resp) => {\n if (summaryGen.current !== gen) return;\n setSummaries((prev) => {\n const m = new Map(prev);\n for (const d of resp.documents ?? []) m.set(d.document_id, d);\n return m;\n });\n })\n .catch(() => {});\n }\n }, [data, dirs, scope, browse]);\n\n const tree = useMemo(() => buildLazyTree(dirs), [dirs]);\n\n // refresh re-lists the root and every open directory, then re-reveals the\n // selection (it may have been on a page the reload folded away).\n const refresh = useCallback(async () => {\n setErr(null);\n resetSummaries();\n setNavReload((n) => n + 1);\n await lazy.refresh(expanded).catch(report);\n if (selectedPath) await lazy.reveal(selectedPath).catch(report);\n }, [lazy, expanded, selectedPath, resetSummaries, report]);\n\n const toggle = useCallback((dir: string) => {\n setExpanded((prev) => {\n const next = new Set(prev);\n if (next.has(dir)) next.delete(dir);\n else next.add(dir);\n return next;\n });\n }, []);\n\n const loadMore = useCallback((dir: string) => lazy.loadMore(dir).catch(report), [lazy, report]);\n const retry = useCallback(\n (dir: string) => {\n const listing = lazy.getSnapshot().get(dir);\n (listing?.loaded ? lazy.loadMore(dir) : lazy.loadDir(dir)).catch(report);\n },\n [lazy, report],\n );\n\n const selected = useMemo(\n () => (selectedPath ? findNode(tree, selectedPath) : undefined),\n [tree, selectedPath],\n );\n const rootErr = dirs.get(\"\")?.error;\n\n // Whether the selected directory has its own dirent or exists only through its\n // descendants. A one-level listing reports both as `directory`, so this asks\n // per selection; a data layer without pathIsStored just omits the row.\n const selectedDir = selected?.kind === \"directory\" ? selected.fullPath : undefined;\n const [stored, setStored] = useState<{ path: string; explicit: boolean } | null>(null);\n useEffect(() => {\n if (!selectedDir || !data.pathIsStored) return;\n let cancelled = false;\n data.pathIsStored(selectedDir, scope, browse).then(\n (explicit) => {\n if (!cancelled) setStored({ path: selectedDir, explicit });\n },\n () => {},\n );\n return () => {\n cancelled = true;\n };\n }, [data, selectedDir, scope, browse]);\n // Only a directory can be implicit; every other kind is a stored entry.\n const storedLabel = !selected\n ? undefined\n : selected.kind !== \"directory\"\n ? \"yes\"\n : stored?.path === selected.fullPath\n ? stored.explicit\n ? \"yes\"\n : \"implicit (no entry)\"\n : undefined;\n\n // The directory new items are created under: the selected directory, the\n // parent of a selected leaf, or root.\n const currentDir = useMemo(() => {\n if (!selected) return \"\";\n return selected.kind === \"directory\" ? selected.fullPath : parentPathOf(selected.fullPath);\n }, [selected]);\n const currentDirLabel = currentDir || \"/\";\n\n\n const newFolder = useCallback(() => {\n setModal({\n title: `New folder in ${currentDirLabel}`,\n fields: [{ key: \"name\", label: \"Folder name\", placeholder: \"e.g. launches\" }],\n submitLabel: \"Create\",\n onSubmit: async (v) => {\n const name = v.name.trim();\n if (!NAME_RE.test(name)) throw new Error(\"name may contain only [A-Za-z0-9._-]\");\n const p = joinPath(currentDir, name);\n await data.pathMkdir(p, scope, browse);\n await invalidate(p).catch(report);\n setSelected(p);\n },\n });\n }, [data, lazy, currentDir, currentDirLabel, scope, browse, report, setSelected]);\n\n const newDocument = useCallback(() => {\n setModal({\n title: `New document in ${currentDirLabel}`,\n fields: [\n { key: \"name\", label: \"Path name\", placeholder: \"e.g. launch-plan\" },\n { key: \"title\", label: \"Title\", placeholder: \"e.g. Launch Plan\" },\n ],\n submitLabel: \"Create\",\n onSubmit: async (v) => {\n const name = v.name.trim();\n if (!NAME_RE.test(name)) throw new Error(\"name may contain only [A-Za-z0-9._-]\");\n const title = v.title.trim() || name;\n const p = joinPath(currentDir, name);\n await data.documentCreate(title, p, scope, browse);\n await invalidate(p).catch(report);\n setSelected(p);\n },\n });\n }, [data, lazy, currentDir, currentDirLabel, scope, browse, report, setSelected]);\n\n const renameSelected = useCallback(() => {\n if (!selected) return;\n setModal({\n title: `Rename / move ${selected.fullPath}`,\n fields: [{ key: \"to\", label: \"New path\", value: selected.fullPath }],\n submitLabel: \"Move\",\n onSubmit: async (v) => {\n const to = v.to.trim();\n if (!to.startsWith(\"/\")) throw new Error(\"path must start with /\");\n await data.pathMv(selected.fullPath, to, scope, browse);\n await Promise.all([\n invalidate(selected.fullPath, { dropSubtree: true }),\n invalidate(to),\n ]).catch(report);\n setSelected(to);\n },\n });\n }, [data, lazy, selected, scope, browse, report, setSelected]);\n\n const deleteSelected = useCallback(() => {\n if (!selected) return;\n if (selected.kind === \"document\") {\n const ref = selected.resourceRef as { document_id?: string } | undefined;\n const id = ref?.document_id;\n setModal({\n title: `Delete document ${selected.fullPath}`,\n message:\n \"This deletes the document, all its chunks, and its path entry. This cannot be undone.\",\n fields: [],\n submitLabel: \"Delete\",\n danger: true,\n onSubmit: async () => {\n if (!id) throw new Error(\"this document dirent has no document_id\");\n await data.documentDelete(id, scope, browse);\n await invalidate(selected.fullPath).catch(report);\n setSelected(undefined);\n },\n });\n return;\n }\n // Directory: cascade-delete contained Documents (so no orphaned content),\n // then remove the dirent subtree — in every scope: a tenant-scope branch\n // delete used to drop only the names, leaving its documents unreachable.\n // The tree holds only the directories that were opened, so the branch is\n // listed in full here — the confirmation must count, and the delete must\n // reach, every Document under it, not just the ones on screen.\n const target = selected;\n setErr(null);\n void (async () => {\n let subtree;\n try {\n subtree = await listSubtree(data, target.fullPath, scope, browse);\n } catch (e) {\n setErr(`could not list ${target.fullPath} for delete: ${e instanceof Error ? e.message : String(e)}`);\n return;\n }\n const docIds = documentIdsOf(subtree);\n setModal({\n title: `Delete branch ${target.fullPath}`,\n message:\n subtree.length === 0\n ? \"This removes the (empty) folder.\"\n : `This removes the folder and everything under it` +\n (docIds.length > 0\n ? ` — including ${docIds.length} document(s), whose chunks are deleted.`\n : \".\"),\n fields: [],\n submitLabel: \"Delete\",\n danger: true,\n onSubmit: async () => {\n for (const id of docIds) {\n await data.documentDelete(id, scope, browse);\n }\n await data.pathRm(target.fullPath, scope, true, browse);\n await invalidate(target.fullPath, { dropSubtree: true }).catch(report);\n setSelected(undefined);\n },\n });\n })();\n }, [data, lazy, selected, scope, browse, report, setSelected]);\n\n const mutable = selected && (selected.kind === \"directory\" || selected.kind === \"document\");\n\n // Copy or move the selected document, or every document under the selected\n // folder, into another scope. Hidden when the data layer cannot do it.\n const canTransfer = !!data.documentsTransfer && !!mutable;\n const transferSelected = useCallback(() => {\n if (!selected) return;\n if (selected.kind === \"document\") {\n const id = (selected.resourceRef as { document_id?: string } | undefined)?.document_id;\n if (!id) {\n setErr(\"this document entry has no document_id\");\n return;\n }\n setTransfer({ documentId: id, fromPath: selected.fullPath });\n return;\n }\n setTransfer({ underPath: selected.fullPath, fromPath: selected.fullPath });\n }, [selected]);\n // After a real copy or move: a move took the selection out of this scope; a\n // copy into this scope added names under the new path.\n const transferDone = useCallback(\n (req: TransferRequest) => {\n if (req.op === \"move\") {\n void invalidate(req.from, { dropSubtree: true }).catch(report);\n setTrail([]);\n setSelected(undefined);\n return;\n }\n if (req.toScope === scope) void invalidate(req.to).catch(report);\n },\n [invalidate, report, scope, setSelected],\n );\n\n // The document on screen: the trail's last entry while references are being\n // followed, else the document the tree selection names.\n const view = useMemo<DocLocation | undefined>(() => {\n if (trail.length > 0) return trail[trail.length - 1];\n if (selected?.kind !== \"document\") return undefined;\n return {\n documentId: (selected.resourceRef as { document_id?: string })?.document_id ?? \"\",\n path: selected.fullPath,\n title: selected.name,\n };\n }, [trail, selected]);\n\n // openDocument follows a reference into another document. The tree follows\n // when that document's path is known: first from the directories already\n // listed, then by asking the data layer. Until (or unless) a path turns up the\n // document is open by id, with the tree selection cleared.\n const openDocument = useCallback(\n (target: DocLocation, from: DocLocation) => {\n const seq = ++navSeq.current;\n const known = findDocumentPath(lazy.getSnapshot(), target.documentId);\n setTrail(followReference(trail, { ...from, path: view?.path }, { ...target, path: known }));\n applySelection(known);\n if (known || !data.documentPath) return;\n data.documentPath(target.documentId, scope, browse).then(\n (p) => {\n if (!p || navSeq.current !== seq) return;\n setTrail((t) => amendCurrent(t, target.documentId, { path: p }));\n applySelection(p);\n },\n () => {}, // best-effort: the document is already open by id\n );\n },\n [data, lazy, trail, view?.path, scope, browse, applySelection],\n );\n\n // jumpToCrumb returns to an earlier document on the trail (Back = the previous\n // one), restoring the chunk that was selected there.\n const jumpToCrumb = useCallback(\n (index: number) => {\n const next = jumpTo(trail, index);\n if (next === trail) return;\n navSeq.current++;\n setTrail(next);\n applySelection(next[next.length - 1].path);\n },\n [trail, applySelection],\n );\n\n const onDocTitle = useCallback(\n (documentId: string, title: string) => setTrail((t) => amendCurrent(t, documentId, { title })),\n [],\n );\n\n // A pick in the navigator. Another chunk of the open document moves the\n // viewer in place; another document opens as a fresh navigation — by its Path\n // name when it has one (so the tree follows), else by id.\n const onNavigatorSelect = useCallback(\n (sel: NavigatorSelection & { documentId: string }) => {\n setFocus((f) => ({\n documentId: sel.documentId,\n chunkId: sel.chunkId,\n seq: (f?.seq ?? 0) + 1,\n }));\n if (view?.documentId === sel.documentId) return;\n if (sel.path) {\n setSelected(sel.path);\n return;\n }\n navSeq.current++;\n setTrail([{ documentId: sel.documentId, chunkId: sel.chunkId }]);\n applySelection(undefined);\n },\n [view?.documentId, setSelected, applySelection],\n );\n\n const navigatorCtx = useMemo<NavigatorContext>(\n () => ({\n scope,\n browse,\n selection: {\n documentId: view?.documentId,\n chunkId:\n liveChunk && liveChunk.documentId === view?.documentId ? liveChunk.chunkId : undefined,\n path: view?.path,\n },\n onSelect: onNavigatorSelect,\n reloadToken: navReload,\n maximized,\n onToggleMaximize: () => setMaximized((m) => !m),\n subject: principal?.subject,\n }),\n [\n scope,\n browse,\n view?.documentId,\n view?.path,\n liveChunk,\n onNavigatorSelect,\n navReload,\n maximized,\n principal?.subject,\n ],\n );\n const focusForView = focus && view && focus.documentId === view.documentId ? focus : undefined;\n\n // rename / delete act on the tree's selected entry, so they are offered only\n // when that entry IS the document on screen (not while its path is unknown, or\n // its directory is still being listed).\n const viewIsSelected =\n !!view?.path && selected?.kind === \"document\" && selected.fullPath === view.path;\n\n return (\n <>\n <Splitter\n className={starsOn ? \"paths-view paths-view--stars\" : \"paths-view\"}\n defaultLeftWidth={starsOn ? 720 : 420}\n minLeftWidth={280}\n minRightWidth={300}\n storageKey={starsOn ? \"loomcycle.explorer.split.stars\" : \"loomcycle.explorer.split.paths\"}\n hideRight={starsOn && maximized}\n >\n <div className=\"left\">\n <div className=\"paths-toolbar\">\n <label className=\"paths-scope\">\n <span>scope</span>\n <select value={scope} onChange={(e) => setScope(e.target.value as PathScope)}>\n <option value=\"user\">user</option>\n <option value=\"agent\">agent</option>\n <option value=\"tenant\">tenant</option>\n </select>\n </label>\n {renderNavigator && (\n <div className=\"paths-nav-switch\" role=\"group\" aria-label=\"Navigator\">\n <button\n type=\"button\"\n aria-pressed={!starsOn}\n className={!starsOn ? \"active\" : undefined}\n onClick={() => setNavMode(\"tree\")}\n title=\"Browse the Path tree\"\n >\n tree\n </button>\n <button\n type=\"button\"\n aria-pressed={starsOn}\n className={starsOn ? \"active\" : undefined}\n onClick={() => setNavMode(\"stars\")}\n title=\"Browse the scope as a 3D star map\"\n >\n stars\n </button>\n </div>\n )}\n <div className=\"paths-toolbar-actions\">\n {!starsOn && (\n <>\n <button\n type=\"button\"\n onClick={newFolder}\n title={`New folder in ${currentDirLabel}`}\n >\n + folder\n </button>\n <button\n type=\"button\"\n onClick={newDocument}\n title={`New document in ${currentDirLabel}`}\n >\n + document\n </button>\n </>\n )}\n <button type=\"button\" onClick={() => void refresh()} title=\"Reload the tree\">\n ↻\n </button>\n </div>\n </div>\n {!starsOn && (\n <p className=\"paths-context\">\n new items → <code>{currentDirLabel}</code>\n {browse?.scopeId && (\n <>\n {\" · \"}subject <code>{browse.scopeId}</code>\n </>\n )}\n {browse?.tenant && (\n <>\n {\" · \"}tenant <code>{browse.tenant}</code>\n </>\n )}\n </p>\n )}\n {(err || rootErr) && <div className=\"paths-err\">{err || rootErr}</div>}\n {starsOn && renderNavigator ? (\n <div className=\"paths-navigator\">{renderNavigator(navigatorCtx)}</div>\n ) : (\n <PathTree\n tree={tree}\n root={dirs.get(\"\")}\n expanded={expanded}\n onToggle={toggle}\n onLoadMore={loadMore}\n onRetry={retry}\n selectedPath={selectedPath}\n onSelect={(n) => setSelected(n.fullPath)}\n summaries={summaries}\n />\n )}\n </div>\n <div className=\"right\">\n {view ? (\n <div className=\"paths-doc\">\n <DocTrail trail={trail} onJump={jumpToCrumb} />\n <div className=\"paths-doc-head\">\n {view.path ? (\n <code className=\"paths-doc-path\">{view.path}</code>\n ) : (\n <span\n className=\"paths-doc-path paths-doc-unfiled\"\n title=\"Opened by id — no entry for this document was found in the Path tree\"\n >\n {labelOf(view)} <em>· opened by id, not in the tree</em>\n </span>\n )}\n {viewIsSelected && (\n <div className=\"paths-detail-actions\">\n <button type=\"button\" onClick={renameSelected}>\n rename / move\n </button>\n {canTransfer && (\n <button type=\"button\" onClick={transferSelected} title=\"Copy or move to another scope\">\n copy / move to…\n </button>\n )}\n <button type=\"button\" className=\"danger\" onClick={deleteSelected}>\n delete\n </button>\n </div>\n )}\n </div>\n {/* Keyed on the trail depth: every step along the trail changes it,\n so the viewer remounts and lands on that step's chunk. A plain\n tree selection (depth 0) keeps the viewer mounted, as before. */}\n <DocumentViewerBody\n key={trail.length}\n documentId={view.documentId}\n scope={scope}\n titleHint={view.title}\n browse={browse}\n principal={principal}\n renderAssistant={renderAssistant}\n initialChunkId={view.chunkId ?? focusForView?.chunkId}\n onOpenDocument={openDocument}\n onTitle={onDocTitle}\n onChunkSelect={(chunkId) => setLiveChunk({ documentId: view.documentId, chunkId })}\n focusChunk={focusForView}\n onRegenerateAnnotation={onRegenerateAnnotation}\n canEditAnnotations={canEditAnnotations}\n onAnnotationChanged={() => void refresh()}\n />\n </div>\n ) : selected ? (\n <div className=\"paths-detail\">\n <h2>\n <span className=\"paths-detail-kind\">{selected.kind}</span>\n <code>{selected.fullPath}</code>\n </h2>\n <dl className=\"paths-detail-meta\">\n <dt>scope</dt>\n <dd>{scope}</dd>\n {storedLabel && (\n <>\n <dt>stored</dt>\n <dd>{storedLabel}</dd>\n </>\n )}\n </dl>\n {mutable ? (\n <div className=\"paths-detail-actions\">\n <button type=\"button\" onClick={renameSelected}>\n rename / move\n </button>\n {canTransfer && (\n <button type=\"button\" onClick={transferSelected} title=\"Copy or move to another scope\">\n copy / move to…\n </button>\n )}\n <button type=\"button\" className=\"danger\" onClick={deleteSelected}>\n delete\n </button>\n </div>\n ) : (\n <p className=\"paths-readonly\">\n Read-only — {selected.kind} entries are managed by their own tool.\n </p>\n )}\n </div>\n ) : (\n <div className=\"empty\">\n <p>Select a path on the left, or create a folder / document.</p>\n </div>\n )}\n </div>\n </Splitter>\n {modal && <PromptModal state={modal} onClose={() => setModal(null)} />}\n {transfer && (\n <TransferModal\n data={data}\n scope={scope}\n browse={browse}\n documentId={transfer.documentId}\n underPath={transfer.underPath}\n fromPath={transfer.fromPath}\n onClose={() => setTransfer(null)}\n onDone={transferDone}\n />\n )}\n </>\n );\n}\n\n// PromptModal is a minimal create/rename/confirm dialog reusing the shared\n// .modal-* anchors. Zero fields + a message renders a confirm; submit errors\n// (incl. tool refusals surfaced by the data layer) show inline.\nfunction PromptModal({ state, onClose }: { state: ModalState; onClose: () => void }) {\n const [vals, setVals] = useState<Record<string, string>>(() =>\n Object.fromEntries(state.fields.map((f) => [f.key, f.value ?? \"\"])),\n );\n const [busy, setBusy] = useState(false);\n const [err, setErr] = useState<string | null>(null);\n\n const submit = async (e: FormEvent) => {\n e.preventDefault();\n setBusy(true);\n setErr(null);\n try {\n await state.onSubmit(vals);\n onClose();\n } catch (ex) {\n setErr(ex instanceof Error ? ex.message : String(ex));\n setBusy(false);\n }\n };\n\n return (\n <div className=\"modal-overlay\" onClick={onClose}>\n <form className=\"modal\" onClick={(e) => e.stopPropagation()} onSubmit={submit}>\n {/* RFC BN P1: Save/Cancel pinned to the top for consistency with the chunk editor. */}\n <div className=\"modal-header sticky-top\">\n <h3>{state.title}</h3>\n <div className=\"modal-buttons modal-buttons-top\">\n <button type=\"button\" onClick={onClose} disabled={busy}>\n cancel\n </button>\n <button type=\"submit\" className={state.danger ? \"danger\" : \"primary\"} disabled={busy}>\n {busy ? \"working…\" : state.submitLabel}\n </button>\n </div>\n </div>\n {state.message && <p className=\"modal-context\">{state.message}</p>}\n {state.fields.map((f, i) => (\n <label key={f.key} className=\"path-field\">\n <span>{f.label}</span>\n <input\n className=\"path-modal-input\"\n value={vals[f.key]}\n placeholder={f.placeholder}\n autoFocus={i === 0}\n onChange={(e) => setVals((v) => ({ ...v, [f.key]: e.target.value }))}\n />\n </label>\n ))}\n {err && <div className=\"modal-err\">{err}</div>}\n </form>\n </div>\n );\n}\n","import { useCallback, useEffect, useRef, useState, type ReactNode } from \"react\";\nimport type { AnnotationTarget, AssistantContext, BrowseScope, DocScope, Principal } from \"./types\";\nimport {\n ExplorerRoot,\n useResolvedDataLayer,\n type ExplorerDataSource,\n} from \"./components/ExplorerRoot\";\nimport { amendCurrent, followReference, jumpTo, type DocLocation, type Trail } from \"./lib/docTrail\";\nimport DocTrail from \"./components/DocTrail\";\nimport DocumentViewerBody from \"./components/DocumentViewerBody\";\n\n// DocumentViewer is the standalone, self-styling root for one chunked-graph\n// document (RFC AK) — the chunk tree + Markdown view + chunk editor. Mount it\n// on its own (a deep-link page) or let <PathExplorer> embed the shared body for\n// a document dirent. It resolves its own data layer + wraps in the themeable\n// `.loomcycle-explorer` root; styles ship separately:\n// `import \"@loomcycle/explorer/styles.css\"`.\n//\n// `documentId` is the document the host opened. A reference into ANOTHER\n// document is followed in place — the viewer shows that document and a\n// breadcrumb back — unless the host takes navigation over with onOpenDocument.\nexport interface DocumentViewerProps extends ExplorerDataSource {\n documentId: string;\n /** The chunk to open on, in place of the document's root: a section a link\n * or a search hit named. An id that is not one of the document's chunks\n * (another document's, a deleted one) lands on the root. Changing it while\n * documentId stays the same moves the selection without reloading. */\n chunkId?: string;\n scope: DocScope;\n /** Shown until the root chunk's title loads. */\n titleHint?: string;\n /** RFC AS browse-by-subject override threaded into every document call. */\n browse?: BrowseScope;\n /** Theming. Set → the root carries data-theme; omit → inherit an ancestor's\n * data-theme (dark is the default palette). */\n theme?: \"light\" | \"dark\";\n /** Authenticated principal — only `subject` is read (passed to renderAssistant). */\n principal?: Principal;\n /** Optional Document Assistant slot. Provide it to show an \"assistant\" toggle\n * that renders the returned node into the panel; omit → no assistant. */\n renderAssistant?: (ctx: AssistantContext) => ReactNode;\n /** Take over \"open another document\" (a followed cross-document reference),\n * e.g. to route to it. `target` is the document + chunk to open; `from` is\n * the document being left, with the chunk selected in it. Omit → the viewer\n * swaps the document itself and keeps a breadcrumb trail back. */\n onOpenDocument?: (target: DocLocation, from: DocLocation) => void;\n /** Have an annotation written again (tenant-scope documents). The host owns\n * how — typically by starting the annotating agent's run; the viewer reloads\n * the annotation when the returned promise settles. Omit → no Regenerate. */\n onRegenerateAnnotation?: (target: AnnotationTarget) => void | Promise<void>;\n /** Whether the reader may edit annotations by hand (the operator plane; the\n * runtime refuses anyone else). Default false: no Edit is offered. */\n canEditAnnotations?: boolean;\n}\n\nexport default function DocumentViewer(props: DocumentViewerProps) {\n const { documentId, scope, browse, theme } = props;\n const resolved = useResolvedDataLayer(props);\n return (\n <ExplorerRoot theme={theme} dataLayer={resolved}>\n {/* Keyed on what the host opened: a new document / scope / subject from the\n host is a fresh navigation, and drops the trail. */}\n <DocumentViewerHost\n key={`${scope}:${documentId}:${browse?.scopeId ?? \"\"}:${browse?.tenant ?? \"\"}`}\n {...props}\n />\n </ExplorerRoot>\n );\n}\n\n// DocumentViewerHost owns the trail for the standalone viewer: the document on\n// screen is the trail's last entry, or the host's `documentId` until a reference\n// has been followed.\nfunction DocumentViewerHost({\n documentId,\n chunkId,\n scope,\n titleHint,\n browse,\n principal,\n renderAssistant,\n onOpenDocument,\n onRegenerateAnnotation,\n canEditAnnotations,\n}: DocumentViewerProps) {\n const [trail, setTrail] = useState<Trail>([]);\n const current = trail[trail.length - 1];\n\n // The host's chunk: the landing chunk on mount, and later changes of it\n // move the selection in the mounted document (focusChunk), or — when the\n // reader has followed a reference elsewhere — bring them back to the host's\n // document at that chunk.\n const [focus, setFocus] = useState<{ chunkId?: string; seq: number }>();\n const hostChunk = useRef(chunkId);\n useEffect(() => {\n if (chunkId === hostChunk.current) return;\n hostChunk.current = chunkId;\n if (trail.length > 0) {\n // Back to the host's document: the body remounts and lands on chunkId,\n // so no earlier focus request may be replayed into it.\n setFocus(undefined);\n setTrail([]);\n } else setFocus((f) => ({ chunkId, seq: (f?.seq ?? 0) + 1 }));\n // trail is read, not watched: only a change of the host's chunk moves here.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [chunkId]);\n\n const open = useCallback(\n (target: DocLocation, from: DocLocation) => {\n if (onOpenDocument) onOpenDocument(target, from);\n else setTrail((t) => followReference(t, from, target));\n },\n [onOpenDocument],\n );\n const jump = useCallback((index: number) => setTrail((t) => jumpTo(t, index)), []);\n const onTitle = useCallback(\n (id: string, title: string) => setTrail((t) => amendCurrent(t, id, { title })),\n [],\n );\n\n return (\n <>\n <DocTrail trail={trail} onJump={jump} />\n {/* Keyed on the trail depth so each step remounts the viewer and lands on\n that step's chunk. */}\n <DocumentViewerBody\n key={trail.length}\n documentId={current?.documentId ?? documentId}\n scope={scope}\n titleHint={current ? current.title : titleHint}\n browse={browse}\n principal={principal}\n renderAssistant={renderAssistant}\n initialChunkId={current ? current.chunkId : chunkId}\n focusChunk={current ? undefined : focus}\n onOpenDocument={open}\n onTitle={onTitle}\n onRegenerateAnnotation={onRegenerateAnnotation}\n canEditAnnotations={canEditAnnotations}\n />\n </>\n );\n}\n"],"mappings":"A,stBAMA,IAAauF,EAAgB,+BAE7B,SAAgBC,EAAkB,EAA8D,CAC9F,GAAI,CACF,OAAOC,GAAS,QAAA,8BAAqB,IAAM,QAAU,QAAU,MACjE,MAAQ,CACN,MAAO,MACT,CACF,CAEA,SAAgBC,EACd,EACA,EACM,CACN,GAA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AAc+E,EAC5B,QACP,UAAW/E,EAAUA,EAAQ,MAAQyqB,EAC7B,SACG,YACM,kBACjB,eAAgBzqB,EAAUA,EAAQ,QAAUmC,EAC5C,WAAYnC,EAAU,IAAA,GAAY+wB,EAClC,eAAgBva,EACP,UACe,yBACJ,oBACrB,EAbM1M,EAAM,MAaZ,CACD,CAAA,CAAA,CAEN,C"}
1
+ {"version":3,"file":"index.cjs","names":["createContext","useContext","LoomcycleClient","createContext","useRef","useContext","useState","useId","useCallback","createPortal","_Fragment","useMemo","useState","useState","useMemo","useState","useRef","useCallback","_Fragment","useState","useCallback","useMemo","useContext","useState","_Fragment","useRef","useState","lazy","useState","useMemo","Suspense","useState","useState","useMemo","_Fragment","useState","useMemo","_Fragment","useContext","_Fragment","_Fragment","useState","useState","useRef","useState","_Fragment","useState","_Fragment","_Fragment","useState","_Fragment","ReactMarkdown","remarkGfm","_Fragment","useState","useRef","useId","_Fragment","useState","useCallback","useState","NARROW_PX","useMemo","useState","useRef","useCallback","_Fragment","memo","_Fragment","useState","useRef","useId","_Fragment","useState","useRef","useCallback","useMemo","useSyncExternalStore","useId","_Fragment","useState","useRef","useCallback","_Fragment","__create","__defProp","__getOwnPropDesc","__getOwnPropNames","__getProtoOf","__hasOwnProp","__copyProps","from","keys","i","n","key","to","except","k","desc","__toESM","mod","isNodeMode","target","react","react_jsx_runtime","_loomcycle_client","react_dom","react_markdown","remark_gfm","NAVIGATOR_KEY","readNavigatorMode","storage","writeNavigatorMode","mode","isSubjectRoot","chunk","entityTypeNames","classes","described","names","c","name","kind","a","b","subjectTypeChoices","cur","current","inForce","t","transferInput","input","r","trimSlash","transferProblem","transferSummary","res","verb","op","lines","parts","plural","m","refused","d","u","f","transferBlocked","dropDangling","p","end","one","many","annotationsApply","scope","BRIEF_MAX_CHARS","ABSTRACT_MAX_CHARS","LEVELS","isLevel","v","usableAnnotations","records","chunkId","loadAnnotations","data","browse","annotationLevelFor","isRoot","codePoints","s","annotationDraftProblem","brief","abstract","setAnnotationInput","edit","writtenByLabel","writtenBy","writtenAtLabel","writtenAt","filenameFromContentDisposition","header","star","baseName","quoted","token","errorMessageFromBody","o","text","status","statusText","fileStem","title","saveBlob","url","blob","filename","DOCUMENT_PATH_PAGES","DOCUMENT_PATH_PAGE_LIMIT","nonEmpty","out","dataLayerFromClient","reviewOps","client","jsonPost","page","cursor","resp","hit","documentId","req","opts","parentId","afterId","patch","mediaType","dataBase64","reason","includeMetadata","limit","fromRevision","toRevision","assetFetch","q","documentExportPath","format","tenantQuery","scopeIdOf","rulingId","scopeId","ExplorerDataContext","ExplorerDataProvider","useExplorerData","LS_MAX_LIMIT","lsTarget","dir","parentPathOf","idx","fullPath","ancestorsOf","segs","path","errMessage","listingOf","l","before","LazyPathTree","pageLimit","listing","fn","tracked","prev","shown","want","ep","e","running","last","dirs","keepSet","keep","listSubtree","next","documentIdsOf","ids","entries","id","createLoomcycleClient","impl","init","assetFetchFromConnection","doFetch","headers","RequestError","message","code","jsonPostFromConnection","body","parsed","CardCacheContext","CardCacheProvider","cache","CardScopeContext","mergeInfo","extra","base","useAnnotationCard","shared","local","specRef","spec","open","setOpen","loaded","setLoaded","anchor","cardEl","timer","pressed","seq","clear","close","show","onScroll","el","vw","vh","w","h","below","top","left","anchorRef","press","info","loading","host","card","CardBody","meta","rowSummary","row","chunkCard","inline","src","listed","documentCard","known","x","useButtonCard","useResolvedDataLayer","dataLayer","connection","ExplorerRoot","themeAttr","theme","followReference","trail","origin","defined","jumpTo","index","amendCurrent","labelOf","loc","collapseTrail","all","length","max","tail","hidden","findDocumentPath","documentIdOf","entry","landingChunk","wanted","rows","DocTrail","showAll","setShowAll","previous","items","onJump","item","TransferModal","setOp","toScope","setToScope","setTo","fromPath","setDropDangling","checked","setChecked","done","setDone","busy","setBusy","err","setErr","underPath","problem","blocked","submit","onClose","real","onDone","ex","label","line","HANDLE_WIDTH","Splitter","restore","storageKey","stored","minLeftWidth","defaultLeftWidth","leftWidth","setLeftWidth","widthKey","setWidthKey","containerRef","dragging","setDragging","onPointerDown","onPointerMove","rect","raw","maxAllowed","minRightWidth","onPointerUp","className","hideRight","hideLeft","leftRail","children","onHandleDoubleClick","IMAGE_MEDIA_TYPES","isSupportedImage","type","readImageAsBase64","file","reject","reader","result","comma","resolve","imageFileFromPaste","it","EDGE_PAGE_CAP","loadDocumentEdges","edges","after","maxPages","ORDINARY_METHODS","QUOTE_MAX","statusLabel","methodLabel","isProposed","formatNsDate","ns","validityLabel","until","verdictHint","head","evidencePreview","total","clipQuote","quote","RULING_CHUNK","QUEUE_CHANGED_RETRIES","MAX_CHUNKS","isQueueChanged","runRuling","sel","dryRun","api","confirm","hooks","why","dry","retries","e2","undoRulings","rulingIds","revert","chunkCount","matched","reviewScopeFor","bulkReviewScope","documentProposals","reviewPanel","ruleDocumentProposals","rulingNote","action","isStringArray","classificationRecord","fields","rec","pendingClassification","proposedTags","statementCount","resultLabel","report","classDisposition","canApply","formatShare","share","STEP_LABELS","stepLabel","step","candidateDetail","summarizeStep","acceptSummary","notices","skipped","classifyErrorText","msg","copyToClipboard","ENTRIES","downloadEntries","runDownload","save","DEFAULT_SCHEME","TINT_ALPHA","effectiveScheme","scheme","lookup","docColor","chunkColor","chunkInheritsDocColor","hexToTint","hex","alpha","tintStyle","color","bg","washStyle","chunkRowStyle","chunkRowColor","parseable","documentColor","own","inherited","ROW_TINT_ALPHA","ROW_WASH_ALPHA","rowTint","tint","wash","chunkRowTint","statusDotColor","TreeIcon","ICON_PATHS","TreeMarks","bare","statusColor","TreeItem","isOpen","expandable","expanded","selected","depth","tabbable","rowClassName","style","onSelect","onToggle","icon","marks","count","treeKeyDown","at","caret","move","ch","buildChunkTree","byId","chunks","roots","node","sortRec","nodes","typeIcon","DocumentChunkTree","setExpanded","toggle","selectedId","parents","ancestorIds","tree","mutated","tintScheme","colorEnabled","briefsListed","someRow","tabStop","ChunkTreeNode","test","walk","hasChildren","isSelected","documentType","documentStatus","cardScope","linkedIds","AnnotationBrief","record","StaleBadge","AnnotationPanel","defaultOpen","editing","setEditing","busyLevel","setBusyLevel","onSave","onRegenerate","regenerate","level","anyStale","anyManual","AnnotationEditor","newLevel","initialBrief","initialAbstract","setBrief","setAbstract","saving","setSaving","onCancel","mermaidSeq","flowchartNode","MermaidDiagram","ref","state","setState","cancelled","mermaid","attr","dark","onNodeClick","CodeEditor","parseJsonLoad","loadParseJson","ChunkEditorModal","setTitle","setType","setStatus","setBody","fieldsText","setFieldsText","tagsText","setTagsText","conflict","setConflict","isMermaid","isImage","bodyLanguage","preview","setPreview","parseJson","setParseJson","fieldsError","fieldsDiagnostics","replaceImage","b64","onSaved","bodyLabel","SubjectTypeModal","setInForce","choice","setChoice","notice","setNotice","types","choices","unchanged","updated","Classification","answer","setAnswer","accepting","setAccepting","acceptErr","setAcceptErr","accepted","setAccepted","pending","rootFields","requestKey","apply","onChanged","accept","acceptedSummary","ClassifyAnswerView","disposition","issuers","concepts","steps","written","iss","j","normalizeHex","ColorSchemeEditor","root","setRoot","enabled","setEnabled","setScheme","set","docType","docStatus","chunkStatuses","rootChunkId","setColor","fieldsWith","existing","copyToType","targets","documents","applied","tr","docKeys","chunkKeys","ColorRow","value","onChange","ChunkTarget","external","targetDocumentId","onOpenDocument","onSelectChunk","StatementMeta","statement","method","verdict","validity","ev","more","StatementReview","rejecting","setRejecting","setReason","rule","onRule","SAMPLE","ProposalReview","setSelected","setStep","setResult","confirmRef","proposals","picked","begin","reasonFor","ok","undo","allPicked","noneToRule","incomplete","BulkConfirm","onAnswer","RELATED_LIMIT","MENTIONS_LIMIT","isEmbedderError","Connections","setLoading","loadedId","setLoadedId","backlinks","setBacklinks","related","setRelated","relatedNote","setRelatedNote","mentions","setMentions","mentionsTruncated","setMentionsTruncated","refreshKey","ready","review","GRAPH_CAP","CrossReferences","showGraph","setShowGraph","refs","graphEdges","graphDef","buildGraph","RefRow","graphEndpoint","outgoing","edge","otherId","otherTitle","otherDoc","onRuleStatement","nodeId","arrow","DocUnavailable","detail","formatTs","ms","createdAt","HistoryModal","chunkTitle","HistoryView","revisions","setRevisions","setMode","selectedRev","setSelectedRev","fromRev","setFromRev","toRev","setToRev","diff","setDiff","revs","nums","viewVersion","rev","runDiff","DiffView","cls","ln","BARE_BREAK","kids","remarkBareBreak","Markdown","MD_COMPONENTS","source","href","lang","MoreMenu","groups","g","openAt","setOpenAt","rootRef","buttonRef","itemRefs","menuId","onDown","focusItem","onItemKeyDown","MoreGlyph","group","PaneIcon","PANE_PATHS","CollapseButton","shortcut","side","PaneRail","counted","countLabel","onExpand","readStored","writeStored","usePersistedFlag","setValue","fallback","usePersistedChoice","isTypingTarget","tag","shortcutApplies","useNarrow","narrow","setNarrow","measure","ro","imageAlt","DETAIL_BATCH","PANELS","PANEL_LABEL","PANEL_KEY","OUTLINE_KEY","NARROW_PX$1","OVERLAY_PX","OVERLAY_WITH_OUTLINE_PX","DocumentViewerBody","browseProp","setChunks","setSelectedId","details","setDetails","detailErrs","setDetailErrs","sourceOpen","setSourceOpen","fileInputRef","retyping","setRetyping","historyFor","setHistoryFor","confirmDelete","setConfirmDelete","loadedFor","setLoadedFor","loadErr","setLoadErr","reload","setReload","assistantOpen","setAssistantOpen","setMeta","colorsOpen","setColorsOpen","setEdges","edgesIncomplete","setEdgesIncomplete","edgesReload","setEdgesReload","classifyKey","setClassifyKey","setRootFields","docAnnotations","setDocAnnotations","chunkAnnotations","setChunkAnnotations","annotationReload","setAnnotationReload","panel","setPanelStored","panelTouched","setPanelTouched","setPanel","outlineCollapsed","setOutlineCollapsed","viewerRef","narrowOutline","setNarrowOutline","outlineHidden","overlay","setOutlineHidden","hide","downloading","setDownloading","copied","setCopied","refresh","hardReload","initialChunkRef","initialChunkId","onTitleRef","onTitle","pageRef","pinRef","pinnedTop","pinSeq","setPinSeq","goTo","flat","rootTitle","titleHint","selectedDetail","rootDetail","onChunkSelectRef","onChunkSelect","headerTint","rootRow","selectedIdRef","detailsRef","batch","got","unavailable","loadedTitle","pendingCount","classificationPending","annotationOpen","saveAnnotation","canEditAnnotations","onAnnotationChanged","regenerateAnnotation","onRegenerateAnnotation","folder","documentBrief","selectedAnnotations","annotationOffered","ruleStatement","reviewScope","onReviewChanged","refCount","focusSeq","focusChunk","focusRef","chunksRef","release","followRef","order","visible","follow","best","io","openDocument","canCreate","addImageFile","parent","created","addDiagram","currentIsRoot","addText","insertAfter","addChild","siblingBounds","sibs","reorderSelected","direction","deleteSelected","onPaste","ae","copy","what","pickChunk","toggleSource","copyChunkId","download","classifyOffered","offered","openPanel","togglePanel","lastPanel","keysRef","onKey","docCard","annotationStale","currentTitle","menuGroups","renderAssistant","documentActions","docLink","pathLabel","BarIcon","ChunkSection","RailButton","principal","Heading","onPick","onToggleSource","onHistory","onCopyId","onEdit","ChunkBody","RAIL_ICON","dot","ChunkImage","error","setUrl","made","buildLazyTree","opens","folderDocuments","ad","formatCount","capped","filtered","KIND_ICON","isAnnotationEntry","nodeBrief","ann","documentSummaryOf","summaries","nodeCard","summary","PathTree","props","visibleChildren","isDrawn","PathTreeNode","ListingRows","indent","onRetry","onLoadMore","isDir","selectedPath","coloured","searchHits","filterMark","searchCurrent","CreateMenu","onNewFolder","onNewDocument","breadcrumbSegments","Breadcrumb","Segment","cardFor","onFolder","onClick","NO_FILTER","filterActive","STATUS_SUGGESTIONS","findCoverage","rootListing","coverageLabel","lsFilters","autoOpen","room","budget","tried","fold","searchListed","query","inside","docMatches","filterTree","nameOnly","kept","isFolder","under","filterChoices","statuses","trees","sort","NAME_RE","SCOPES","TREE_KEY","NARROW_PX","TREE_WIDTH_PX","FILTER_DEBOUNCE_MS","NO_DIRS","noDirs","noSubscribe","joinPath","findNode","PathExplorer","resolved","PathExplorerBody","pathProp","navigatorProp","setScope","defaultScope","internalSelected","setInternalSelected","modal","setModal","transfer","setTransfer","onPathChangeRef","onPathChange","onErrorRef","onError","setTrail","navSeq","emittedPath","applySelection","lazy","findOpen","setFindOpen","findMode","setFindMode","setQuery","filter","setFilter","filtering","asked","setAsked","localFilterIn","setLocalFilterIn","localOnly","askedKey","flazy","fdirs","filterOpen","setFilterOpen","autoTried","froot","serverFiltered","fsettled","ftree","navMode","setNavModeState","renderNavigator","starsOn","setNavMode","setMaximized","maximized","navReload","setNavReload","consoleRef","treeCollapsed","setTreeCollapsed","narrowTree","setNarrowTree","treeHidden","setTreeHidden","liveChunk","setLiveChunk","focus","setFocus","invalidate","setSummaries","requested","summaryGen","resetSummaries","firstLoad","revealedIn","switched","ancestors","fresh","gen","hitAt","setHitAt","findInput","serverTree","coverage","listId","typeWidened","toggleFiltered","shownLazy","loadMore","retry","rootErr","selectedAnnotation","selectedDir","setStored","storedLabel","currentDir","currentDirLabel","searchBase","setSearchBase","searching","hits","hitSet","above","treeBox","openFind","closeFind","by","newFolder","newDocument","renameSelected","subtree","docIds","mutable","canTransfer","transferSelected","transferDone","view","jumpToCrumb","onDocTitle","onNavigatorSelect","navigatorCtx","focusForView","viewIsSelected","pick","revealFolder","crumbCard","segment","isDocument","folderCard","PromptModal","vals","setVals","DocumentViewer","DocumentViewerHost","hostChunk","jump"],"sources":["../src/lib/navigator.ts","../src/lib/subjectType.ts","../src/lib/transfer.ts","../src/lib/annotation.ts","../src/lib/download.ts","../src/lib/dataLayer.tsx","../src/lib/lazyPathTree.ts","../src/lib/createClient.ts","../src/components/AnnotationCard.tsx","../src/components/ExplorerRoot.tsx","../src/lib/docTrail.ts","../src/components/DocTrail.tsx","../src/components/TransferModal.tsx","../src/components/Splitter.tsx","../src/lib/imageUpload.ts","../src/lib/edgePages.ts","../src/lib/statement.ts","../src/lib/ruling.ts","../src/lib/bulkReview.ts","../src/lib/classify.ts","../src/lib/clipboard.ts","../src/lib/documentDownload.ts","../src/lib/colorScheme.ts","../src/components/TreeRow.tsx","../src/components/DocumentChunkTree.tsx","../src/components/AnnotationPanel.tsx","../src/components/Mermaid.tsx","../src/components/ChunkEditorModal.tsx","../src/components/SubjectTypeModal.tsx","../src/components/Classification.tsx","../src/components/ColorSchemeEditor.tsx","../src/components/ChunkTarget.tsx","../src/components/Statement.tsx","../src/components/ProposalReview.tsx","../src/components/Connections.tsx","../src/components/CrossReferences.tsx","../src/components/DocUnavailable.tsx","../src/components/HistoryModal.tsx","../src/lib/remarkBareBreak.ts","../src/components/Markdown.tsx","../src/components/MoreMenu.tsx","../src/components/Pane.tsx","../src/lib/persisted.ts","../src/lib/useNarrow.ts","../src/components/DocumentViewerBody.tsx","../src/components/PathTree.tsx","../src/components/CreateMenu.tsx","../src/components/Breadcrumb.tsx","../src/lib/treeFind.ts","../src/PathExplorer.tsx","../src/DocumentViewer.tsx"],"sourcesContent":["// The explorer's navigator choice: the Path tree (the default) or the slot a\n// host provides (the 3D star map). Remembered per browser; storage failures\n// (private mode, blocked site data) fall back to the tree.\n\nexport type NavigatorMode = \"tree\" | \"stars\";\n\nexport const NAVIGATOR_KEY = \"loomcycle.explorer.navigator\";\n\nexport function readNavigatorMode(storage: Pick<Storage, \"getItem\"> | undefined): NavigatorMode {\n try {\n return storage?.getItem(NAVIGATOR_KEY) === \"stars\" ? \"stars\" : \"tree\";\n } catch {\n return \"tree\";\n }\n}\n\nexport function writeNavigatorMode(\n storage: Pick<Storage, \"setItem\"> | undefined,\n mode: NavigatorMode,\n): void {\n try {\n storage?.setItem(NAVIGATOR_KEY, mode);\n } catch {\n // Blocked storage: the choice lasts for this page only.\n }\n}\n","import type { ChunkDetail } from \"../types\";\n\n// A subject is a document whose ROOT chunk is the entity node: it carries a natural\n// key. A keyed chunk below a root is a fact filed under a subject, not a subject, and\n// re-typing it is an ordinary chunk edit.\nexport function isSubjectRoot(chunk: ChunkDetail | null | undefined): boolean {\n return !!chunk && !chunk.parent_id && !!chunk.entity?.natural_key;\n}\n\n// entityTypeNames reads the entity types in force out of a describe_ontology answer:\n// its chunk classes, sorted. A document class types a document, never the subject a\n// document is about, so it is left out. Anything unexpected reads as no types.\nexport function entityTypeNames(described: unknown): string[] {\n const classes = (described as { classes?: unknown } | null)?.classes;\n if (!Array.isArray(classes)) return [];\n const names = new Set<string>();\n for (const c of classes) {\n const { name, kind } = (c ?? {}) as { name?: unknown; kind?: unknown };\n if (typeof name === \"string\" && name !== \"\" && kind !== \"document\") names.add(name);\n }\n return [...names].sort((a, b) => a.localeCompare(b));\n}\n\n// subjectTypeChoices is what the change-type picker offers: the types in force, and\n// the subject's current type even when it is not one of them, so the picker can show\n// where the subject stands rather than silently preselecting something else.\nexport function subjectTypeChoices(inForce: string[], current: string | undefined): string[] {\n const cur = current ?? \"\";\n if (cur === \"\" || inForce.some((t) => t.toLowerCase() === cur.toLowerCase())) return inForce;\n return [cur, ...inForce];\n}\n","// transfer.ts — the explorer's \"copy / move\" of a document or a folder's\n// documents into another scope (the Document tool's copy_documents and\n// move_documents). Pure: the request the dialog sends and the lines it shows,\n// kept apart from the component so both are tested without a DOM.\n\nimport type { DocScope } from \"../types\";\n\nexport type TransferOp = \"copy\" | \"move\";\n\n// TransferRequest is what the dialog asks for. A document is named by id (its\n// own path names no folder to list); a folder by its path, every document at or\n// under it. `from` → `to` rewrites the names on the way.\nexport interface TransferRequest {\n op: TransferOp;\n scope: DocScope;\n toScope: DocScope;\n documentId?: string;\n underPath?: string;\n from: string;\n to: string;\n dropDangling?: boolean;\n dryRun: boolean;\n expectCount?: number;\n}\n\nexport interface TransferRefusal {\n document_id: string;\n code: string;\n detail?: string;\n}\n\nexport interface TransferDangling {\n statement_id: string;\n kind: string;\n from: string;\n to: string;\n outside: \"from\" | \"to\" | \"evidence\" | string;\n}\n\n// TransferResult is the answer of both ops, dry run or not. Fields a call did\n// not produce are absent.\nexport interface TransferResult {\n dry_run: boolean;\n documents: { id: string; new_id?: string; paths: string[]; resumed?: boolean }[];\n counts: Record<string, number>;\n refused: TransferRefusal[];\n refused_count?: number;\n dangling: TransferDangling[];\n dangling_count: number;\n blocked_by?: string;\n dropped?: number;\n moved?: string[];\n to_finish?: string[];\n unfinished?: { document_id: string; code: string; detail?: string }[];\n name_failures?: { document_id: string; path: string; error: string }[];\n body_failures?: number;\n statements_failed?: number;\n statement_error?: string;\n}\n\n// transferInput is the Document tool input for a request.\nexport function transferInput(r: TransferRequest): Record<string, unknown> {\n const input: Record<string, unknown> = {\n op: r.op === \"copy\" ? \"copy_documents\" : \"move_documents\",\n scope: r.scope,\n to_scope: r.toScope,\n dry_run: r.dryRun,\n };\n if (r.documentId) input.document_ids = [r.documentId];\n if (r.underPath) input.under_path = r.underPath;\n const from = trimSlash(r.from);\n const to = trimSlash(r.to);\n if (from && to && from !== to) input.path_map = { [from]: to };\n if (r.op === \"move\") {\n if (r.dropDangling) input.dangling = \"drop\";\n if (!r.dryRun) input.expect_count = r.expectCount ?? 0;\n }\n return input;\n}\n\n// transferProblem is why a request cannot be sent, or null.\nexport function transferProblem(r: TransferRequest): string | null {\n const to = r.to.trim();\n if (!to.startsWith(\"/\")) return \"the new path must start with /\";\n if (r.op === \"move\" && r.toScope === r.scope) {\n return \"a move goes to another scope; to rename within this one, use rename / move\";\n }\n if (r.op === \"copy\" && r.toScope === r.scope && trimSlash(to) === trimSlash(r.from)) {\n return \"a copy into the same scope needs a new path\";\n }\n return null;\n}\n\n// transferSummary is the lines the dialog shows for an answer: what will happen\n// (a dry run) or what did (a real call), then what stands in the way.\nexport function transferSummary(op: TransferOp, res: TransferResult): string[] {\n const c = res.counts ?? {};\n const n = c.documents ?? 0;\n const verb = op === \"copy\" ? \"copied\" : \"moved\";\n const lines: string[] = [];\n const parts = `${c.chunks ?? 0} parts, ${c.revisions ?? 0} revisions, ${c.statements ?? 0} relations, ${c.assets ?? 0} images`;\n if (res.dry_run) {\n lines.push(`${n} ${plural(n, \"document\")} would be ${verb}: ${parts}.`);\n if (res.to_finish?.length) {\n lines.push(`${res.to_finish.length} ${plural(res.to_finish.length, \"document\")} left by an earlier interrupted move will be finished.`);\n }\n } else if (op === \"move\") {\n const m = res.moved?.length ?? 0;\n lines.push(`${m} ${plural(m, \"document\")} moved: ${parts}.`);\n } else {\n lines.push(`${n} ${plural(n, \"document\")} copied: ${parts}.`);\n }\n const refused = res.refused_count ?? res.refused?.length ?? 0;\n if (refused > 0) {\n lines.push(`${refused} ${plural(refused, \"document\")} refused:`);\n for (const r of res.refused ?? []) lines.push(` ${r.document_id}: ${r.code}${r.detail ? ` — ${r.detail}` : \"\"}`);\n }\n if (res.dangling_count > 0) {\n if (op === \"copy\") {\n lines.push(`${res.dangling_count} ${plural(res.dangling_count, \"relation\")} to documents outside the set stay behind.`);\n } else if (res.dropped !== undefined) {\n lines.push(`${res.dropped} ${plural(res.dropped, \"relation\")} to documents outside the set were dropped.`);\n } else if (res.blocked_by === \"dangling_relations\") {\n lines.push(\n `${res.dangling_count} ${plural(res.dangling_count, \"relation\")} join these documents to ones outside the set. ` +\n \"A relation cannot span two scopes: include the other documents, or drop these relations.\",\n );\n } else {\n lines.push(`${res.dangling_count} ${plural(res.dangling_count, \"relation\")} to documents outside the set will be dropped.`);\n }\n for (const d of res.dangling ?? []) lines.push(` ${d.kind}: ${d.from} → ${d.to} (outside: ${d.outside})`);\n }\n for (const u of res.unfinished ?? []) {\n lines.push(`not finished: ${u.document_id}: ${u.code}${u.detail ? ` — ${u.detail}` : \"\"}. Run the move again.`);\n }\n for (const f of res.name_failures ?? []) lines.push(`no name ${f.path} for ${f.document_id}: ${f.error}`);\n if (res.body_failures) lines.push(`${res.body_failures} ${plural(res.body_failures, \"body\", \"bodies\")} could not be written.`);\n if (res.statements_failed) {\n lines.push(`${res.statements_failed} ${plural(res.statements_failed, \"relation\")} could not be written${res.statement_error ? `: ${res.statement_error}` : \"\"}.`);\n }\n return lines;\n}\n\n// transferBlocked: the real call would be refused as the dry run stands.\nexport function transferBlocked(op: TransferOp, res: TransferResult, dropDangling: boolean): boolean {\n if (op === \"move\" && res.dangling_count > 0 && !dropDangling) return true;\n return (res.counts?.documents ?? 0) === 0 && !(res.to_finish?.length ?? 0);\n}\n\n// trimSlash drops trailing slashes, keeping a lone \"/\". A loop, not /\\/+$/: that\n// regex backtracks polynomially on a long run of slashes not at the end.\nfunction trimSlash(p: string): string {\n const t = p.trim();\n let end = t.length;\n while (end > 1 && t[end - 1] === \"/\") end--;\n return t.slice(0, end);\n}\n\nfunction plural(n: number, one: string, many = one + \"s\"): string {\n return n === 1 ? one : many;\n}\n","import type { Annotation, AnnotationEdit, AnnotationLevel, BrowseScope, DocScope } from \"../types\";\nimport type { ExplorerDataLayer } from \"./dataLayer\";\n\n// Annotations live only in the tenant scope: the runtime refuses to write one\n// anywhere else and reads return nothing. The viewer therefore makes no call at\n// all for another scope rather than asking a question whose answer is known.\nexport function annotationsApply(scope: DocScope): boolean {\n return scope === \"tenant\";\n}\n\n// The runtime's length caps, in characters (Unicode code points, as the runtime\n// counts them). The editor checks them before sending so an over-long draft is\n// named in place instead of coming back as a refusal.\nexport const BRIEF_MAX_CHARS = 240;\nexport const ABSTRACT_MAX_CHARS = 2000;\n\nconst LEVELS: readonly AnnotationLevel[] = [\"branch\", \"document\", \"path\", \"scheme\", \"concept\", \"class\"];\n\nfunction isLevel(v: unknown): v is AnnotationLevel {\n return typeof v === \"string\" && (LEVELS as readonly string[]).includes(v);\n}\n\n// usableAnnotations keeps the records that describe `chunkId` and carry a\n// brief, ordered branch → document → path. A record that would render as an\n// empty panel is dropped, not padded: nothing here is ever written in place of\n// a missing record.\nexport function usableAnnotations(records: unknown, chunkId: string): Annotation[] {\n if (!Array.isArray(records)) return [];\n return records\n .filter(\n (r): r is Annotation =>\n !!r &&\n typeof r === \"object\" &&\n (r as Annotation).chunk_id === chunkId &&\n isLevel((r as Annotation).level) &&\n typeof (r as Annotation).brief === \"string\" &&\n (r as Annotation).brief.trim() !== \"\",\n )\n .sort((a, b) => LEVELS.indexOf(a.level) - LEVELS.indexOf(b.level));\n}\n\n// loadAnnotations fetches a chunk's records. It answers [] without a call when\n// the scope holds no annotations or the data layer cannot read them.\nexport async function loadAnnotations(\n data: Pick<ExplorerDataLayer, \"documentGetAnnotation\">,\n chunkId: string,\n scope: DocScope,\n browse?: BrowseScope,\n): Promise<Annotation[]> {\n if (!annotationsApply(scope) || !data.documentGetAnnotation || !chunkId) return [];\n const resp = await data.documentGetAnnotation(chunkId, scope, browse);\n return usableAnnotations(resp?.annotations, chunkId);\n}\n\n// annotationLevelFor is the level a new annotation of a chunk takes: the root\n// chunk stands for the whole document, any other chunk is a branch.\nexport function annotationLevelFor(isRoot: boolean): AnnotationLevel {\n return isRoot ? \"document\" : \"branch\";\n}\n\n// codePoints counts characters the way the runtime does (a surrogate pair is\n// one character, not two).\nexport function codePoints(s: string): number {\n return [...s].length;\n}\n\n// annotationDraftProblem says what is wrong with an edit before it is sent, or\n// undefined when it can go.\nexport function annotationDraftProblem(brief: string, abstract: string): string | undefined {\n if (brief.trim() === \"\") return \"The brief is required.\";\n if (codePoints(brief) > BRIEF_MAX_CHARS) return `The brief is longer than ${BRIEF_MAX_CHARS} characters.`;\n if (abstract.trim() === \"\") return \"The abstract is required.\";\n if (codePoints(abstract) > ABSTRACT_MAX_CHARS) {\n return `The abstract is longer than ${ABSTRACT_MAX_CHARS} characters.`;\n }\n return undefined;\n}\n\n// setAnnotationInput is the wire input of an operator's edit: always a manual\n// record (the background walk then leaves it alone), and never an inputs hash,\n// so the runtime stores the hash of the text as it is now.\nexport function setAnnotationInput(edit: AnnotationEdit, scope: DocScope): Record<string, unknown> {\n return {\n op: \"set_annotation\",\n scope,\n id: edit.id,\n level: edit.level,\n brief: edit.brief.trim(),\n abstract: edit.abstract.trim(),\n manual: true,\n };\n}\n\n// writtenByLabel renders a record's writer for the provenance line.\nexport function writtenByLabel(writtenBy: string | undefined): string | undefined {\n if (!writtenBy) return undefined;\n if (writtenBy.startsWith(\"run:\")) return `run ${writtenBy.slice(4)}`;\n if (writtenBy.startsWith(\"principal:\")) return writtenBy.slice(10);\n return writtenBy;\n}\n\n// writtenAtLabel renders the write time in the reader's locale; an unparseable\n// value is shown as the runtime sent it.\nexport function writtenAtLabel(writtenAt: string | undefined): string | undefined {\n if (!writtenAt) return undefined;\n const t = Date.parse(writtenAt);\n return Number.isNaN(t) ? writtenAt : new Date(t).toLocaleString();\n}\n\n// ANNOTATION_ENTRY is the reserved Path name of a folder's annotation document.\nexport const ANNOTATION_ENTRY = \"_annotation\";\n","// Helpers for handing a file to the browser: the document downloads (RFC BS\n// .md / .canvas, RFC GR rendered files) share them.\n\n/** The file formats the runtime renders a document into (RFC GR). */\nexport type RenderFormat = \"pdf\" | \"docx\" | \"odt\" | \"epub\" | \"html\" | \"md\";\n\n/** Options of a rendered export — `GET /v1/_document/export/{id}`. Unset\n * options are left to the server's defaults. */\nexport interface DocumentExportOptions {\n /** Render only the subtree under this chunk. */\n chunk?: string;\n toc?: boolean;\n titlePage?: boolean;\n pageSize?: \"a4\" | \"letter\";\n language?: string;\n /** false leaves the provenance note out (the server puts it in by default). */\n provenance?: boolean;\n}\n\n/** The file name a Content-Disposition header names: the RFC 8187\n * `filename*=UTF-8''…` form first (it carries non-ASCII names), then the plain\n * `filename=\"…\"` / `filename=token` fallback. Undefined when it names none, or\n * only an undecodable `filename*` with no fallback. Any directory part is\n * dropped — the name is used as a download name, never a path. */\nexport function filenameFromContentDisposition(header: string | null | undefined): string | undefined {\n if (!header) return undefined;\n const star = /filename\\*\\s*=\\s*([^']*)'[^']*'([^;]+)/i.exec(header);\n if (star && /^utf-8$/i.test(star[1]!.trim())) {\n try {\n const name = baseName(decodeURIComponent(star[2]!.trim()));\n if (name) return name;\n } catch {\n // malformed percent-encoding: fall back to the plain parameter\n }\n }\n const quoted = /(?:^|;)\\s*filename\\s*=\\s*\"((?:[^\"\\\\]|\\\\.)*)\"/i.exec(header);\n if (quoted) return baseName(quoted[1]!.replace(/\\\\(.)/g, \"$1\")) || undefined;\n const token = /(?:^|;)\\s*filename\\s*=\\s*([^;\\s\"]+)/i.exec(header);\n if (token) return baseName(token[1]!) || undefined;\n return undefined;\n}\n\nfunction baseName(name: string): string {\n return name.slice(Math.max(name.lastIndexOf(\"/\"), name.lastIndexOf(\"\\\\\")) + 1).trim();\n}\n\n/** The message of a refused request: the `error` field of the runtime's\n * `{\"code\",\"error\"}` body, else the status line (e.g. a proxy's HTML page). */\nexport function errorMessageFromBody(text: string, status: number, statusText = \"\"): string {\n try {\n const o = JSON.parse(text) as { error?: unknown };\n if (typeof o.error === \"string\" && o.error) return o.error;\n } catch {\n // not JSON\n }\n return `${status} ${statusText}`.trim();\n}\n\n/** A title made safe as a file-name stem — the rule the .md download has\n * always used. */\nexport function fileStem(title: string | undefined): string {\n return (title || \"document\").replace(/[^\\w.-]+/g, \"_\");\n}\n\n/** Hand a Blob to the browser as a download named `filename`. The object URL\n * is revoked on the next tick, not at once: some browsers start reading the\n * blob only after click() returns. */\nexport function saveBlob(blob: Blob, filename: string): void {\n const url = URL.createObjectURL(blob);\n const a = document.createElement(\"a\");\n a.href = url;\n a.download = filename;\n a.click();\n setTimeout(() => URL.revokeObjectURL(url), 0);\n}\n","import { createContext, useContext, type ReactNode } from \"react\";\nimport type { LoomcycleClient, DocumentToolInput } from \"@loomcycle/client\";\nimport type {\n AcceptClassificationAnswer,\n Annotation,\n AnnotationEdit,\n Backlink,\n BrowseScope,\n CanvasDoc,\n ChunkDetail,\n ChunkRevision,\n ChunkRow,\n ClassifyAnswer,\n ClassifyWrite,\n DocEdge,\n DocScope,\n PathEntry,\n StatementStatus,\n PathScope,\n RelatedChunk,\n UnlinkedMention,\n} from \"../types\";\nimport type { DocSummary, DocumentMeta } from \"./colorScheme\";\nimport type { AssetFetch, JsonPost } from \"./createClient\";\nimport type { RulingCounts, RulingRequest } from \"./ruling\";\nimport { entityTypeNames } from \"./subjectType\";\nimport { transferInput, type TransferRequest, type TransferResult } from \"./transfer\";\nimport { setAnnotationInput } from \"./annotation\";\nimport {\n errorMessageFromBody,\n filenameFromContentDisposition,\n type DocumentExportOptions,\n type RenderFormat,\n} from \"./download\";\n\n// ChunkPatch is the subset of chunk fields update_chunk accepts. `fields` is\n// unknown (arbitrary typed JSON the chunk carries); a blank/absent value leaves\n// the existing fields untouched (the caller only sends what changed).\nexport interface ChunkPatch {\n body?: string;\n fields?: unknown;\n title?: string;\n status?: string;\n type?: string;\n // tags (RFC BS) replace-set the chunk's whole tag set when present ([] clears);\n // the editor always sends the parsed set, so it is authoritative for what shows.\n tags?: string[];\n}\n\n// DocRulingFilter is the review queue filter a document's bulk ruling sends:\n// the statements filed from that document.\nexport interface DocRulingFilter {\n from_document_id: string;\n}\n\n// DocRulingAnswer is a bulk ruling's answer (POST /v1/_statements/rule): the\n// counts runRuling reads, and on a dry run a sample and a breakdown.\nexport interface DocRulingAnswer extends RulingCounts {\n sample?: DocEdge[] | null;\n breakdown?: { kind: string; method: string; count: number }[] | null;\n}\n\n// DocRevertAnswer is a ruling's undo (POST /v1/_statements/revert).\nexport interface DocRevertAnswer {\n ruling_id: string;\n reverted: number;\n changed: number;\n}\n\n// PathLsPage selects one page of an `ls`: `limit` bounds it (the runtime clamps\n// it to 5000), `cursor` is a previous page's next_cursor, passed back verbatim.\n//\n// withCounts and filters are RFC HA's, for a one-level listing only: counts add\n// `documents` to the entries; filters keep only what leads to a matching\n// document, and the runtime echoes what it applied as `filters` on the answer.\n// A runtime before RFC HA ignores both — the answer then carries no echo.\nexport interface PathLsPage {\n limit?: number;\n cursor?: string;\n withCounts?: boolean;\n filters?: PathLsFilters;\n}\n\n// PathLsFilters are the filters of a one-level ls (RFC HA), as on the wire:\n// `name_contains` matches a document's Path name or title, ignoring case;\n// `type` takes in its subtypes; `status` is exact.\nexport interface PathLsFilters {\n name_contains?: string;\n type?: string;\n status?: string;\n}\n\n// DocEdgesPage is one get_edges page: truncated + next_cursor are present only\n// when more edges follow.\nexport interface DocEdgesPage {\n edges: DocEdge[];\n truncated?: boolean;\n next_cursor?: string;\n}\n\nexport interface PathLsResult {\n path: string;\n entries: PathEntry[];\n truncated?: boolean;\n next_cursor?: string;\n // RFC HA: the filters a filtered listing applied (its echo), and the\n // subtypes a `type` filter took in.\n filters?: PathLsFilters;\n type_expanded_to?: string[];\n}\n\n// ExplorerDataLayer is the narrow data contract the Path / Document components\n// need — the ten off-run reads/writes the browser makes. Decoupling behind this\n// interface lets a host inject the default client-backed implementation\n// (dataLayerFromClient), or a custom one (e.g. a cookie-authed same-origin\n// fetcher) without the components importing any global api module. Every method\n// takes an optional `browse` (RFC AS browse-by-subject) threaded to the runtime.\nexport interface ExplorerDataLayer {\n // pathLs lists one directory (or, recursive, a whole subtree, flat). The\n // runtime pages every listing (default 500 entries, max 5000): a clipped page\n // reports truncated + next_cursor, and passing that back as `page.cursor`\n // continues it. A custom data layer that returns neither reads as complete.\n pathLs(\n path: string,\n scope: PathScope,\n recursive: boolean,\n browse?: BrowseScope,\n page?: PathLsPage,\n ): Promise<PathLsResult>;\n // pathIsStored reports whether a path has its own dirent (false: an implicit\n // directory, one that exists only through its descendants). A one-level ls\n // reports both as plain `directory` entries, so this is the only way to tell\n // them apart. Optional: without it the detail pane omits its \"stored\" row.\n pathIsStored?(path: string, scope: PathScope, browse?: BrowseScope): Promise<boolean>;\n // documentPath answers \"where is this document in the Path tree\" — the reverse\n // of a dirent, which the runtime has no index for (a dirent names a document;\n // a document does not know its names). It lets the tree follow a document that\n // was opened by id, i.e. reached through a reference. undefined = no dirent\n // found: the document is still readable by id. Optional — without it the tree\n // only follows documents in directories it has already listed.\n documentPath?(\n documentId: string,\n scope: PathScope,\n browse?: BrowseScope,\n ): Promise<string | undefined>;\n pathMkdir(\n path: string,\n scope: PathScope,\n browse?: BrowseScope,\n ): Promise<unknown>;\n pathMv(\n from: string,\n to: string,\n scope: PathScope,\n browse?: BrowseScope,\n ): Promise<unknown>;\n pathRm(\n path: string,\n scope: PathScope,\n recursive: boolean,\n browse?: BrowseScope,\n ): Promise<unknown>;\n documentCreate(\n title: string,\n path: string,\n scope: DocScope,\n browse?: BrowseScope,\n ): Promise<{\n document_id: string;\n root_chunk_id?: string;\n title?: string;\n path?: string;\n }>;\n documentDelete(\n id: string,\n scope: DocScope,\n browse?: BrowseScope,\n ): Promise<unknown>;\n // documentsTransfer copies or moves documents into another scope (the\n // Document tool's copy_documents / move_documents), dry run or real.\n // Optional: a data layer without it hides the explorer's copy / move action.\n documentsTransfer?(req: TransferRequest, browse?: BrowseScope): Promise<TransferResult>;\n documentGet(\n id: string,\n scope: DocScope,\n browse?: BrowseScope,\n ): Promise<DocumentMeta>;\n // documentsSummary returns per-document display metadata (type/status + RFC BN\n // color settings) for a set of ids and/or a Path subtree — the Path tree's\n // one-call coloring source (dirents carry only a document_id).\n documentsSummary(\n opts: { documentIds?: string[]; underPath?: string },\n scope: DocScope,\n browse?: BrowseScope,\n ): Promise<{ documents: DocSummary[] }>;\n documentQueryChunks(\n documentId: string,\n scope: DocScope,\n browse?: BrowseScope,\n ): Promise<{ chunks: ChunkRow[] }>;\n documentGetChunk(\n id: string,\n scope: DocScope,\n browse?: BrowseScope,\n ): Promise<ChunkDetail>;\n // documentCreateChunk creates a new chunk under a parent (RFC BO authoring).\n // afterId (RFC BP) inserts the new chunk immediately after that sibling\n // (server insert-and-shift); when set it overrides parentId.\n documentCreateChunk(\n documentId: string,\n parentId: string,\n patch: ChunkPatch,\n scope: DocScope,\n browse?: BrowseScope,\n afterId?: string,\n ): Promise<ChunkDetail>;\n // documentReorderChunk moves a chunk up/down within its level (RFC BP).\n documentReorderChunk(\n id: string,\n direction: \"up\" | \"down\",\n scope: DocScope,\n browse?: BrowseScope,\n ): Promise<unknown>;\n // documentDeleteChunk deletes a chunk + its subtree (RFC BP; existing\n // delete_chunk op — cascades, refuses the document root).\n documentDeleteChunk(\n id: string,\n scope: DocScope,\n browse?: BrowseScope,\n ): Promise<unknown>;\n // documentSetAsset attaches an image's base64 bytes to a chunk (→ type=image,\n // served by GET /v1/_document/asset/{id}). RFC BO.\n documentSetAsset(\n chunkId: string,\n mediaType: string,\n dataBase64: string,\n filename: string | undefined,\n scope: DocScope,\n browse?: BrowseScope,\n ): Promise<ChunkDetail>;\n // documentGetEdges returns one page of the cross-reference edges touching a\n // document (RFC BN P4) — the References list + relationship graph source. The\n // runtime pages them (500 a page, ordered by kind): a clipped page reports\n // truncated + next_cursor, and passing that back as `page.after` continues it.\n // loadDocumentEdges follows the pages. A custom data layer that returns\n // neither reads as complete.\n documentGetEdges(\n documentId: string,\n scope: DocScope,\n browse?: BrowseScope,\n page?: { after?: string },\n ): Promise<DocEdgesPage>;\n // RFC FN statement ops. Optional, like pathIsStored, so a custom data layer\n // written before them still satisfies the interface: without get_edge the\n // viewer only shows the evidence preview the listing carries, and without both\n // rulings it shows a proposal's status but no Accept / Reject.\n //\n // documentGetEdge returns one statement with ALL its evidence rows.\n documentGetEdge?(\n id: string,\n scope: DocScope,\n browse?: BrowseScope,\n ): Promise<{ statement: DocEdge }>;\n // documentAcceptStatement / documentRejectStatement are the operator's ruling on\n // a proposed statement. The runtime accepts them only from the off-run operator\n // plane (this console), never from an agent inside a run; a refusal rejects the\n // promise with the runtime's error text. A rejection needs a reason.\n documentAcceptStatement?(\n id: string,\n scope: DocScope,\n browse?: BrowseScope,\n reason?: string,\n ): Promise<{ id: string; status: StatementStatus }>;\n documentRejectStatement?(\n id: string,\n reason: string,\n scope: DocScope,\n browse?: BrowseScope,\n ): Promise<{ id: string; status: StatementStatus }>;\n // documentListStatements is the review queue: statements in a status\n // (the runtime defaults to \"proposed\"), paged by `after` = a previous page's\n // next_cursor.\n documentListStatements?(\n scope: DocScope,\n browse?: BrowseScope,\n opts?: { status?: StatementStatus; kind?: string; limit?: number; after?: string },\n ): Promise<{ statements: DocEdge[]; truncated?: boolean; next_cursor?: string }>;\n // RFC FS bulk rulings. Optional, like the single rulings: without\n // documentRuleStatements the Connections panel offers no bulk Accept / Reject,\n // and without documentRevertRuling no undo of one.\n //\n // documentRuleStatements is POST /v1/_statements/rule: a dry run unless\n // `dry_run` is false, and a real call must carry the dry run's `matched` as\n // `expect_count` (runRuling does both). `req.scope` is the review scope, and\n // with the user scope `req.scope_id` the subject whose documents (an\n // operator may name another; a member is refused). `browse.tenant` is an\n // admin's tenant focus. A refusal rejects with an error carrying the\n // server's `code` (queue_changed, forbidden, …).\n documentRuleStatements?(\n req: RulingRequest<DocRulingFilter>,\n browse?: BrowseScope,\n ): Promise<DocRulingAnswer>;\n // documentRevertRuling is POST /v1/_statements/revert: each statement the\n // ruling ruled and nothing changed since goes back to its earlier status.\n // With the user scope, browse.scopeId names the subject, as for the ruling.\n documentRevertRuling?(\n rulingId: string,\n scope: \"tenant\" | \"user\",\n browse?: BrowseScope,\n ): Promise<DocRevertAnswer>;\n // RFC FO classification ops. Optional, like the statement rulings: without\n // documentClassify the viewer offers no Classify action, and without\n // documentAcceptClassification a pending classification is not shown.\n //\n // documentClassify says what the document is from the confirmed ontology.\n // `report` writes nothing; `propose` applies a unique rule match and files the\n // rest for review. A refusal rejects with the runtime's error text.\n documentClassify?(\n documentId: string,\n write: ClassifyWrite,\n scope: DocScope,\n browse?: BrowseScope,\n ): Promise<ClassifyAnswer>;\n // documentAcceptClassification is the operator's acceptance of the pending\n // classification in the root's fields. Like the statement rulings, the runtime\n // takes it only from the off-run operator plane. Nothing pending rejects with\n // the runtime's nothing_pending error.\n documentAcceptClassification?(\n documentId: string,\n scope: DocScope,\n browse?: BrowseScope,\n ): Promise<AcceptClassificationAnswer>;\n // documentEntityTypes lists the entity types in force for the tenant (from\n // describe_ontology), for re-typing a subject. Optional: without it the viewer\n // offers no change-type action.\n documentEntityTypes?(scope: DocScope, browse?: BrowseScope): Promise<string[]>;\n // Annotation ops. Optional, like the rulings: without documentGetAnnotation\n // the viewer shows no annotations, and without documentSetAnnotation it offers\n // no Edit. Annotations exist only in the tenant scope; the viewer never calls\n // either for another scope.\n //\n // documentGetAnnotation returns every record of one chunk (a branch chunk, or a\n // document's root, which may carry both a document and a path record). No\n // record → an empty list.\n documentGetAnnotation?(\n chunkId: string,\n scope: DocScope,\n browse?: BrowseScope,\n ): Promise<{ annotations: Annotation[] }>;\n // documentSetAnnotation writes an operator's edit as a manual record. A\n // refusal rejects with the runtime's error text.\n documentSetAnnotation?(\n edit: AnnotationEdit,\n scope: DocScope,\n browse?: BrowseScope,\n ): Promise<{ annotation: Annotation }>;\n // documentAssetObjectUrl fetches an image chunk's bytes (RFC BO) WITH auth and\n // returns a blob object-URL for an <img src> — a bare <img src=/v1/...> can't\n // carry a bearer header. The CALLER must URL.revokeObjectURL when done. Absent\n // when the data source can't do a raw binary GET (a bare client with no\n // connection) → the viewer falls back to a placeholder.\n documentAssetObjectUrl?(\n chunkId: string,\n scope: DocScope,\n browse?: BrowseScope,\n ): Promise<string>;\n // documentExportFile renders the document into a file (RFC GR —\n // GET /v1/_document/export/{id}): PDF, Word, HTML or Markdown (a Markdown\n // render with pictures arrives as a .zip). `filename` is the server's\n // Content-Disposition name, \"\" when it sent none. A refusal rejects with the\n // server's message. Absent, like documentAssetObjectUrl, when the data source\n // can't do a raw binary GET → the viewer offers only the .md / .canvas\n // downloads.\n documentExportFile?(\n documentId: string,\n scope: DocScope,\n format: RenderFormat,\n browse?: BrowseScope,\n opts?: DocumentExportOptions,\n ): Promise<{ blob: Blob; filename: string }>;\n documentUpdateChunk(\n id: string,\n revision: number,\n patch: ChunkPatch,\n scope: DocScope,\n browse?: BrowseScope,\n ): Promise<ChunkDetail>;\n documentExportMd(\n documentId: string,\n scope: DocScope,\n includeMetadata: boolean,\n browse?: BrowseScope,\n ): Promise<{ markdown: string; title: string; document_id: string }>;\n // documentBacklinks returns the chunks that link TO this chunk (RFC BS) — the\n // \"what links here\" list, each enriched with the source's title/type/status +\n // whether the edge was auto-derived from a [[name]] wikilink.\n documentBacklinks(\n id: string,\n scope: DocScope,\n browse?: BrowseScope,\n ): Promise<{ backlinks: Backlink[] }>;\n // documentRelated returns semantic neighbours of a chunk (RFC BS, vector\n // similarity). It REFUSES when no embedder is configured — the caller catches\n // the error and shows a \"semantic search not configured\" note. limit caps the\n // result count (server default when omitted).\n documentRelated(\n id: string,\n scope: DocScope,\n browse?: BrowseScope,\n limit?: number,\n ): Promise<{ related: RelatedChunk[] }>;\n // documentUnlinkedMentions returns chunks that mention this chunk's title but\n // don't link to it (RFC BS) — candidate links. `truncated` flags an elided tail.\n documentUnlinkedMentions(\n id: string,\n scope: DocScope,\n browse?: BrowseScope,\n limit?: number,\n ): Promise<{ unlinked_mentions: UnlinkedMention[]; truncated: boolean }>;\n // documentHistory returns a chunk's edit history (RFC BS) — revision numbers +\n // timestamps + actors, newest-relevant first as the server orders them.\n documentHistory(\n id: string,\n scope: DocScope,\n browse?: BrowseScope,\n limit?: number,\n ): Promise<{ chunk_id: string; revisions: ChunkRevision[] }>;\n // documentGetVersion returns one historical revision's body verbatim (RFC BS).\n documentGetVersion(\n id: string,\n revision: number,\n scope: DocScope,\n browse?: BrowseScope,\n ): Promise<{ chunk_id: string; revision: number; body: string }>;\n // documentDiff returns a unified-diff text between two revisions of a chunk\n // (RFC BS) — from_revision → to_revision.\n documentDiff(\n id: string,\n fromRevision: number,\n toRevision: number,\n scope: DocScope,\n browse?: BrowseScope,\n ): Promise<{\n chunk_id: string;\n from_revision: number;\n to_revision: number;\n diff: string;\n }>;\n // documentExportCanvas returns the whole document as a node/edge canvas graph\n // (RFC BS), downloaded as a `.canvas` (JSON) file by the viewer.\n documentExportCanvas(\n documentId: string,\n scope: DocScope,\n browse?: BrowseScope,\n ): Promise<{ canvas: CanvasDoc; document_id: string }>;\n}\n\n// DOCUMENT_PATH_PAGES bounds the documentPath scan: that many pages of the\n// largest size the runtime serves. Subject-homed facts are document dirents too,\n// so a scope can hold tens of thousands; past the bound the lookup gives up and\n// the document simply opens without a tree position.\nconst DOCUMENT_PATH_PAGES = 4;\nconst DOCUMENT_PATH_PAGE_LIMIT = 5000;\n\n// nonEmpty keeps the filters that are set, so an unset one is not sent as \"\".\nfunction nonEmpty(f: PathLsFilters | undefined): PathLsFilters {\n const out: PathLsFilters = {};\n if (f?.name_contains) out.name_contains = f.name_contains;\n if (f?.type) out.type = f.type;\n if (f?.status) out.status = f.status;\n return out;\n}\n\n// dataLayerFromClient maps a @loomcycle/client instance onto the\n// ExplorerDataLayer. Path ops route to client.path (POST /v1/_path); document\n// ops to client.document (POST /v1/_document) — both op-discriminated.\n//\n// browse is passed straight through as the client's opts second argument: a\n// BrowseScope ({scopeId?, tenant?}) is structurally the client's browse opts, so\n// the SDK serializes it to ?scope_id= / ?tenant= (empty/undefined → the caller's\n// own subject, byte-identical to the pre-RFC-AS behaviour). Responses are\n// op-varying `unknown`, cast to the kept shapes the components consume.\n//\n// jsonPost (the connection path) reaches the RFC FS review routes when the\n// client has no method for them; see reviewOps.\nexport function dataLayerFromClient(\n client: LoomcycleClient,\n assetFetch?: AssetFetch,\n jsonPost?: JsonPost,\n): ExplorerDataLayer {\n return {\n ...reviewOps(client, jsonPost),\n pathLs: (path, scope, recursive, browse, page) =>\n client.path(\n {\n op: \"ls\",\n path,\n scope,\n recursive,\n ...(page?.limit ? { limit: page.limit } : {}),\n ...(page?.cursor ? { cursor: page.cursor } : {}),\n ...(page?.withCounts ? { with_counts: true } : {}),\n ...nonEmpty(page?.filters),\n },\n browse,\n ) as Promise<PathLsResult>,\n // stat refuses a path with no dirent; that refusal IS the answer \"implicit\"\n // here (the path came from a listing, so it exists). Any other failure —\n // network, auth — is not an answer and propagates. Matched by name, not\n // instanceof: the host's client may be a different copy of the package.\n pathIsStored: (path, scope, browse) =>\n client.path({ op: \"stat\", path, scope }, browse).then(\n () => true,\n (e: unknown) => {\n if ((e as { name?: string } | null)?.name === \"SubstrateToolRefusedError\") return false;\n throw e;\n },\n ),\n // One recursive listing of document dirents, followed page by page until the\n // document turns up.\n documentPath: async (documentId, scope, browse) => {\n let cursor: string | undefined;\n for (let page = 0; page < DOCUMENT_PATH_PAGES; page++) {\n const resp = (await client.path(\n {\n op: \"ls\",\n path: \"/\",\n scope,\n recursive: true,\n kind_filter: \"document\",\n limit: DOCUMENT_PATH_PAGE_LIMIT,\n ...(cursor ? { cursor } : {}),\n },\n browse,\n )) as PathLsResult;\n const hit = (resp.entries ?? []).find(\n (e) => (e.resource_ref as { document_id?: string } | undefined)?.document_id === documentId,\n );\n if (hit) return hit.full_path;\n cursor = resp.next_cursor || undefined;\n if (!cursor) return undefined;\n }\n return undefined;\n },\n pathMkdir: (path, scope, browse) =>\n client.path({ op: \"mkdir\", path, scope }, browse),\n pathMv: (from, to, scope, browse) =>\n client.path({ op: \"mv\", path: from, to, scope }, browse),\n pathRm: (path, scope, recursive, browse) =>\n client.path({ op: \"rm\", path, scope, recursive }, browse),\n // The `as unknown as DocumentToolInput` casts below are the same pinned-SDK\n // workaround documentReorderChunk already uses, for a different reason: the\n // published @loomcycle/client still types `scope` as \"agent\" | \"user\", from\n // when Documents refused tenant scope. The runtime has accepted tenant since\n // v1.41.0 and adapters/ts is fixed at source, so these casts come out on the\n // next client publish — they are not papering over a wire mismatch, they are\n // waiting for a version bump.\n documentCreate: (title, path, scope, browse) =>\n client.document(\n { op: \"create_document\", title, path, scope } as unknown as DocumentToolInput,\n browse,\n ) as Promise<{\n document_id: string;\n root_chunk_id?: string;\n title?: string;\n path?: string;\n }>,\n documentDelete: (id, scope, browse) =>\n client.document({ op: \"delete_document\", id, scope } as unknown as DocumentToolInput, browse),\n // copy_documents / move_documents are newer than the pinned SDK type; the\n // /v1/_document passthrough takes them verbatim.\n documentsTransfer: (req, browse) =>\n client.document(transferInput(req) as unknown as DocumentToolInput, browse) as Promise<TransferResult>,\n documentGet: (id, scope, browse) =>\n client.document({ op: \"get_document\", id, scope } as unknown as DocumentToolInput, browse) as Promise<DocumentMeta>,\n documentsSummary: (opts, scope, browse) =>\n client.document(\n // documents_summary + document_ids are RFC BN wire additions the pinned\n // SDK type doesn't enumerate; the /v1/_document passthrough accepts them\n // verbatim, so cast past DocumentToolInput (same pattern as update_chunk).\n {\n op: \"documents_summary\",\n scope,\n ...(opts.documentIds ? { document_ids: opts.documentIds } : {}),\n ...(opts.underPath ? { under_path: opts.underPath } : {}),\n } as unknown as DocumentToolInput,\n browse,\n ) as Promise<{ documents: DocSummary[] }>,\n documentQueryChunks: (documentId, scope, browse) =>\n client.document(\n // with_summary (RFC HA) puts each chunk's own brief on its row, so the\n // outline's hover cards need no call; an older runtime ignores it.\n {\n op: \"query_chunks\",\n document_id: documentId,\n scope,\n limit: 1000,\n with_summary: true,\n } as unknown as DocumentToolInput,\n browse,\n ) as Promise<{ chunks: ChunkRow[] }>,\n documentGetChunk: (id, scope, browse) =>\n client.document({ op: \"get_chunk\", id, scope } as unknown as DocumentToolInput, browse) as Promise<ChunkDetail>,\n documentCreateChunk: (documentId, parentId, patch, scope, browse, afterId) =>\n client.document(\n {\n op: \"create_chunk\",\n document_id: documentId,\n parent_id: parentId,\n scope,\n ...(afterId ? { after_id: afterId } : {}),\n ...patch,\n } as unknown as DocumentToolInput,\n browse,\n ) as Promise<ChunkDetail>,\n documentReorderChunk: (id, direction, scope, browse) =>\n client.document(\n // reorder_chunk is an RFC BP wire op the pinned SDK type doesn't\n // enumerate; the /v1/_document passthrough accepts it verbatim.\n { op: \"reorder_chunk\", id, direction, scope } as unknown as DocumentToolInput,\n browse,\n ),\n documentDeleteChunk: (id, scope, browse) =>\n client.document({ op: \"delete_chunk\", id, scope } as unknown as DocumentToolInput, browse),\n documentSetAsset: (chunkId, mediaType, dataBase64, filename, scope, browse) =>\n client.document(\n // set_asset is an RFC BO wire op the pinned SDK type doesn't enumerate;\n // the /v1/_document passthrough accepts it verbatim.\n {\n op: \"set_asset\",\n id: chunkId,\n media_type: mediaType,\n data: dataBase64,\n ...(filename ? { filename } : {}),\n scope,\n } as unknown as DocumentToolInput,\n browse,\n ) as Promise<ChunkDetail>,\n documentGetEdges: (documentId, scope, browse, page) =>\n client.document(\n // get_edges is an RFC BN P4 wire op the pinned SDK type doesn't\n // enumerate; the /v1/_document passthrough accepts it verbatim.\n {\n op: \"get_edges\",\n document_id: documentId,\n scope,\n ...(page?.after ? { after: page.after } : {}),\n } as unknown as DocumentToolInput,\n browse,\n ) as Promise<DocEdgesPage>,\n // RFC FN statement ops — the same passthrough cast: new wire ops the pinned\n // SDK type doesn't enumerate.\n documentGetEdge: (id, scope, browse) =>\n client.document(\n { op: \"get_edge\", id, scope } as unknown as DocumentToolInput,\n browse,\n ) as Promise<{ statement: DocEdge }>,\n documentAcceptStatement: (id, scope, browse, reason) =>\n client.document(\n {\n op: \"accept_statement\",\n id,\n scope,\n ...(reason ? { reason } : {}),\n } as unknown as DocumentToolInput,\n browse,\n ) as Promise<{ id: string; status: StatementStatus }>,\n documentRejectStatement: (id, reason, scope, browse) =>\n client.document(\n { op: \"reject_statement\", id, reason, scope } as unknown as DocumentToolInput,\n browse,\n ) as Promise<{ id: string; status: StatementStatus }>,\n documentListStatements: (scope, browse, opts) =>\n client.document(\n {\n op: \"list_statements\",\n scope,\n ...(opts?.status ? { status: opts.status } : {}),\n ...(opts?.kind ? { kind: opts.kind } : {}),\n ...(opts?.limit ? { limit: opts.limit } : {}),\n ...(opts?.after ? { after: opts.after } : {}),\n } as unknown as DocumentToolInput,\n browse,\n ) as Promise<{ statements: DocEdge[]; truncated?: boolean; next_cursor?: string }>,\n // RFC FO classification ops — the same passthrough cast.\n documentClassify: (documentId, write, scope, browse) =>\n client.document(\n { op: \"classify\", document_id: documentId, write, scope } as unknown as DocumentToolInput,\n browse,\n ) as Promise<ClassifyAnswer>,\n documentEntityTypes: (scope, browse) =>\n client\n .document({ op: \"describe_ontology\", scope } as unknown as DocumentToolInput, browse)\n .then(entityTypeNames),\n documentAcceptClassification: (documentId, scope, browse) =>\n client.document(\n { op: \"accept_classification\", document_id: documentId, scope } as unknown as DocumentToolInput,\n browse,\n ) as Promise<AcceptClassificationAnswer>,\n // Annotation ops — the same passthrough cast: wire ops newer than the\n // pinned SDK type.\n documentGetAnnotation: (chunkId, scope, browse) =>\n client.document(\n { op: \"get_annotation\", id: chunkId, scope } as unknown as DocumentToolInput,\n browse,\n ) as Promise<{ annotations: Annotation[] }>,\n documentSetAnnotation: (edit, scope, browse) =>\n client.document(setAnnotationInput(edit, scope) as unknown as DocumentToolInput, browse) as Promise<{\n annotation: Annotation;\n }>,\n documentUpdateChunk: (id, revision, patch, scope, browse) =>\n client.document(\n // `patch.fields` is unknown but DocumentToolInput.fields is a typed\n // Record; the cast reconciles the spread (the server accepts arbitrary\n // JSON there). Op order + arg names mirror the wire contract exactly.\n {\n op: \"update_chunk\",\n id,\n revision,\n scope,\n ...patch,\n } as DocumentToolInput,\n browse,\n ) as Promise<ChunkDetail>,\n documentExportMd: (documentId, scope, includeMetadata, browse) =>\n client.document(\n {\n op: \"export_md\",\n document_id: documentId,\n scope,\n include_metadata: includeMetadata,\n } as unknown as DocumentToolInput,\n browse,\n ) as Promise<{ markdown: string; title: string; document_id: string }>,\n // RFC BS document-connections + history + canvas ops. Same `as unknown as\n // DocumentToolInput` passthrough as documentGetEdges — new wire ops the pinned\n // SDK type doesn't enumerate; the /v1/_document passthrough accepts them\n // verbatim (adapters/ts is fixed at source, so the casts come out on the next\n // client publish).\n documentBacklinks: (id, scope, browse) =>\n client.document(\n { op: \"backlinks\", id, scope } as unknown as DocumentToolInput,\n browse,\n ) as Promise<{ backlinks: Backlink[] }>,\n documentRelated: (id, scope, browse, limit) =>\n client.document(\n {\n op: \"related\",\n id,\n scope,\n ...(limit ? { limit } : {}),\n } as unknown as DocumentToolInput,\n browse,\n ) as Promise<{ related: RelatedChunk[] }>,\n documentUnlinkedMentions: (id, scope, browse, limit) =>\n client.document(\n {\n op: \"unlinked_mentions\",\n id,\n scope,\n ...(limit ? { limit } : {}),\n } as unknown as DocumentToolInput,\n browse,\n ) as Promise<{ unlinked_mentions: UnlinkedMention[]; truncated: boolean }>,\n documentHistory: (id, scope, browse, limit) =>\n client.document(\n {\n op: \"history\",\n id,\n scope,\n ...(limit ? { limit } : {}),\n } as unknown as DocumentToolInput,\n browse,\n ) as Promise<{ chunk_id: string; revisions: ChunkRevision[] }>,\n documentGetVersion: (id, revision, scope, browse) =>\n client.document(\n { op: \"get_version\", id, revision, scope } as unknown as DocumentToolInput,\n browse,\n ) as Promise<{ chunk_id: string; revision: number; body: string }>,\n documentDiff: (id, fromRevision, toRevision, scope, browse) =>\n client.document(\n {\n op: \"diff\",\n id,\n from_revision: fromRevision,\n to_revision: toRevision,\n scope,\n } as unknown as DocumentToolInput,\n browse,\n ) as Promise<{\n chunk_id: string;\n from_revision: number;\n to_revision: number;\n diff: string;\n }>,\n documentExportCanvas: (documentId, scope, browse) =>\n client.document(\n { op: \"export_canvas\", document_id: documentId, scope } as unknown as DocumentToolInput,\n browse,\n ) as Promise<{ canvas: CanvasDoc; document_id: string }>,\n // Present only when an AssetFetch was supplied (the connection path); a bare\n // client can't do the raw binary GET, so the op is omitted and the viewer\n // shows a placeholder.\n ...(assetFetch\n ? {\n documentAssetObjectUrl: async (chunkId, scope, browse) => {\n const q = new URLSearchParams({ scope });\n if (browse?.scopeId) q.set(\"scope_id\", browse.scopeId);\n if (browse?.tenant) q.set(\"tenant\", browse.tenant);\n const resp = await assetFetch(\n `/v1/_document/asset/${encodeURIComponent(chunkId)}?${q.toString()}`,\n );\n if (!resp.ok) throw new Error(`asset fetch failed: ${resp.status}`);\n const blob = await resp.blob();\n return URL.createObjectURL(blob);\n },\n documentExportFile: async (documentId, scope, format, browse, opts) => {\n const resp = await assetFetch(documentExportPath(documentId, scope, format, browse, opts));\n if (!resp.ok) {\n throw new Error(errorMessageFromBody(await resp.text(), resp.status, resp.statusText));\n }\n const blob = await resp.blob();\n return {\n blob,\n filename: filenameFromContentDisposition(resp.headers.get(\"Content-Disposition\")) ?? \"\",\n };\n },\n }\n : {}),\n };\n}\n\n// documentExportPath builds the export route's path + query. Unset options are\n// left out, so the server's defaults apply.\nexport function documentExportPath(\n documentId: string,\n scope: DocScope,\n format: RenderFormat,\n browse?: BrowseScope,\n opts?: DocumentExportOptions,\n): string {\n const q = new URLSearchParams({ format, scope });\n if (browse?.scopeId) q.set(\"scope_id\", browse.scopeId);\n if (browse?.tenant) q.set(\"tenant\", browse.tenant);\n if (opts?.chunk) q.set(\"chunk\", opts.chunk);\n if (opts?.toc) q.set(\"toc\", \"true\");\n if (opts?.titlePage) q.set(\"title_page\", \"true\");\n if (opts?.pageSize) q.set(\"page_size\", opts.pageSize);\n if (opts?.language) q.set(\"language\", opts.language);\n if (opts?.provenance === false) q.set(\"provenance\", \"false\");\n return `/v1/_document/export/${encodeURIComponent(documentId)}?${q.toString()}`;\n}\n\n// ReviewClient is the part of a newer @loomcycle/client this package reads when\n// present: the review methods arrived after the client version it pins.\ninterface ReviewClient {\n ruleStatements?: (\n action: \"accept\" | \"reject\",\n select: { ids: string[] } | { filter: DocRulingFilter },\n opts: {\n reason?: string;\n dryRun?: boolean;\n expectCount?: number;\n max?: number;\n scope?: \"tenant\" | \"user\";\n scopeId?: string;\n tenant?: string;\n },\n ) => Promise<DocRulingAnswer>;\n revertRuling?: (\n rulingId: string,\n opts: { scope?: \"tenant\" | \"user\"; scopeId?: string; tenant?: string },\n ) => Promise<DocRevertAnswer>;\n}\n\n// reviewOps is the bulk ruling and its undo: through the client's own methods\n// when it has them, else a JSON POST over the connection, else absent — and\n// absent means the viewer offers no bulk action.\nfunction reviewOps(\n client: LoomcycleClient,\n jsonPost?: JsonPost,\n): Pick<ExplorerDataLayer, \"documentRuleStatements\" | \"documentRevertRuling\"> {\n const c = client as unknown as ReviewClient;\n const tenantQuery = (browse?: BrowseScope) => (browse?.tenant ? `?tenant=${encodeURIComponent(browse.tenant)}` : \"\");\n const out: Pick<ExplorerDataLayer, \"documentRuleStatements\" | \"documentRevertRuling\"> = {};\n if (typeof c.ruleStatements === \"function\") {\n out.documentRuleStatements = (req, browse) =>\n c.ruleStatements!(req.action, req.ids ? { ids: req.ids } : { filter: req.filter! }, {\n reason: req.reason,\n dryRun: req.dry_run,\n expectCount: req.expect_count,\n max: req.max,\n scope: req.scope,\n scopeId: req.scope_id,\n tenant: browse?.tenant,\n });\n } else if (jsonPost) {\n out.documentRuleStatements = (req, browse) =>\n jsonPost(`/v1/_statements/rule${tenantQuery(browse)}`, req) as Promise<DocRulingAnswer>;\n }\n // The subject whose user documents a revert acts on, as its ruling did.\n const scopeIdOf = (scope: \"tenant\" | \"user\", browse?: BrowseScope) =>\n scope === \"user\" && browse?.scopeId ? browse.scopeId : undefined;\n if (typeof c.revertRuling === \"function\") {\n out.documentRevertRuling = (rulingId, scope, browse) =>\n c.revertRuling!(rulingId, { scope, scopeId: scopeIdOf(scope, browse), tenant: browse?.tenant });\n } else if (jsonPost) {\n out.documentRevertRuling = (rulingId, scope, browse) => {\n const scopeId = scopeIdOf(scope, browse);\n return jsonPost(`/v1/_statements/revert${tenantQuery(browse)}`, {\n ruling_id: rulingId,\n scope,\n ...(scopeId ? { scope_id: scopeId } : {}),\n }) as Promise<DocRevertAnswer>;\n };\n }\n return out;\n}\n\n// The data layer reaches the components through context — no module-global\n// singleton. The root (<PathExplorer> / <DocumentViewer>) builds it once\n// (useMemo over connection identity) and provides it; nested panels/modals read\n// it via useExplorerData().\nconst ExplorerDataContext = createContext<ExplorerDataLayer | null>(null);\n\nexport function ExplorerDataProvider({\n value,\n children,\n}: {\n value: ExplorerDataLayer;\n children: ReactNode;\n}) {\n return (\n <ExplorerDataContext.Provider value={value}>\n {children}\n </ExplorerDataContext.Provider>\n );\n}\n\nexport function useExplorerData(): ExplorerDataLayer {\n const v = useContext(ExplorerDataContext);\n if (!v) {\n throw new Error(\n \"useExplorerData must be used within <PathExplorer> or <DocumentViewer> (no ExplorerDataLayer in context)\",\n );\n }\n return v;\n}\n","import type { BrowseScope, PathEntry, PathScope } from \"../types\";\nimport type { ExplorerDataLayer, PathLsFilters, PathLsResult } from \"./dataLayer\";\n\n// The Path tree is loaded one directory at a time, one page at a time.\n//\n// WHY NOT ONE RECURSIVE LISTING: the runtime pages every `ls` (500 entries by\n// default, 5000 at most) and orders a recursive one by full path. Subject-homed\n// facts make /facts as large as the tenant's entity count, so a single recursive\n// `ls /` filled its whole first page with /documents/* and /facts/* — and every\n// top-level directory sorting after \"facts\" silently vanished from the tree while\n// the data sat intact server-side. Following every cursor instead would still\n// fetch tens of thousands of dirents to draw a tree whose directories are\n// mostly collapsed. So a directory is listed only when it is opened, and a\n// directory too large for one page says so with a \"load more\" row rather than\n// dropping its tail.\n\n// LS_PAGE_LIMIT matches the runtime's default page; LS_MAX_LIMIT is its ceiling\n// (a larger limit is clamped server-side, so asking for more is pointless).\nexport const LS_PAGE_LIMIT = 500;\nexport const LS_MAX_LIMIT = 5000;\n\n// DirListing is one directory's load state. `entries` are in the runtime's page\n// order (by name), which is what makes \"the next segment is not in a later page\"\n// decidable in reveal.\nexport interface DirListing {\n entries: PathEntry[];\n nextCursor?: string; // set while more pages remain\n loaded: boolean; // at least one page has arrived\n loading: boolean;\n error?: string;\n // appliedFilters is the runtime's echo of the filters it applied to this\n // listing (RFC HA) — present only when it really filtered, which is how a\n // runtime that ignores the filters is told apart. typeExpandedTo lists the\n // subtypes a `type` filter took in.\n appliedFilters?: PathLsFilters;\n typeExpandedTo?: string[];\n}\n\n// ListingOptions are what every one-level listing of a tree asks for (RFC HA):\n// counts on the entries, and the filters a filtered tree is listed with.\nexport interface ListingOptions {\n withCounts?: boolean;\n filters?: PathLsFilters;\n}\n\n// DirMap keys a listing by directory path, spelled like PathNode.fullPath:\n// \"\" is the root, then \"/a\", \"/a/b\".\nexport type DirMap = ReadonlyMap<string, DirListing>;\n\n// lsTarget maps a directory key onto the path the runtime lists.\nexport function lsTarget(dir: string): string {\n return dir === \"\" ? \"/\" : dir;\n}\n\n// parentPathOf returns the canonical parent of a node path (\"\" = root).\nexport function parentPathOf(fullPath: string): string {\n const idx = fullPath.lastIndexOf(\"/\");\n return idx <= 0 ? \"\" : fullPath.slice(0, idx);\n}\n\n// ancestorsOf returns every directory that must be listed for `path` to show,\n// root first: \"/a/b/c\" → [\"\", \"/a\", \"/a/b\"].\nexport function ancestorsOf(path: string): string[] {\n const out = [\"\"];\n const segs = path.split(\"/\").filter(Boolean);\n let dir = \"\";\n for (let i = 0; i < segs.length - 1; i++) {\n dir = `${dir}/${segs[i]}`;\n out.push(dir);\n }\n return out;\n}\n\nfunction errMessage(e: unknown): string {\n return e instanceof Error ? e.message : String(e);\n}\n\nfunction listingOf(resp: PathLsResult, before: PathEntry[]): DirListing {\n const l: DirListing = {\n entries: [...before, ...(resp.entries ?? [])],\n nextCursor: resp.next_cursor || undefined,\n loaded: true,\n loading: false,\n };\n if (resp.filters && typeof resp.filters === \"object\") l.appliedFilters = resp.filters;\n if (Array.isArray(resp.type_expanded_to)) l.typeExpandedTo = resp.type_expanded_to;\n return l;\n}\n\n// LazyPathTree is the per-(scope, browse) cache of directory listings. It is a\n// plain subscribable store rather than React state so the paging rules can be\n// tested without a DOM; PathExplorer reads it through useSyncExternalStore and\n// builds a fresh instance whenever the scope or browsed subject changes, which\n// is also what discards a previous subject's in-flight responses.\n//\n// Every method that fetches records a failure on the directory's listing (the\n// tree renders it inline) AND rejects, so the caller can report it.\nexport class LazyPathTree {\n private dirs = new Map<string, DirListing>();\n private snapshot: DirMap = new Map();\n private readonly listeners = new Set<() => void>();\n private readonly inflight = new Map<string, Promise<void>>();\n // epoch bumps whenever a directory is re-listed from its first page or\n // dropped, so a page that was in flight across that point is discarded\n // instead of being appended to a listing it no longer continues.\n private readonly epoch = new Map<string, number>();\n\n constructor(\n private readonly data: ExplorerDataLayer,\n private readonly scope: PathScope,\n private readonly browse?: BrowseScope,\n private readonly pageLimit: number = LS_PAGE_LIMIT,\n private readonly listing: ListingOptions = {},\n ) {}\n\n getSnapshot = (): DirMap => this.snapshot;\n\n subscribe = (fn: () => void): (() => void) => {\n this.listeners.add(fn);\n return () => {\n this.listeners.delete(fn);\n };\n };\n\n private publish() {\n this.snapshot = new Map(this.dirs);\n this.listeners.forEach((fn) => fn());\n }\n\n private set(dir: string, listing: DirListing) {\n this.dirs.set(dir, listing);\n this.publish();\n }\n\n private track(dir: string, p: Promise<void>): Promise<void> {\n const tracked = p.finally(() => {\n if (this.inflight.get(dir) === tracked) this.inflight.delete(dir);\n });\n this.inflight.set(dir, tracked);\n return tracked;\n }\n\n // loadDir lists a directory's first page unless it is already listed. A\n // request already in flight for it is joined rather than repeated.\n loadDir(dir: string): Promise<void> {\n const running = this.inflight.get(dir);\n if (running) return running;\n if (this.dirs.get(dir)?.loaded) return Promise.resolve();\n return this.fetchFirst(dir, this.pageLimit);\n }\n\n // reload re-lists a directory from its first page, asking for as many entries\n // as it already showed so a refresh does not fold away pages the operator\n // loaded (up to the runtime's ceiling; past it the \"load more\" row returns).\n // A directory that was shown in full gets a page of headroom on top, so the\n // entry just created in it does not split it back into \"load more\".\n reload(dir: string): Promise<void> {\n const prev = this.dirs.get(dir);\n const shown = prev?.entries.length ?? 0;\n const want = prev?.loaded && !prev.nextCursor ? shown + this.pageLimit : shown;\n return this.fetchFirst(dir, Math.min(LS_MAX_LIMIT, Math.max(this.pageLimit, want)));\n }\n\n private fetchFirst(dir: string, limit: number): Promise<void> {\n const ep = (this.epoch.get(dir) ?? 0) + 1;\n this.epoch.set(dir, ep);\n const prev = this.dirs.get(dir);\n // Keep showing what was there while the new listing is in flight.\n this.set(dir, {\n ...prev,\n entries: prev?.entries ?? [],\n nextCursor: prev?.nextCursor,\n loaded: prev?.loaded ?? false,\n loading: true,\n error: undefined,\n });\n const p = this.data\n .pathLs(lsTarget(dir), this.scope, false, this.browse, { ...this.listing, limit })\n .then(\n (resp) => {\n if (this.epoch.get(dir) === ep) this.set(dir, listingOf(resp, []));\n },\n (e: unknown) => {\n if (this.epoch.get(dir) === ep) {\n this.set(dir, {\n ...prev,\n entries: prev?.entries ?? [],\n nextCursor: prev?.nextCursor,\n loaded: prev?.loaded ?? false,\n loading: false,\n error: errMessage(e),\n });\n }\n throw e;\n },\n );\n return this.track(dir, p);\n }\n\n // loadMore appends a directory's next page. A no-op when it has none.\n loadMore(dir: string): Promise<void> {\n const running = this.inflight.get(dir);\n if (running) return running;\n const cur = this.dirs.get(dir);\n if (!cur?.nextCursor) return Promise.resolve();\n const ep = this.epoch.get(dir) ?? 0;\n this.set(dir, { ...cur, loading: true, error: undefined });\n const p = this.data\n .pathLs(lsTarget(dir), this.scope, false, this.browse, {\n ...this.listing,\n limit: this.pageLimit,\n cursor: cur.nextCursor,\n })\n .then(\n (resp) => {\n if (this.epoch.get(dir) === ep) this.set(dir, listingOf(resp, cur.entries));\n },\n (e: unknown) => {\n if (this.epoch.get(dir) === ep) {\n this.set(dir, { ...cur, loading: false, error: errMessage(e) });\n }\n throw e;\n },\n );\n return this.track(dir, p);\n }\n\n // reveal lists every ancestor of `path`, paging each one until the next path\n // segment appears, so a deep link to an entry on a later page still resolves.\n // Resolves false when the path is not there. Because a page is ordered by\n // name, paging stops as soon as a page ends past the wanted name.\n async reveal(path: string): Promise<boolean> {\n const segs = path.split(\"/\").filter(Boolean);\n let dir = \"\";\n for (const name of segs) {\n await this.loadDir(dir);\n for (;;) {\n const l = this.dirs.get(dir);\n if (!l) return false;\n if (l.entries.some((e) => e.name === name)) break;\n const last = l.entries[l.entries.length - 1];\n if (!l.nextCursor || (last && last.name > name)) return false;\n const cursor = l.nextCursor;\n await this.loadMore(dir);\n // A page that moved nothing forward (a reload raced it, or a runtime\n // that handed back the same cursor) must not spin this loop.\n if (this.dirs.get(dir)?.nextCursor === cursor) return false;\n }\n dir = `${dir}/${name}`;\n }\n return true;\n }\n\n // invalidate re-lists what a change at `path` can alter: every ancestor that\n // is already listed — not just the parent, because an implicit directory\n // appears with its first descendant and vanishes with its last. dropSubtree\n // also forgets the listings at/under `path` (a moved or removed directory's\n // old children must not linger under its old name).\n async invalidate(path: string, opts?: { dropSubtree?: boolean }): Promise<void> {\n if (opts?.dropSubtree) {\n for (const k of [...this.dirs.keys()]) {\n if (k === path || k.startsWith(`${path}/`)) {\n this.dirs.delete(k);\n this.epoch.set(k, (this.epoch.get(k) ?? 0) + 1);\n this.inflight.delete(k);\n }\n }\n this.publish();\n }\n const dirs = ancestorsOf(path).filter((d) => this.dirs.has(d));\n await Promise.all(dirs.map((d) => this.reload(d)));\n }\n\n // refresh re-lists the root and every directory in `keep` that is listed, and\n // forgets the rest (a collapsed directory re-lists when it is next opened).\n async refresh(keep: Iterable<string>): Promise<void> {\n const keepSet = new Set(keep);\n keepSet.add(\"\");\n for (const k of [...this.dirs.keys()]) {\n if (!keepSet.has(k)) {\n this.dirs.delete(k);\n this.epoch.set(k, (this.epoch.get(k) ?? 0) + 1);\n this.inflight.delete(k);\n }\n }\n this.publish();\n const dirs = [...keepSet].filter((d) => d === \"\" || this.dirs.has(d));\n await Promise.all(dirs.map((d) => this.reload(d)));\n }\n}\n\n// listSubtree returns every dirent under `dir`, following the runtime's cursor\n// to the end. For the operations that genuinely need the whole subtree (a branch\n// delete has to find every Document under it) — never for drawing the tree.\nexport async function listSubtree(\n data: ExplorerDataLayer,\n dir: string,\n scope: PathScope,\n browse?: BrowseScope,\n): Promise<PathEntry[]> {\n const out: PathEntry[] = [];\n let cursor: string | undefined;\n for (;;) {\n const resp = await data.pathLs(lsTarget(dir), scope, true, browse, {\n limit: LS_MAX_LIMIT,\n cursor,\n });\n out.push(...(resp.entries ?? []));\n const next = resp.next_cursor || undefined;\n if (!next || next === cursor) return out;\n cursor = next;\n }\n}\n\n// documentIdsOf returns the document_id of every `document` entry.\nexport function documentIdsOf(entries: Iterable<PathEntry>): string[] {\n const ids: string[] = [];\n for (const e of entries) {\n if (e.kind !== \"document\") continue;\n const id = (e.resource_ref as { document_id?: string } | undefined)?.document_id;\n if (id) ids.push(id);\n }\n return ids;\n}\n","import { LoomcycleClient } from \"@loomcycle/client\";\n\n// Connection the host hands to <PathExplorer> / <DocumentViewer>. `fetch` is an\n// optional override so an embedding app can route requests however it needs\n// (proxying, header injection, instrumentation). External consumers just pass\n// baseUrl + token and hit the runtime directly.\nexport interface Connection {\n /** loomcycle base URL. \"\" means same-origin. */\n baseUrl: string;\n /** Bearer token. Omit when the runtime runs in open mode (or when the host\n * authenticates via a same-origin cookie through a custom `fetch`). */\n token?: string;\n /** Optional fetch override (proxying, header injection, instrumentation). */\n fetch?: typeof fetch;\n}\n\n/** Build a loomcycle client from a Connection. The fetch is always wrapped: the\n * SDK calls its stored fetch as a method (`ctx.fetchImpl(url)`), and the\n * browser's native fetch rejects a non-global receiver with \"Illegal\n * invocation\" — so we hand it a plain function that calls global fetch. */\nexport function createLoomcycleClient(c: Connection): LoomcycleClient {\n const impl = c.fetch;\n return new LoomcycleClient({\n baseUrl: c.baseUrl,\n authToken: c.token || undefined,\n fetch: (input, init) => (impl ? impl(input, init) : fetch(input, init)),\n });\n}\n\n/** AssetFetch does a raw authenticated GET against a relative loomcycle path and\n * returns the Response — for BINARY endpoints (RFC BO image assets) the JSON\n * client can't model. It mirrors the Connection's transport: the custom `fetch`\n * (e.g. the Web UI's same-origin cookie fetch) carries cookie auth, and a bearer\n * token is added as an Authorization header when set. */\nexport type AssetFetch = (path: string) => Promise<Response>;\n\n/** Build the AssetFetch from a Connection — the SAME auth transport the JSON\n * client uses, so an image asset loads under both cookie (web) and bearer\n * (standalone package) auth. */\nexport function assetFetchFromConnection(c: Connection): AssetFetch {\n const impl = c.fetch;\n const doFetch: typeof fetch = (input, init) => (impl ? impl(input, init) : fetch(input, init));\n return (path) => {\n const headers: Record<string, string> = {};\n if (c.token) headers.Authorization = `Bearer ${c.token}`;\n return doFetch(c.baseUrl + path, { headers });\n };\n}\n\n/** JsonPost POSTs a JSON body to a relative loomcycle path and returns the parsed\n * answer; a refusal rejects with an Error carrying the HTTP `status` and the\n * server's `code` (e.g. `queue_changed`), its message the server's `error`. It\n * reaches routes the pinned @loomcycle/client may not have a method for yet\n * (RFC FS: POST /v1/_statements/rule and /revert), over the same transport. */\nexport type JsonPost = (path: string, body: unknown) => Promise<unknown>;\n\n/** RequestError is a JsonPost refusal. */\nexport class RequestError extends Error {\n readonly status: number;\n readonly code?: string;\n constructor(message: string, status: number, code?: string) {\n super(message);\n this.name = \"RequestError\";\n this.status = status;\n this.code = code;\n }\n}\n\n/** Build the JsonPost from a Connection — the same auth transport as the JSON\n * client and the asset fetch. */\nexport function jsonPostFromConnection(c: Connection): JsonPost {\n const impl = c.fetch;\n const doFetch: typeof fetch = (input, init) => (impl ? impl(input, init) : fetch(input, init));\n return async (path, body) => {\n const headers: Record<string, string> = { \"Content-Type\": \"application/json\", Accept: \"application/json\" };\n if (c.token) headers.Authorization = `Bearer ${c.token}`;\n const resp = await doFetch(c.baseUrl + path, { method: \"POST\", headers, body: JSON.stringify(body) });\n const text = await resp.text();\n let parsed: unknown = undefined;\n try {\n parsed = text ? JSON.parse(text) : undefined;\n } catch {\n // not JSON: the status line is the message below\n }\n if (!resp.ok) {\n const o = parsed && typeof parsed === \"object\" ? (parsed as { error?: unknown; code?: unknown }) : {};\n const msg = typeof o.error === \"string\" && o.error ? o.error : `${resp.status} ${resp.statusText}`.trim();\n throw new RequestError(msg, resp.status, typeof o.code === \"string\" ? o.code : undefined);\n }\n return parsed;\n };\n}\n","import {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useId,\n useLayoutEffect,\n useRef,\n useState,\n type FocusEvent,\n type KeyboardEvent,\n type ReactNode,\n} from \"react\";\nimport { createPortal } from \"react-dom\";\nimport type { BrowseScope, ChunkRow, DocScope } from \"../types\";\nimport type { ExplorerDataLayer } from \"../lib/dataLayer\";\nimport { loadAnnotations } from \"../lib/annotation\";\n\n// The annotation card (RFC GZ): one card for whatever names a document or a\n// chunk — a Path tree row, a chunk outline row, a reference link, a breadcrumb\n// segment, the header's annotation icon. It shows the title, the type and\n// status, the brief and, when there is one, the abstract; with no annotation,\n// the title and type only.\n//\n// It opens after a hover of CARD_DELAY_MS or on keyboard focus, and closes on\n// leave, blur or Escape. A plain click never opens it: the click stays\n// \"select\" or \"follow\". What a card cannot know at once (a brief read from the\n// runtime) is loaded on first open and kept for the session.\n\nexport const CARD_DELAY_MS = 600;\n\nexport interface CardInfo {\n title: string;\n type?: string;\n status?: string;\n // path — where the thing sits in the Path tree, when that is useful.\n path?: string;\n brief?: string;\n abstract?: string;\n // stale — the annotation was written before the text last changed.\n stale?: boolean;\n}\n\n// CardSpec is what a trigger knows now, plus how to learn the rest. `load`\n// runs on the first open; its answer fills in (never blanks) what is known,\n// and is cached under `key` for the session. A load that fails leaves the card\n// on what is known — the title at least.\nexport interface CardSpec extends CardInfo {\n key?: string;\n load?: () => Promise<Partial<CardInfo> | undefined>;\n}\n\ntype CardCache = Map<string, Promise<Partial<CardInfo> | undefined>>;\nconst CardCacheContext = createContext<CardCache | null>(null);\n\n// CardCacheProvider holds the session's loaded briefs for every card under it\n// (the explorer root provides one).\nexport function CardCacheProvider({ children }: { children: ReactNode }) {\n const cache = useRef<CardCache>(new Map());\n return <CardCacheContext.Provider value={cache.current}>{children}</CardCacheContext.Provider>;\n}\n\n// CardScope is where the cards inside a document view read from: the\n// document's scope and browse override (a reference link knows only ids).\nexport interface CardScope {\n data: ExplorerDataLayer;\n scope: DocScope;\n browse?: BrowseScope;\n}\nexport const CardScopeContext = createContext<CardScope | null>(null);\n\nfunction mergeInfo(base: CardInfo, extra: Partial<CardInfo> | undefined): CardInfo {\n if (!extra) return base;\n const out: CardInfo = { ...base };\n for (const k of Object.keys(extra) as (keyof CardInfo)[]) {\n const v = extra[k];\n if (v !== undefined && v !== \"\") (out as unknown as Record<string, unknown>)[k] = v;\n }\n return out;\n}\n\nexport interface CardTrigger {\n // anchor: the element the card is placed against (never covered by it).\n anchorRef: (el: HTMLElement | null) => void;\n // hover: on the element the pointer rests on.\n hover: {\n onMouseEnter: () => void;\n onMouseLeave: () => void;\n onMouseDown: () => void;\n };\n // focus: on the element that takes the keyboard focus.\n focus: {\n onFocus: (e: FocusEvent<HTMLElement>) => void;\n onBlur: (e: FocusEvent<HTMLElement>) => void;\n onKeyDown: (e: KeyboardEvent<HTMLElement>) => void;\n onMouseDown: () => void;\n \"aria-describedby\"?: string;\n };\n card: ReactNode;\n}\n\n// useAnnotationCard wires one trigger. With no spec it does nothing.\nexport function useAnnotationCard(spec: CardSpec | undefined): CardTrigger {\n const shared = useContext(CardCacheContext);\n const local = useRef<CardCache>(new Map());\n const cache = shared ?? local.current;\n const specRef = useRef(spec);\n specRef.current = spec;\n\n const [open, setOpen] = useState(false);\n const [loaded, setLoaded] = useState<{ key: string | undefined; info?: Partial<CardInfo>; done: boolean }>({\n key: undefined,\n done: false,\n });\n const anchor = useRef<HTMLElement | null>(null);\n const cardEl = useRef<HTMLDivElement | null>(null);\n const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);\n const pressed = useRef(false);\n const seq = useRef(0);\n const id = useId();\n\n const clear = () => {\n if (timer.current !== undefined) clearTimeout(timer.current);\n timer.current = undefined;\n };\n const close = useCallback(() => {\n clear();\n seq.current++;\n setOpen(false);\n }, []);\n\n const show = useCallback(() => {\n clear();\n const s = specRef.current;\n if (!s) return;\n setOpen(true);\n if (!s.load) {\n setLoaded({ key: s.key, done: true });\n return;\n }\n const n = ++seq.current;\n let p = s.key ? cache.get(s.key) : undefined;\n if (!p) {\n p = s.load().catch(() => undefined);\n if (s.key) cache.set(s.key, p);\n }\n setLoaded({ key: s.key, done: false });\n void p.then((info) => {\n if (seq.current === n) setLoaded({ key: s.key, info, done: true });\n });\n }, [cache]);\n\n useEffect(() => clear, []);\n\n // While open, a scroll anywhere moves the anchor from under the card.\n useEffect(() => {\n if (!open) return;\n const onScroll = () => close();\n window.addEventListener(\"scroll\", onScroll, true);\n return () => window.removeEventListener(\"scroll\", onScroll, true);\n }, [open, close]);\n\n // Place the card under its anchor, or over it when there is no room below,\n // inside the viewport either way, so it never covers what it describes.\n useLayoutEffect(() => {\n const el = cardEl.current;\n const a = anchor.current;\n if (!open || !el || !a) return;\n const r = a.getBoundingClientRect();\n const vw = window.innerWidth || document.documentElement.clientWidth;\n const vh = window.innerHeight || document.documentElement.clientHeight;\n const w = el.offsetWidth;\n const h = el.offsetHeight;\n const gap = 4;\n const below = r.bottom + gap;\n const top = below + h <= vh - 8 || r.top - gap - h < 8 ? below : r.top - gap - h;\n const left = Math.max(8, Math.min(r.left, vw - w - 8));\n el.style.top = `${Math.round(top)}px`;\n el.style.left = `${Math.round(left)}px`;\n });\n\n const anchorRef = useCallback((el: HTMLElement | null) => {\n anchor.current = el;\n }, []);\n const press = useCallback(() => {\n // A press is a click on its way: it selects or follows, and the focus it\n // brings is not a reason to show the card.\n pressed.current = true;\n setTimeout(() => {\n pressed.current = false;\n }, 0);\n close();\n }, [close]);\n\n const info = spec && open ? mergeInfo(spec, loaded.key === spec.key ? loaded.info : undefined) : undefined;\n const loading = !!spec?.load && open && !(loaded.key === spec.key && loaded.done);\n const host =\n typeof document === \"undefined\" ? null : (anchor.current?.closest(\".loomcycle-explorer\") ?? document.body);\n const card =\n info && host\n ? createPortal(\n <div className=\"ex-card\" id={id} role=\"tooltip\" ref={cardEl}>\n <CardBody info={info} loading={loading} />\n </div>,\n host,\n )\n : null;\n\n return {\n anchorRef,\n hover: {\n onMouseEnter: () => {\n if (!specRef.current || pressed.current) return;\n clear();\n timer.current = setTimeout(show, CARD_DELAY_MS);\n },\n onMouseLeave: close,\n onMouseDown: press,\n },\n focus: {\n onFocus: (e) => {\n if (e.target !== e.currentTarget || pressed.current) return;\n show();\n },\n onBlur: (e) => {\n if (e.target === e.currentTarget) close();\n },\n onKeyDown: (e) => {\n if (e.key === \"Escape\" && open) close();\n },\n onMouseDown: press,\n \"aria-describedby\": info ? id : undefined,\n },\n card,\n };\n}\n\n// CardBody is the card's content, also shown in place (a folder's detail pane\n// is its card).\nexport function CardBody({ info, loading }: { info: CardInfo; loading?: boolean }) {\n const meta = [info.type, info.status].filter(Boolean).join(\" · \");\n return (\n <>\n <div className=\"ex-card-title\">{info.title}</div>\n {(meta || info.stale) && (\n <div className=\"ex-card-meta\">\n {meta}\n {info.stale && <span className=\"ex-card-stale\">{meta ? \" · \" : \"\"}annotation out of date</span>}\n </div>\n )}\n {info.path && <div className=\"ex-card-path\">{info.path}</div>}\n {info.brief && <p className=\"ex-card-brief\">{info.brief}</p>}\n {info.abstract && <p className=\"ex-card-abstract\">{info.abstract}</p>}\n {loading && !info.brief && <p className=\"ex-card-loading\">Loading…</p>}\n </>\n );\n}\n\n// rowSummary reads a chunk row's annotation when the chunk list carries one\n// (RFC HA's query_chunks `with_summary` puts `summary` on the rows; a runtime\n// before it leaves it out and the card reads the chunk's annotation on first\n// open).\nexport function rowSummary(row: ChunkRow): Partial<CardInfo> | undefined {\n const s = row.summary as { brief?: unknown; abstract?: unknown; stale?: unknown } | undefined;\n if (!s || typeof s.brief !== \"string\") return undefined;\n return {\n brief: s.brief,\n abstract: typeof s.abstract === \"string\" ? s.abstract : undefined,\n stale: s.stale === true || undefined,\n };\n}\n\n// chunkCard is the card of a chunk: its own fields now, its annotation from\n// the chunk list when the list carries it, else read on first open.\n// `listed` says the list carries the briefs (some row has one): a row without\n// one then has no annotation of its own, and nothing is read for it.\nexport function chunkCard(row: ChunkRow, src: CardScope | null, listed?: boolean): CardSpec {\n const base: CardSpec = { title: row.title || \"(untitled)\", type: row.type, status: row.status };\n const inline = rowSummary(row);\n if (inline) return { ...base, ...inline };\n if (!src || listed) return base;\n return {\n ...base,\n key: `${src.scope}:${src.browse?.scopeId ?? \"\"}:${src.browse?.tenant ?? \"\"}:chunk:${row.id}`,\n load: async () => {\n const recs = await loadAnnotations(src.data, row.id, src.scope, src.browse);\n const a = recs[0];\n return a ? { brief: a.brief, abstract: a.abstract, stale: a.stale || undefined } : undefined;\n },\n };\n}\n\n// documentCard is the card of a document known by id (a reference into\n// another document, the breadcrumb's last segment): its summary on first\n// open. The brief there is the document's, and exists only for an annotated\n// tenant-scope document; without it the card keeps the title it was given.\nexport function documentCard(\n documentId: string,\n title: string,\n src: Pick<CardScope, \"data\" | \"scope\" | \"browse\"> | null,\n known?: Partial<CardInfo>,\n): CardSpec {\n const base: CardSpec = { title, ...known };\n if (!src || known?.brief !== undefined) return base;\n return {\n ...base,\n key: `${src.scope}:${src.browse?.scopeId ?? \"\"}:${src.browse?.tenant ?? \"\"}:doc:${documentId}`,\n load: async () => {\n const r = await src.data.documentsSummary({ documentIds: [documentId] }, src.scope, src.browse);\n const d = r.documents?.find((x) => x.document_id === documentId);\n return d ? { title: d.title, type: d.type, status: d.status, brief: d.brief } : undefined;\n },\n };\n}\n\n// useButtonCard wires a trigger that is one focusable element (a button), its\n// own anchor; spread `props` on it and render `card` beside it.\nexport function useButtonCard(spec: CardSpec | undefined) {\n const t = useAnnotationCard(spec);\n return {\n props: {\n ref: t.anchorRef,\n onMouseEnter: t.hover.onMouseEnter,\n onMouseLeave: t.hover.onMouseLeave,\n onMouseDown: t.hover.onMouseDown,\n onFocus: t.focus.onFocus,\n onBlur: t.focus.onBlur,\n onKeyDown: t.focus.onKeyDown,\n \"aria-describedby\": t.focus[\"aria-describedby\"],\n },\n card: t.card,\n };\n}\n","import { useMemo, type ReactNode } from \"react\";\nimport type { LoomcycleClient } from \"@loomcycle/client\";\nimport {\n createLoomcycleClient,\n assetFetchFromConnection,\n jsonPostFromConnection,\n type Connection,\n} from \"../lib/createClient\";\nimport {\n ExplorerDataProvider,\n dataLayerFromClient,\n type ExplorerDataLayer,\n} from \"../lib/dataLayer\";\nimport { CardCacheProvider } from \"./AnnotationCard\";\n\n// ExplorerDataSource is the data-source contract shared by both public roots\n// (<PathExplorer> / <DocumentViewer>). Provide exactly one; precedence is\n// dataLayer > client > connection. The default path is `connection` → an\n// internal LoomcycleClient.\nexport interface ExplorerDataSource {\n /** A raw connection (baseUrl + optional token + optional fetch override). */\n connection?: Connection;\n /** A prebuilt @loomcycle/client instance. */\n client?: LoomcycleClient;\n /** A fully custom data layer (e.g. a cookie-authed same-origin fetcher). */\n dataLayer?: ExplorerDataLayer;\n}\n\n// useResolvedDataLayer picks the data layer from the source props once per\n// connection identity. Depending on the connection's PRIMITIVE fields (not the\n// object) keeps an inline `connection={{...}}` from rebuilding the client every\n// render.\nexport function useResolvedDataLayer(src: ExplorerDataSource): ExplorerDataLayer | null {\n const { dataLayer, client, connection } = src;\n return useMemo<ExplorerDataLayer | null>(() => {\n if (dataLayer) return dataLayer;\n if (client) return dataLayerFromClient(client);\n if (connection)\n return dataLayerFromClient(\n createLoomcycleClient(connection),\n assetFetchFromConnection(connection), // RFC BO — binary image-asset GET\n jsonPostFromConnection(connection), // RFC FS — the review routes\n );\n return null;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [dataLayer, client, connection?.baseUrl, connection?.token, connection?.fetch]);\n}\n\n// ExplorerRoot renders the themeable `.loomcycle-explorer` wrapper + provides the\n// data layer to nested components. When no data source resolved, it shows an\n// inline error banner instead (so a misconfiguration is visible, not silent).\n// The component NEVER redirects on 401 — the host owns the auth flow.\nexport function ExplorerRoot({\n theme,\n dataLayer,\n children,\n}: {\n theme?: \"light\" | \"dark\";\n dataLayer: ExplorerDataLayer | null;\n children: ReactNode;\n}) {\n const themeAttr = theme ? { \"data-theme\": theme } : {};\n if (!dataLayer) {\n return (\n <div className=\"loomcycle-explorer\" {...themeAttr}>\n <div className=\"error-banner\">\n @loomcycle/explorer: provide a <code>connection</code>, <code>client</code>, or{\" \"}\n <code>dataLayer</code> prop.\n </div>\n </div>\n );\n }\n return (\n <div className=\"loomcycle-explorer\" {...themeAttr}>\n <ExplorerDataProvider value={dataLayer}>\n {/* The annotation cards' briefs, read once per session. */}\n <CardCacheProvider>{children}</CardCacheProvider>\n </ExplorerDataProvider>\n </div>\n );\n}\n","import type { ChunkRow, PathEntry } from \"../types\";\nimport type { DirMap } from \"./lazyPathTree\";\n\n// The document trail: where the reader has been while following references from\n// one document into another, so there is a way back.\n//\n// A reference between chunks can cross documents, and following one replaces the\n// document in the viewer. Without a record of where the reader came from, the\n// only way back is to find the original document again in the tree — and the\n// chunk that was selected there is lost either way. The trail is that record. It\n// is kept as plain data + pure functions (no React) so both hosts — the tree\n// console and the single-document viewer — share one set of rules, and so those\n// rules can be tested without a DOM.\n\n// DocLocation is one stop on the trail: a document and the chunk selected in it.\n// `path` is the document's Path-tree name when it has one and it is known — a\n// document can exist without a dirent, and is then addressed by id alone.\nexport interface DocLocation {\n documentId: string;\n chunkId?: string;\n title?: string;\n path?: string;\n}\n\n// Trail is the visited documents, oldest first; the last entry is the one on\n// screen. Empty = the document was opened directly (from the tree or by a host),\n// and nothing has been followed yet.\nexport type Trail = readonly DocLocation[];\n\n// followReference records a jump from `origin` into `target`. `origin` is the\n// document being left, WITH the chunk selected at that moment — that is what\n// Back has to restore, and it is only known at the moment of leaving. An empty\n// trail is seeded with it; a trail already under way has its last entry (the\n// same document) brought up to date instead of duplicated.\nexport function followReference(trail: Trail, origin: DocLocation, target: DocLocation): Trail {\n const last = trail[trail.length - 1];\n const head =\n last && last.documentId === origin.documentId\n ? [...trail.slice(0, -1), { ...last, ...defined(origin) }]\n : [...trail, origin];\n return [...head, target];\n}\n\n// jumpTo cuts the trail back to the entry at `index`, which becomes the document\n// on screen (with its remembered chunk). An out-of-range index is a no-op.\nexport function jumpTo(trail: Trail, index: number): Trail {\n if (index < 0 || index >= trail.length - 1) return trail;\n return trail.slice(0, index + 1);\n}\n\n// back is jumpTo the previous entry.\nexport function back(trail: Trail): Trail {\n return jumpTo(trail, trail.length - 2);\n}\n\n// amendCurrent fills in what is learned about the document on screen AFTER the\n// jump — its real title once it loads, its path once the lookup answers. It\n// only applies while that document is still the one on screen, so a late answer\n// for a document the reader has already left lands nowhere.\nexport function amendCurrent(\n trail: Trail,\n documentId: string,\n patch: Pick<DocLocation, \"title\" | \"path\">,\n): Trail {\n const last = trail[trail.length - 1];\n if (!last || last.documentId !== documentId) return trail;\n const next = { ...last, ...defined(patch) };\n if (next.title === last.title && next.path === last.path) return trail;\n return [...trail.slice(0, -1), next];\n}\n\n// defined drops undefined values, so merging a partial location never erases a\n// field the trail already knows (an origin snapshot carries no path of its own).\nfunction defined<T extends object>(o: T): Partial<T> {\n return Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined)) as Partial<T>;\n}\n\n// labelOf is what a crumb shows: the document's title, else its path's last\n// segment, else a short id — never blank.\nexport function labelOf(loc: DocLocation): string {\n if (loc.title) return loc.title;\n if (loc.path) return loc.path.slice(loc.path.lastIndexOf(\"/\") + 1) || loc.path;\n return loc.documentId.slice(0, 8);\n}\n\n// TrailItem is one rendered breadcrumb slot: an entry (by its index in the\n// trail), or a gap standing in for the entries folded out of a long trail.\nexport type TrailItem = { kind: \"crumb\"; index: number } | { kind: \"gap\"; hidden: number[] };\n\n// TRAIL_VISIBLE is how many crumbs a trail shows before it folds its middle.\nexport const TRAIL_VISIBLE = 4;\n\n// collapseTrail folds a long trail to its first entry, a gap, and its last\n// entries. The ends are what matter: where the reader started, and the steps\n// that led directly here.\nexport function collapseTrail(length: number, max: number = TRAIL_VISIBLE): TrailItem[] {\n const all: TrailItem[] = Array.from({ length }, (_, index) => ({ kind: \"crumb\", index }));\n if (length <= max || max < 3) return all;\n const tail = max - 1; // crumbs kept at the end, after the first one\n const hidden = Array.from({ length: length - 1 - tail }, (_, i) => i + 1);\n return [all[0], { kind: \"gap\", hidden }, ...all.slice(length - tail)];\n}\n\n// findDocumentPath looks a document up among the directories the tree has\n// already listed. Dirents point at documents (never the reverse), so this is the\n// free half of the id → path lookup; a document in a directory nobody opened is\n// not found here, and the data layer's documentPath is asked instead.\nexport function findDocumentPath(dirs: DirMap, documentId: string): string | undefined {\n for (const listing of dirs.values()) {\n const hit = listing.entries.find((e) => documentIdOf(e) === documentId);\n if (hit) return hit.full_path;\n }\n return undefined;\n}\n\n// documentIdOf reads the document id a `document` dirent points at.\nexport function documentIdOf(entry: PathEntry): string | undefined {\n if (entry.kind !== \"document\") return undefined;\n return (entry.resource_ref as { document_id?: string } | undefined)?.document_id || undefined;\n}\n\n// landingChunk picks the chunk a freshly loaded document opens on: the one asked\n// for when it is among the loaded rows, else the root. A wanted chunk that is\n// not there (deleted since the edge was written, or past the viewer's row cap)\n// falls back to the root rather than selecting something the tree cannot show.\nexport function landingChunk(rows: ChunkRow[], wanted?: string): string | undefined {\n if (wanted && rows.some((c) => c.id === wanted)) return wanted;\n return rows.find((c) => !c.parent_id)?.id;\n}\n","import { useState } from \"react\";\nimport { collapseTrail, labelOf, type Trail } from \"../lib/docTrail\";\n\n// DocTrail is the breadcrumb over a document reached by following references:\n// every document on the way here, each one a button back to it — and to the\n// chunk that was selected there — plus a Back button for the common single step.\n// It renders nothing until a reference has actually been followed (one entry is\n// just \"the document on screen\").\n//\n// A long trail folds its middle into a \"…\" that expands on demand; a long title\n// is cut with an ellipsis in CSS and carried in full by the tooltip.\nexport interface DocTrailProps {\n trail: Trail;\n // onJump receives the index of the trail entry to return to.\n onJump: (index: number) => void;\n}\n\nexport default function DocTrail({ trail, onJump }: DocTrailProps) {\n const [showAll, setShowAll] = useState(false);\n if (trail.length < 2) return null;\n\n const current = trail.length - 1;\n const previous = trail[current - 1];\n const items = collapseTrail(trail.length, showAll ? trail.length : undefined);\n\n return (\n <nav className=\"doc-trail\" aria-label=\"Documents you came through\">\n <button\n type=\"button\"\n className=\"doc-trail-back\"\n onClick={() => onJump(current - 1)}\n title={`Back to ${labelOf(previous)}`}\n >\n ← Back\n </button>\n <ol className=\"doc-trail-list\">\n {items.map((item) =>\n item.kind === \"gap\" ? (\n <li className=\"doc-trail-item\" key=\"gap\">\n <button\n type=\"button\"\n className=\"doc-trail-gap\"\n onClick={() => setShowAll(true)}\n title={`Show ${item.hidden.length} more: ${item.hidden\n .map((i) => labelOf(trail[i]))\n .join(\" › \")}`}\n aria-label={`Show ${item.hidden.length} hidden documents`}\n >\n …\n </button>\n </li>\n ) : item.index === current ? (\n <li className=\"doc-trail-item\" key={item.index}>\n <span className=\"doc-trail-current\" aria-current=\"page\" title={labelOf(trail[current])}>\n {labelOf(trail[current])}\n </span>\n </li>\n ) : (\n <li className=\"doc-trail-item\" key={item.index}>\n <button\n type=\"button\"\n className=\"doc-trail-crumb\"\n onClick={() => onJump(item.index)}\n title={labelOf(trail[item.index])}\n >\n {labelOf(trail[item.index])}\n </button>\n </li>\n ),\n )}\n </ol>\n </nav>\n );\n}\n","import { useMemo, useState, type FormEvent } from \"react\";\nimport type { BrowseScope, DocScope } from \"../types\";\nimport type { ExplorerDataLayer } from \"../lib/dataLayer\";\nimport {\n transferBlocked,\n transferInput,\n transferProblem,\n transferSummary,\n type TransferOp,\n type TransferRequest,\n type TransferResult,\n} from \"../lib/transfer\";\n\nexport interface TransferModalProps {\n data: ExplorerDataLayer;\n scope: DocScope;\n browse?: BrowseScope;\n // What is being copied or moved: one document by id, or a folder's documents.\n documentId?: string;\n underPath?: string;\n // The selected path, the prefix the new path replaces.\n fromPath: string;\n onClose: () => void;\n // Called after a real copy or move, with what was asked and the answer.\n onDone: (req: TransferRequest, res: TransferResult) => void;\n}\n\n// TransferModal copies or moves a document, or every document under a folder,\n// into another scope. It always runs the dry run first and shows what would\n// happen, what is refused and which relations leave the set; the real call is\n// offered only for the inputs that dry run checked, and a move passes the dry\n// run's count so a set that changed since is refused rather than moved.\nexport default function TransferModal({\n data,\n scope,\n browse,\n documentId,\n underPath,\n fromPath,\n onClose,\n onDone,\n}: TransferModalProps) {\n const [op, setOp] = useState<TransferOp>(\"copy\");\n const [toScope, setToScope] = useState<DocScope>(scope === \"tenant\" ? \"user\" : \"tenant\");\n const [to, setTo] = useState(fromPath);\n const [dropDangling, setDropDangling] = useState(false);\n const [checked, setChecked] = useState<{ key: string; res: TransferResult } | null>(null);\n const [done, setDone] = useState<TransferResult | null>(null);\n const [busy, setBusy] = useState(false);\n const [err, setErr] = useState<string | null>(null);\n\n const req = useMemo<TransferRequest>(\n () => ({ op, scope, toScope, documentId, underPath, from: fromPath, to, dropDangling, dryRun: true }),\n [op, scope, toScope, documentId, underPath, fromPath, to, dropDangling],\n );\n const key = JSON.stringify(transferInput(req));\n const problem = transferProblem(req);\n const current = checked && checked.key === key ? checked.res : null;\n const blocked = current ? transferBlocked(op, current, dropDangling) : false;\n const n = current ? (op === \"move\" ? (current.counts?.documents ?? 0) + (current.to_finish?.length ?? 0) : current.counts?.documents ?? 0) : 0;\n\n const submit = async (e: FormEvent) => {\n e.preventDefault();\n if (done) {\n onClose();\n return;\n }\n if (problem || !data.documentsTransfer) return;\n setBusy(true);\n setErr(null);\n try {\n if (!current) {\n setChecked({ key, res: await data.documentsTransfer(req, browse) });\n } else {\n const real: TransferRequest = { ...req, dryRun: false, expectCount: current.counts?.documents ?? 0 };\n const res = await data.documentsTransfer(real, browse);\n setDone(res);\n onDone(real, res);\n }\n } catch (ex) {\n setErr(ex instanceof Error ? ex.message : String(ex));\n } finally {\n setBusy(false);\n }\n };\n\n const label = done\n ? \"close\"\n : busy\n ? \"working…\"\n : !current\n ? \"check\"\n : `${op} ${n} document${n === 1 ? \"\" : \"s\"}`;\n const shown = done ?? current;\n const what = documentId ? \"document\" : \"documents under\";\n\n return (\n <div className=\"modal-overlay\" onClick={busy ? undefined : onClose}>\n <form className=\"modal\" onClick={(e) => e.stopPropagation()} onSubmit={submit}>\n <div className=\"modal-header sticky-top\">\n <h3>\n Copy or move the {what} {fromPath}\n </h3>\n <div className=\"modal-buttons modal-buttons-top\">\n {!done && (\n <button type=\"button\" onClick={onClose} disabled={busy}>\n cancel\n </button>\n )}\n <button\n type=\"submit\"\n className={current && op === \"move\" && !done ? \"danger\" : \"primary\"}\n disabled={busy || (!done && (!!problem || blocked))}\n >\n {label}\n </button>\n </div>\n </div>\n <p className=\"modal-context\">\n A copy gets new ids and leaves the source as it is. A move keeps every id and removes the\n documents from <code>{scope}</code>. Relations between the documents go with them.\n </p>\n <div className=\"paths-nav-switch\" role=\"group\" aria-label=\"Copy or move\">\n {([\"copy\", \"move\"] as const).map((o) => (\n <button\n key={o}\n type=\"button\"\n aria-pressed={op === o}\n className={op === o ? \"active\" : undefined}\n disabled={busy || !!done}\n onClick={() => setOp(o)}\n >\n {o}\n </button>\n ))}\n </div>\n <label className=\"path-field\">\n <span>To scope</span>\n <select value={toScope} disabled={busy || !!done} onChange={(e) => setToScope(e.target.value as DocScope)}>\n <option value=\"user\">user</option>\n <option value=\"agent\">agent</option>\n <option value=\"tenant\">tenant</option>\n </select>\n </label>\n <label className=\"path-field\">\n <span>New path</span>\n <input\n className=\"path-modal-input\"\n value={to}\n disabled={busy || !!done}\n onChange={(e) => setTo(e.target.value)}\n />\n </label>\n {op === \"move\" && (\n <label className=\"path-field\">\n <span>\n <input\n type=\"checkbox\"\n checked={dropDangling}\n disabled={busy || !!done}\n onChange={(e) => setDropDangling(e.target.checked)}\n />{\" \"}\n Drop relations to documents outside the set\n </span>\n </label>\n )}\n {problem && <div className=\"modal-err\">{problem}</div>}\n {shown && (\n <div className=\"modal-context\" aria-live=\"polite\">\n {transferSummary(op, shown).map((line, i) =>\n line.startsWith(\" \") ? (\n <div key={i}>\n <code>{line.trim()}</code>\n </div>\n ) : (\n <div key={i}>{line}</div>\n ),\n )}\n </div>\n )}\n {err && <div className=\"modal-err\">{err}</div>}\n </form>\n </div>\n );\n}\n","import { useCallback, useEffect, useRef, useState, type ReactNode } from \"react\";\n\n// Splitter wraps two children with a draggable vertical handle\n// between them. The left pane's width is owned in state and (when\n// `storageKey` is set) persisted to localStorage so the operator's\n// layout choice survives reloads.\n//\n// Implementation notes:\n// - CSS Grid with three columns: [left] [handle] [right]. Grid\n// keeps the right pane on a fluid `1fr` regardless of the\n// window width, while the left pane snaps to the dragged size.\n// - Drag uses window-level pointermove + pointerup so the user\n// can drag PAST the handle bounds without losing tracking\n// (common UX pitfall when the listener lives on the handle\n// element). The container ref provides the origin for the\n// fractional clientX calculation.\n// - min/max clamps so the user can't drag a pane into oblivion\n// or off-screen.\n//\n// Self-contained copy (the loomcycle Web UI + @loomcycle/library carry the same\n// component); the explorer package deliberately owns its own copy rather than\n// sharing, so it has no cross-package coupling.\n\nexport interface SplitterProps {\n children: [ReactNode, ReactNode];\n // Initial left-pane width in px. Used until the user drags or a\n // persisted value is restored from localStorage.\n defaultLeftWidth?: number;\n // Lower bound for the left pane in px. Pane content has its own\n // overflow:auto so it survives squeezing, but a too-narrow pane\n // is unusable.\n minLeftWidth?: number;\n // Upper bound for the left pane in px. Prevents the operator from\n // dragging the right pane to zero by accident.\n minRightWidth?: number;\n // localStorage key for persistence. Omit to make the split\n // ephemeral (resets on every page mount).\n storageKey?: string;\n // Extra class on the outer wrapper (the parent .paths-view rules\n // expect a specific class; this lets the caller keep those\n // selectors intact).\n className?: string;\n // Give the left pane the whole width. The right pane stays MOUNTED (hidden),\n // so whatever it holds keeps its state for when it comes back.\n hideRight?: boolean;\n // Give the right pane the whole width, the mirror of hideRight: the left\n // pane stays mounted (hidden), and `leftRail` — when given — takes a narrow\n // column in its place (a collapsed pane's rail).\n hideLeft?: boolean;\n leftRail?: ReactNode;\n // A double-click on the divider (RFC GZ: one of the ways a pane collapses).\n onHandleDoubleClick?: () => void;\n}\n\nconst HANDLE_WIDTH = 6;\n\nexport default function Splitter({\n children,\n defaultLeftWidth = 380,\n minLeftWidth = 180,\n minRightWidth = 240,\n storageKey,\n className,\n hideRight = false,\n hideLeft = false,\n leftRail,\n onHandleDoubleClick,\n}: SplitterProps) {\n const restore = (): number => {\n if (storageKey) {\n const stored = localStorage.getItem(storageKey);\n const n = stored ? parseInt(stored, 10) : NaN;\n if (Number.isFinite(n) && n >= minLeftWidth) return n;\n }\n return defaultLeftWidth;\n };\n const [leftWidth, setLeftWidth] = useState<number>(restore);\n // A host that switches layouts (the explorer's tree vs. star map) passes a\n // different key per layout; each remembers its own width.\n const [widthKey, setWidthKey] = useState(storageKey);\n if (widthKey !== storageKey) {\n setWidthKey(storageKey);\n setLeftWidth(restore());\n }\n const containerRef = useRef<HTMLDivElement | null>(null);\n const [dragging, setDragging] = useState(false);\n\n // Persist on every settled width. Debouncing isn't needed — drag\n // already produces a single final settle via pointerup.\n useEffect(() => {\n if (!storageKey || dragging || widthKey !== storageKey) return;\n localStorage.setItem(storageKey, String(Math.round(leftWidth)));\n }, [storageKey, widthKey, leftWidth, dragging]);\n\n const onPointerDown = useCallback((e: React.PointerEvent) => {\n e.preventDefault();\n setDragging(true);\n (e.target as HTMLElement).setPointerCapture(e.pointerId);\n }, []);\n\n const onPointerMove = useCallback(\n (e: React.PointerEvent) => {\n if (!dragging || !containerRef.current) return;\n const rect = containerRef.current.getBoundingClientRect();\n const raw = e.clientX - rect.left;\n const maxAllowed = rect.width - minRightWidth - HANDLE_WIDTH;\n const clamped = Math.max(minLeftWidth, Math.min(raw, maxAllowed));\n setLeftWidth(clamped);\n },\n [dragging, minLeftWidth, minRightWidth],\n );\n\n const onPointerUp = useCallback((e: React.PointerEvent) => {\n setDragging(false);\n try {\n (e.target as HTMLElement).releasePointerCapture(e.pointerId);\n } catch {\n // Pointer was already released (e.g. capture lost from a\n // browser-internal gesture). Safe to ignore.\n }\n }, []);\n\n return (\n <div\n ref={containerRef}\n className={`splitter ${className ?? \"\"} ${dragging ? \"dragging\" : \"\"}`}\n style={{\n // The drag clamps against the container, but a remembered width can come\n // from a wider host (the document viewer is both a full page and a pane\n // inside the Path console) or a since-narrowed window — so CSS clamps it\n // again against the container as it is now.\n // A hidden pane is not a grid item, so a hidden left pane leaves the\n // rail (when there is one) in the first column.\n gridTemplateColumns: hideRight\n ? \"1fr 0 0\"\n : hideLeft\n ? leftRail\n ? \"auto 1fr\"\n : \"1fr\"\n : `min(${leftWidth}px, calc(100% - ${minRightWidth + HANDLE_WIDTH}px)) ${HANDLE_WIDTH}px 1fr`,\n }}\n >\n <div className=\"splitter-pane splitter-left\" hidden={hideLeft && !hideRight}>\n {children[0]}\n </div>\n {hideLeft && !hideRight && leftRail}\n <div\n hidden={hideRight || hideLeft}\n className=\"splitter-handle\"\n role=\"separator\"\n aria-orientation=\"vertical\"\n aria-valuenow={Math.round(leftWidth)}\n onPointerDown={onPointerDown}\n onPointerMove={onPointerMove}\n onPointerUp={onPointerUp}\n onPointerCancel={onPointerUp}\n onDoubleClick={onHandleDoubleClick}\n />\n <div className=\"splitter-pane splitter-right\" hidden={hideRight}>\n {children[1]}\n </div>\n </div>\n );\n}\n","// RFC BO image-upload helpers for the explorer authoring UI.\n\n// IMAGE_MEDIA_TYPES is the accepted set — mirrors the backend whitelist\n// (validImageMediaTypes / ValidImageMediaType in document.go). SVG is excluded\n// (script-in-SVG XSS surface on the serving endpoint).\nexport const IMAGE_MEDIA_TYPES = [\"image/png\", \"image/jpeg\", \"image/gif\", \"image/webp\"];\n\n// isSupportedImage reports whether a File/Blob's type is an accepted image.\nexport function isSupportedImage(type: string): boolean {\n return IMAGE_MEDIA_TYPES.includes(type);\n}\n\n// readImageAsBase64 reads a File/Blob into standard base64 (NO data: prefix — the\n// set_asset op wants the raw base64, matching the backend's decode). Rejects an\n// unsupported media type up front so the server never sees it.\nexport function readImageAsBase64(file: File | Blob): Promise<{ mediaType: string; data: string }> {\n return new Promise((resolve, reject) => {\n if (!isSupportedImage(file.type)) {\n reject(new Error(`unsupported image type \"${file.type || \"unknown\"}\" (png, jpeg, gif, webp only)`));\n return;\n }\n const reader = new FileReader();\n reader.onerror = () => reject(reader.error ?? new Error(\"failed to read file\"));\n reader.onload = () => {\n // FileReader.readAsDataURL yields \"data:<type>;base64,<payload>\"; strip the\n // prefix to hand set_asset the raw base64.\n const result = String(reader.result ?? \"\");\n const comma = result.indexOf(\",\");\n if (comma < 0) {\n reject(new Error(\"could not decode image data\"));\n return;\n }\n resolve({ mediaType: file.type, data: result.slice(comma + 1) });\n };\n reader.readAsDataURL(file);\n });\n}\n\n// imageFileFromPaste extracts the first supported image from a paste event's\n// clipboard items, or null if none (so a normal text paste is ignored).\nexport function imageFileFromPaste(items: DataTransferItemList | null | undefined): File | null {\n if (!items) return null;\n for (let i = 0; i < items.length; i++) {\n const it = items[i];\n if (it.kind === \"file\" && isSupportedImage(it.type)) {\n const f = it.getAsFile();\n if (f) return f;\n }\n }\n return null;\n}\n","import type { BrowseScope, DocEdge, DocScope } from \"../types\";\nimport type { ExplorerDataLayer } from \"./dataLayer\";\n\n// EDGE_PAGE_CAP bounds how many get_edges pages one document load follows. The\n// runtime serves 500 edges a page, so the viewer holds up to 10,000 — far past\n// what the References list or the graph can show usefully — and a document\n// with more says so rather than looking complete.\nexport const EDGE_PAGE_CAP = 20;\n\n// loadDocumentEdges collects every edge touching a document, following\n// next_cursor until the runtime reports the list complete or the cap is hit.\n// get_edges orders by kind, so an unfollowed cursor drops whole kinds, not a\n// random sample. `incomplete` is true when the load stopped before the end: the\n// cap, a page marked truncated with no cursor, or a data layer that hands back\n// the cursor it was given (one that ignores `after` would otherwise repeat its\n// first page until the cap).\nexport async function loadDocumentEdges(\n data: Pick<ExplorerDataLayer, \"documentGetEdges\">,\n documentId: string,\n scope: DocScope,\n browse?: BrowseScope,\n maxPages: number = EDGE_PAGE_CAP,\n): Promise<{ edges: DocEdge[]; incomplete: boolean }> {\n const edges: DocEdge[] = [];\n let after: string | undefined;\n for (let page = 0; page < maxPages; page++) {\n const r = await data.documentGetEdges(documentId, scope, browse, after ? { after } : undefined);\n if (after && r.next_cursor === after) return { edges, incomplete: true };\n edges.push(...(r.edges ?? []));\n if (!r.truncated) return { edges, incomplete: false };\n if (!r.next_cursor) return { edges, incomplete: true };\n after = r.next_cursor;\n }\n return { edges, incomplete: true };\n}\n","import type { EdgeEvidence, StatementFields } from \"../types\";\n\n// Display helpers for the RFC FN statement envelope an edge carries. Pure, so the\n// rules for what a reference row shows are testable without rendering it.\n\n// Methods that are the ordinary way a link comes to exist in a document — typed\n// by hand or written as a [[wikilink]]. Only the others are worth a label.\nconst ORDINARY_METHODS = new Set([\"manual\", \"wikilink\"]);\n\n// EVIDENCE_PREVIEW is how many quotes a reference row shows; a listing carries at\n// most three anyway.\nexport const EVIDENCE_PREVIEW = 3;\nconst QUOTE_MAX = 280;\n\n// statusLabel is the badge for a statement that does not simply hold: proposed or\n// rejected. An asserted statement — or an older server's edge with no status —\n// gets none.\nexport function statusLabel(s: StatementFields): string | undefined {\n return s.status && s.status !== \"asserted\" ? s.status : undefined;\n}\n\n// methodLabel names how the statement was made, when that is not the ordinary\n// manual / wikilink way (an import, a sync, a canvas, an agent at runtime…).\nexport function methodLabel(s: StatementFields): string | undefined {\n return s.method && !ORDINARY_METHODS.has(s.method) ? s.method : undefined;\n}\n\n// isProposed: the statement waits for an operator's ruling.\nexport function isProposed(s: StatementFields): boolean {\n return s.status === \"proposed\" && !!s.id;\n}\n\n// formatNsDate renders a Unix-nanosecond timestamp as a UTC calendar date.\nexport function formatNsDate(ns: number): string {\n return new Date(Math.floor(ns / 1e6)).toISOString().slice(0, 10);\n}\n\n// validityLabel describes when the related thing holds, from valid_at / invalid_at,\n// or undefined when the statement carries neither.\nexport function validityLabel(s: StatementFields): string | undefined {\n const from = s.valid_at != null ? formatNsDate(s.valid_at) : undefined;\n const until = s.invalid_at != null ? formatNsDate(s.invalid_at) : undefined;\n if (from && until) return `valid ${from} → ${until}`;\n if (from) return `valid from ${from}`;\n if (until) return `valid until ${until}`;\n return undefined;\n}\n\n// verdictHint summarizes a ruling — an operator's or a judge model's — for a\n// tooltip: who judged, when, and why. undefined when nobody has judged it.\nexport function verdictHint(s: StatementFields): string | undefined {\n if (s.judged_at == null) return undefined;\n const head = `judged by ${s.judged_by || \"a judge\"} on ${formatNsDate(s.judged_at)}`;\n return s.judge_reason ? `${head}: ${s.judge_reason}` : head;\n}\n\n// evidencePreview picks the quotes a row shows and how many it leaves out.\n// `more` counts against evidence_count (the total), not the rows the listing\n// happened to carry.\nexport function evidencePreview(\n s: StatementFields,\n max = EVIDENCE_PREVIEW,\n): { rows: EdgeEvidence[]; more: number } {\n const rows = (s.evidence ?? []).slice(0, max);\n const total = Math.max(s.evidence_count ?? 0, s.evidence?.length ?? 0);\n return { rows, more: Math.max(0, total - rows.length) };\n}\n\n// clipQuote shortens a long quote for the row; the full text stays the element's\n// tooltip.\nexport function clipQuote(quote: string, max = QUOTE_MAX): string {\n const q = quote.replace(/\\s+/g, \" \").trim();\n return q.length > max ? q.slice(0, max - 1) + \"…\" : q;\n}\n","// A bulk ruling on proposed statements (POST /v1/_statements/rule), run the one\n// way every surface runs it: dry run first, then the real call carrying the dry\n// run's count, in chunks of at most RULING_CHUNK. The document viewer's\n// Connections panel and the Web UI's Review page both go through runRuling, so\n// the order of calls a reviewer's click makes is decided here alone.\n\n// The most statements one call rules (the runtime's cap).\nexport const RULING_CHUNK = 1000;\n// A queue that keeps changing under a ruling stops being retried after this\n// many fresh dry runs, rather than looping on a busy scope.\nexport const QUEUE_CHANGED_RETRIES = 3;\n// A hard ceiling on calls for one ruling: a million statements.\nconst MAX_CHUNKS = 1000;\n\nexport type RulingAction = \"accept\" | \"reject\";\nexport type RulingScope = \"tenant\" | \"user\";\n\n/** One statement's outcome in a ruling or a revert: the status it was ruled to,\n * or the refusal's code and message. */\nexport interface RulingItem {\n id: string;\n status?: string;\n error?: string;\n message?: string;\n}\n\n/** A rule call's body. `F` is the queue filter's shape. */\nexport interface RulingRequest<F> {\n action: RulingAction;\n ids?: string[];\n filter?: F;\n reason?: string;\n dry_run: boolean;\n expect_count?: number;\n max?: number;\n scope?: RulingScope;\n /** Whose user scope (with scope user): another subject's, for an operator. */\n scope_id?: string;\n}\n\n/** The counts of a rule call's answer that the sequence reads. */\nexport interface RulingCounts {\n dry_run: boolean;\n ruling_id?: string;\n /** What the selection matches that the caller may read; expect_count repeats it. */\n matched: number;\n /** The part this call considers: at most RULING_CHUNK, first in queue order. */\n selected: number;\n /** Of `selected`, the ones the caller may not rule on. */\n skipped: number;\n to_rule: number;\n ruled: number;\n failed: number;\n items?: RulingItem[] | null;\n}\n\nexport interface RulingApi<F, R extends RulingCounts> {\n rule(req: RulingRequest<F>): Promise<R>;\n}\n\nexport interface RulingSelection<F> {\n action: RulingAction;\n ids?: string[];\n filter?: F;\n reason?: string;\n scope?: RulingScope;\n /** Whose user documents, with scope user: the subject a viewer is browsing.\n * Every call of the ruling carries it. */\n scopeId?: string;\n}\n\n/** Why a reviewer is asked to confirm: the first dry run, a dry run after the\n * queue changed under the ruling (`queue_changed`), or one that found more\n * than was confirmed while ruling in chunks. */\nexport type ConfirmReason = \"first\" | \"queue_changed\" | \"grew\";\n\nexport interface RulingProgress {\n ruled: number;\n failed: number;\n /** What the reviewer confirmed: the dry run's match count. */\n total: number;\n chunks: number;\n}\n\nexport interface RulingOutcome {\n /** Each call that ruled made one ruling; undoing the whole ruling reverts each. */\n rulingIds: string[];\n ruled: number;\n failed: number;\n /** The last dry run's count of statements the caller may not rule on. */\n skipped: number;\n /** What the reviewer confirmed (0 when nothing matched). */\n total: number;\n /** The reviewer declined a confirm. */\n cancelled: boolean;\n /** The statements that did not take the ruling, with the runtime's reason. */\n failures: RulingItem[];\n /** A call failed part way; whatever was ruled before it is in rulingIds. */\n error?: unknown;\n}\n\nexport interface RulingHooks<R> {\n /** Asked with each dry run the reviewer has not seen yet; false stops. Omitted\n * (a single row, a hand-picked selection), nothing is asked. */\n confirm?: (dry: R, why: ConfirmReason) => Promise<boolean>;\n onProgress?: (p: RulingProgress) => void;\n}\n\n/** isQueueChanged recognizes the refusal of a real call whose expect_count no\n * longer matches. Read off the error's `code`, which both @loomcycle/client's\n * errors and a host's own carry. */\nexport function isQueueChanged(e: unknown): boolean {\n return !!e && typeof e === \"object\" && (e as { code?: unknown }).code === \"queue_changed\";\n}\n\n/** runRuling rules a selection: ALWAYS a dry run first (the confirm sees its\n * count and sample), then each real call carries that dry run's count as\n * expect_count. Over RULING_CHUNK matches it rules in chunks — dry run, rule,\n * dry run — until the selection is ruled, a chunk rules nothing (what is left\n * cannot be ruled by this caller), or the reviewer stops.\n *\n * A queue that changed between a dry run and its ruling (queue_changed) is\n * dry-run again and confirmed again. So is one that grew past what was\n * confirmed while chunking: \"all matching\" means what the reviewer saw. */\nexport async function runRuling<F, R extends RulingCounts>(\n api: RulingApi<F, R>,\n sel: RulingSelection<F>,\n hooks: RulingHooks<R> = {},\n): Promise<RulingOutcome> {\n const base: Omit<RulingRequest<F>, \"dry_run\"> = {\n action: sel.action,\n ...(sel.ids ? { ids: sel.ids } : { filter: sel.filter ?? ({} as F) }),\n ...(sel.reason ? { reason: sel.reason } : {}),\n ...(sel.scope && sel.scope !== \"tenant\" ? { scope: sel.scope } : {}),\n ...(sel.scope === \"user\" && sel.scopeId ? { scope_id: sel.scopeId } : {}),\n };\n const out: RulingOutcome = { rulingIds: [], ruled: 0, failed: 0, skipped: 0, total: 0, cancelled: false, failures: [] };\n const dryRun = async () => {\n const d = await api.rule({ ...base, dry_run: true });\n out.skipped = d.skipped;\n return d;\n };\n const confirm = async (d: R, why: ConfirmReason) => {\n if (!hooks.confirm || (await hooks.confirm(d, why))) {\n out.total = out.ruled + d.matched;\n return true;\n }\n out.cancelled = true;\n return false;\n };\n\n let dry: R;\n try {\n dry = await dryRun();\n } catch (e) {\n out.error = e;\n return out;\n }\n if (dry.matched === 0 || !(await confirm(dry, \"first\"))) return out;\n\n let retries = 0;\n for (let chunk = 0; chunk < MAX_CHUNKS; chunk++) {\n if (dry.to_rule === 0) break;\n let res: R;\n try {\n res = await api.rule({ ...base, dry_run: false, expect_count: dry.matched });\n } catch (e) {\n if (!isQueueChanged(e) || retries >= QUEUE_CHANGED_RETRIES) {\n out.error = e;\n return out;\n }\n retries++;\n try {\n dry = await dryRun();\n } catch (e2) {\n out.error = e2;\n return out;\n }\n if (dry.matched === 0 || !(await confirm(dry, \"queue_changed\"))) return out;\n continue;\n }\n if (res.ruling_id) out.rulingIds.push(res.ruling_id);\n out.ruled += res.ruled;\n out.failed += res.failed;\n for (const it of res.items ?? []) if (it.error) out.failures.push(it);\n hooks.onProgress?.({ ruled: out.ruled, failed: out.failed, total: out.total, chunks: out.rulingIds.length });\n // Everything the selection matched was in this call's window, or the call\n // ruled nothing: what is left is not this caller's to rule.\n if (res.ruled === 0 || res.matched <= res.selected) break;\n try {\n dry = await dryRun();\n } catch (e) {\n out.error = e;\n return out;\n }\n if (dry.matched === 0) break;\n if (dry.matched > out.total - out.ruled && !(await confirm(dry, \"grew\"))) return out;\n }\n return out;\n}\n\nexport interface UndoOutcome {\n reverted: number;\n changed: number;\n /** Rulings the runtime could not undo (not found, refused), with why. */\n errors: string[];\n}\n\n/** undoRulings reverts each ruling of a bulk ruling, newest first, and adds up\n * what came back. One ruling failing does not stop the others. */\nexport async function undoRulings(\n revert: (rulingId: string) => Promise<{ reverted: number; changed: number }>,\n rulingIds: string[],\n): Promise<UndoOutcome> {\n const out: UndoOutcome = { reverted: 0, changed: 0, errors: [] };\n for (const id of [...rulingIds].reverse()) {\n try {\n const r = await revert(id);\n out.reverted += r.reverted;\n out.changed += r.changed;\n } catch (e) {\n out.errors.push(e instanceof Error ? e.message : String(e));\n }\n }\n return out;\n}\n\n/** chunkCount is how many calls a confirmed ruling of `matched` takes. */\nexport function chunkCount(matched: number): number {\n return Math.max(1, Math.ceil(matched / RULING_CHUNK));\n}\n","// RFC FS — ruling on one document's proposals at once, from the document viewer.\n// The sequence is runRuling's (dry run first, expect_count, chunks); what is\n// here is which documents it is offered for and what it selects.\n\nimport type { BrowseScope, DocEdge, DocScope } from \"../types\";\nimport type { DocRulingAnswer, DocRulingFilter, ExplorerDataLayer } from \"./dataLayer\";\nimport { isProposed } from \"./statement\";\nimport { runRuling, type RulingAction, type RulingHooks, type RulingOutcome, type RulingScope } from \"./ruling\";\n\n// reviewScopeFor is the review scope a document's bulk ruling acts in, or\n// undefined for an agent-scope document, which the review routes do not reach.\n// A user document is reviewed in the scope of the subject being browsed\n// (ruleDocumentProposals sends it as scope_id); the runtime decides whether\n// the caller may name that subject.\nexport function reviewScopeFor(scope: DocScope): RulingScope | undefined {\n return scope === \"tenant\" || scope === \"user\" ? scope : undefined;\n}\n\n// bulkReviewScope is where the document viewer offers bulk review: the review\n// scope, when the data layer can rule in bulk (documentRuleStatements is\n// optional — a custom data layer without it gets no bulk action) and the review\n// routes reach the document.\nexport function bulkReviewScope(\n data: Pick<ExplorerDataLayer, \"documentRuleStatements\">,\n scope: DocScope,\n): RulingScope | undefined {\n return data.documentRuleStatements ? reviewScopeFor(scope) : undefined;\n}\n\n// documentProposals is the document's own proposals among its edges: those\n// filed from it, which is what from_document_id selects on the server.\nexport function documentProposals(edges: DocEdge[], documentId: string): DocEdge[] {\n return edges.filter((e) => isProposed(e) && !!e.id && e.from_document_id === documentId);\n}\n\n// ReviewPanel is what the Connections panel needs to offer bulk review.\nexport interface ReviewPanel {\n proposals: DocEdge[];\n scope: RulingScope;\n // The edge list stopped at its page cap: proposals past it are not listed.\n incomplete: boolean;\n onChanged: () => void;\n}\n\n// reviewPanel decides whether the Connections panel shows bulk review: wherever\n// it can rule (scope), even with nothing listed. Hiding it at zero unmounted it\n// the moment a ruling took the document's last proposal, and with it the\n// ruling's result and its Undo.\nexport function reviewPanel(\n scope: RulingScope | undefined,\n proposals: DocEdge[],\n incomplete: boolean,\n onChanged: () => void,\n): ReviewPanel | undefined {\n return scope ? { proposals, scope, incomplete, onChanged } : undefined;\n}\n\nexport interface DocumentRuling {\n documentId: string;\n action: RulingAction;\n // The statements picked by hand; empty or absent rules every proposal filed\n // from the document.\n ids?: string[];\n reason?: string;\n scope: RulingScope;\n browse?: BrowseScope;\n}\n\n// ruleDocumentProposals rules a document's proposals through the data layer's\n// bulk ruling. Rejects when the data layer has none.\nexport function ruleDocumentProposals(\n data: ExplorerDataLayer,\n r: DocumentRuling,\n hooks?: RulingHooks<DocRulingAnswer>,\n): Promise<RulingOutcome> {\n if (!data.documentRuleStatements) {\n return Promise.reject(new Error(\"this data layer cannot rule in bulk\"));\n }\n return runRuling<DocRulingFilter, DocRulingAnswer>(\n // Called through `data` so a class-based data layer keeps `this`.\n { rule: (req) => data.documentRuleStatements!(req, r.browse) },\n {\n action: r.action,\n ...(r.ids && r.ids.length > 0 ? { ids: r.ids } : { filter: { from_document_id: r.documentId } }),\n ...(r.reason ? { reason: r.reason } : {}),\n scope: r.scope,\n // The browsed subject's user documents: the review routes take it as\n // scope_id, as the document reads take it as browse.scopeId.\n ...(r.scope === \"user\" && r.browse?.scopeId ? { scopeId: r.browse.scopeId } : {}),\n },\n hooks,\n );\n}\n\n// rulingNote is the one line a ruling leaves in the panel.\nexport function rulingNote(action: RulingAction, o: RulingOutcome): string {\n const n = (x: number) => x.toLocaleString(\"en-US\");\n const parts = [`${action === \"accept\" ? \"Accepted\" : \"Rejected\"} ${n(o.ruled)} statement${o.ruled === 1 ? \"\" : \"s\"}`];\n if (o.failed > 0) parts.push(`${n(o.failed)} did not take the ruling`);\n if (o.skipped > 0) parts.push(`${n(o.skipped)} skipped: not yours to rule`);\n return parts.join(\"; \") + \".\";\n}\n","import type {\n AcceptClassificationAnswer,\n ClassificationRecord,\n ClassifyAnswer,\n ClassifyCandidate,\n ClassifyStep,\n} from \"../types\";\n\n// Display helpers for RFC FO classification (the classify and\n// accept_classification Document ops). Pure, so what the viewer shows is\n// testable without rendering it.\n\n// PendingClassification is what waits in a root chunk's classification record\n// for an operator to accept.\nexport interface PendingClassification {\n proposedType?: string;\n proposedTags: string[];\n statementCount: number;\n}\n\nfunction isStringArray(v: unknown): v is string[] {\n return Array.isArray(v) && v.every((x) => typeof x === \"string\");\n}\n\n// classificationRecord reads `fields.classification` off a root chunk's fields.\n// The record lives in ordinary chunk fields, which any writer of the document may\n// set, so it is read defensively: a field of the wrong shape is dropped rather\n// than trusted, and anything that is not an object reads as no record.\nexport function classificationRecord(fields: unknown): ClassificationRecord | undefined {\n if (!fields || typeof fields !== \"object\") return undefined;\n const raw = (fields as { classification?: unknown }).classification;\n if (!raw || typeof raw !== \"object\" || Array.isArray(raw)) return undefined;\n const r = raw as Record<string, unknown>;\n const rec: ClassificationRecord = {};\n if (typeof r.by === \"string\") rec.by = r.by;\n if (typeof r.at === \"number\") rec.at = r.at;\n if (typeof r.applied_type === \"string\" && r.applied_type) rec.applied_type = r.applied_type;\n if (typeof r.proposed_type === \"string\" && r.proposed_type) rec.proposed_type = r.proposed_type;\n if (r.proposed_fields && typeof r.proposed_fields === \"object\" && !Array.isArray(r.proposed_fields)) {\n rec.proposed_fields = r.proposed_fields as Record<string, unknown>;\n }\n if (isStringArray(r.proposed_tags)) rec.proposed_tags = r.proposed_tags;\n if (isStringArray(r.statements)) rec.statements = r.statements;\n return rec;\n}\n\n// pendingClassification is the runtime's own \"nothing_pending\" test turned\n// around: a record is pending when it proposes a type, names statements, or\n// proposes tags. undefined when nothing waits (an applied-only record included).\nexport function pendingClassification(fields: unknown): PendingClassification | undefined {\n const rec = classificationRecord(fields);\n if (!rec) return undefined;\n const proposedTags = rec.proposed_tags ?? [];\n const statementCount = rec.statements?.length ?? 0;\n if (!rec.proposed_type && proposedTags.length === 0 && statementCount === 0) return undefined;\n return { proposedType: rec.proposed_type, proposedTags, statementCount };\n}\n\n// resultLabel says what a classify answer decided. A `report` answer wrote\n// nothing, so it says what an Apply would do; a `propose` answer says what was\n// done.\nexport function resultLabel(a: Pick<ClassifyAnswer, \"result\" | \"write\">): string {\n const report = a.write === \"report\";\n switch (a.result) {\n case \"classified\":\n return report ? \"would be classified\" : \"classified\";\n case \"proposed\":\n return report ? \"would be proposed for review\" : \"proposed — waits for review\";\n case \"kept\":\n return \"kept — the type was set by hand\";\n case \"unclassified\":\n return \"unclassified — nothing decided\";\n default:\n return String(a.result);\n }\n}\n\n// classDisposition says what became (or would become) of the class: applied to\n// the document live, or only proposed. undefined when no class was chosen. A\n// kept answer still names the class classify would choose, but never applies it.\nexport function classDisposition(\n a: Pick<ClassifyAnswer, \"class\" | \"live\" | \"result\" | \"write\">,\n): string | undefined {\n if (!a.class) return undefined;\n if (a.result === \"kept\") return \"not applied\";\n const report = a.write === \"report\";\n if (a.live) return report ? \"would be applied\" : \"applied\";\n return report ? \"would be proposed\" : \"proposed\";\n}\n\n// canApply: a report answer that a propose run would act on — a class to apply\n// or propose, or concepts / issuers to file. A propose answer has already been\n// applied, and an empty unclassified or kept report has nothing to write.\nexport function canApply(a: ClassifyAnswer): boolean {\n if (a.write !== \"report\") return false;\n if (a.result === \"classified\" || a.result === \"proposed\") return true;\n return (a.concepts?.length ?? 0) > 0 || (a.issued_by?.length ?? 0) > 0;\n}\n\n// formatShare renders a 0..1 share as a whole percentage.\nexport function formatShare(share: number | undefined): string {\n if (share == null || !Number.isFinite(share)) return \"\";\n return `${Math.round(share * 100)}%`;\n}\n\nconst STEP_LABELS: Record<string, string> = {\n rules: \"Rules\",\n vote: \"Neighbourhood vote\",\n model: \"Model\",\n};\n\n// stepLabel names a step; an unknown step name (a newer runtime) shows verbatim.\nexport function stepLabel(step: string): string {\n return STEP_LABELS[step] ?? step;\n}\n\n// candidateDetail is the one-line explanation of a candidate: the quote a rule\n// matched and where, or a vote's count and share.\nexport function candidateDetail(c: ClassifyCandidate): string {\n const parts: string[] = [];\n if (c.quote) parts.push(c.from ? `“${c.quote}” (${c.from})` : `“${c.quote}”`);\n if (c.votes != null) parts.push(`${c.votes} vote${c.votes === 1 ? \"\" : \"s\"}`);\n const share = formatShare(c.share);\n if (share) parts.push(share);\n return parts.join(\" · \");\n}\n\n// StepSummary is one step reduced to what the panel shows on its line; the\n// candidates go behind a collapsible.\nexport interface StepSummary {\n label: string;\n chosen?: string;\n method?: string;\n neighbours?: number;\n reason?: string;\n candidates: { class: string; detail: string }[];\n}\n\nexport function summarizeStep(s: ClassifyStep): StepSummary {\n return {\n label: stepLabel(s.step),\n ...(s.chosen ? { chosen: s.chosen } : {}),\n ...(s.method ? { method: s.method } : {}),\n ...(s.neighbours ? { neighbours: s.neighbours } : {}),\n ...(s.reason ? { reason: s.reason } : {}),\n candidates: (s.candidates ?? []).map((c) => ({ class: c.class, detail: candidateDetail(c) })),\n };\n}\n\n// acceptSummary reduces an accept_classification answer to a headline of what\n// became live, plus a notice per thing that did not: a class left pending or not\n// applied, skipped statements or tags, and the runtime's warnings.\nexport function acceptSummary(a: AcceptClassificationAnswer): { applied: string; notices: string[] } {\n const done: string[] = [];\n if (a.type) done.push(`type ${a.type}`);\n const n = a.accepted_statements?.length ?? 0;\n if (n > 0) done.push(`${n} statement${n === 1 ? \"\" : \"s\"}`);\n if (a.tags && a.tags.length > 0) done.push(`tags ${a.tags.join(\", \")}`);\n const notices: string[] = [];\n if (a.type_pending) {\n notices.push(\"The proposed class stays pending: another document already holds its identity.\");\n }\n if (a.skipped_type) {\n notices.push(`Class ${a.skipped_type} was not applied: it is not a declared document class.`);\n }\n const skipped = a.skipped_statements?.length ?? 0;\n if (skipped > 0) {\n notices.push(\n `${skipped} statement${skipped === 1 ? \" was\" : \"s were\"} skipped (already ruled on, or not this document's proposal).`,\n );\n }\n if (a.skipped_tags && a.skipped_tags.length > 0) {\n notices.push(`Tags not applied (not concepts of the ontology): ${a.skipped_tags.join(\", \")}.`);\n }\n notices.push(...(a.warnings ?? []));\n return { applied: done.length > 0 ? `Accepted ${done.join(\", \")}.` : \"Nothing was accepted.\", notices };\n}\n\n// classifyErrorText turns a refused op into the line the panel shows. The\n// runtime's nothing_pending business error gets plain words; anything else\n// (a permission refusal, an unconfirmed ontology) shows the runtime's own text.\nexport function classifyErrorText(e: unknown): string {\n const msg = e instanceof Error ? e.message : String(e);\n if (msg.includes(\"nothing_pending\")) return \"Nothing is pending for this document — it may already have been accepted.\";\n return msg;\n}\n","// copyToClipboard writes text to the system clipboard and returns whether it\n// succeeded. It is a standalone helper (not inlined in the button) so the copy\n// affordance's success/failure branch is unit-testable without a DOM — the UI\n// only needs the boolean. It guards a missing clipboard (an insecure context, an\n// old browser, or a non-browser test env) by returning false rather than\n// throwing, so a copy button can never crash the viewer.\nexport async function copyToClipboard(text: string): Promise<boolean> {\n try {\n if (typeof navigator === \"undefined\" || !navigator.clipboard) return false;\n await navigator.clipboard.writeText(text);\n return true;\n } catch {\n return false;\n }\n}\n","import type { BrowseScope, DocScope } from \"../types\";\nimport type { ExplorerDataLayer } from \"./dataLayer\";\nimport { fileStem, saveBlob, type RenderFormat } from \"./download\";\n\n// The files a whole document downloads as (RFC BS .md / .canvas, RFC GR\n// rendered files). The document header's \"more\" menu lists them.\n\n/** One download of the document. */\nexport type DownloadKind = \"pdf\" | \"docx\" | \"odt\" | \"epub\" | \"html\" | \"md\" | \"canvas\";\n\nexport interface DownloadEntry {\n kind: DownloadKind;\n label: string;\n title: string;\n // rendered: the runtime renders the file (RFC GR) — needs documentExportFile.\n rendered: boolean;\n}\n\nconst ENTRIES: DownloadEntry[] = [\n { kind: \"pdf\", label: \"PDF\", title: \"Render the whole document as a PDF file\", rendered: true },\n { kind: \"docx\", label: \"Word (.docx)\", title: \"Render the whole document as a Word document\", rendered: true },\n { kind: \"odt\", label: \"OpenDocument (.odt)\", title: \"Render the whole document as an OpenDocument text file\", rendered: true },\n { kind: \"epub\", label: \"E-book (.epub)\", title: \"Render the whole document as an EPUB e-book\", rendered: true },\n { kind: \"html\", label: \"HTML\", title: \"Render the whole document as a web page\", rendered: true },\n {\n kind: \"md\",\n label: \"Markdown (.md)\",\n title: \"Download the whole document as Markdown, with the metadata comments that let it be imported back\",\n rendered: false,\n },\n {\n kind: \"canvas\",\n label: \"Canvas (.canvas)\",\n title: \"Download the whole document as a node/edge canvas graph (.canvas)\",\n rendered: false,\n },\n];\n\n/** The downloads offered for a data layer: the rendered formats only when it\n * can fetch a rendered file. */\nexport function downloadEntries(data: Pick<ExplorerDataLayer, \"documentExportFile\">): DownloadEntry[] {\n return ENTRIES.filter((e) => !e.rendered || !!data.documentExportFile);\n}\n\n/** Fetch one download through the data layer and hand it to the browser.\n * .md and .canvas keep their own exports (the round-trippable Markdown with\n * metadata comments, the canvas graph); the rest are rendered by the runtime. */\nexport async function runDownload(\n data: ExplorerDataLayer,\n kind: DownloadKind,\n documentId: string,\n scope: DocScope,\n browse: BrowseScope | undefined,\n title: string | undefined,\n save: (blob: Blob, filename: string) => void = saveBlob,\n): Promise<void> {\n if (kind === \"md\") {\n const r = await data.documentExportMd(documentId, scope, true, browse);\n save(new Blob([r.markdown], { type: \"text/markdown\" }), fileStem(r.title) + \".md\");\n return;\n }\n if (kind === \"canvas\") {\n const r = await data.documentExportCanvas(documentId, scope, browse);\n save(new Blob([JSON.stringify(r.canvas, null, 2)], { type: \"application/json\" }), fileStem(title) + \".canvas\");\n return;\n }\n if (!data.documentExportFile) throw new Error(\"this connection cannot download rendered files\");\n const format: RenderFormat = kind;\n const r = await data.documentExportFile(documentId, scope, format, browse);\n // The server names the file; without a name, the title and the format.\n save(r.blob, r.filename || fileStem(title) + \".\" + format);\n}\n","import type { CSSProperties } from \"react\";\n\n// RFC BN per-document color schemes. A document can tint its chunk tiles and its\n// Path-tree row by (document type, state) and (chunk state), so a reader scanning\n// the tree sees kind + progress at a glance. A scheme is a flat map of semantic\n// keys → CSS hex colors, stored in the document's ROOT chunk fields (color_scheme)\n// alongside a color_enabled flag; the backend stores/returns it verbatim and this\n// module is the only place that interprets it.\n\n// ColorScheme maps a semantic key to a CSS hex color. Keys:\n// doc.<type>.<status> — a document tile/row by its ROOT chunk's type + status\n// doc.<type> — fallback for any status of that document type\n// doc.*.<status> — fallback for a type the scheme does not name, by status\n// doc.* — fallback for a type the scheme does not name, any status\n// chunk.<status> — a chunk tile by its own status\n// chunk.inherit — \"false\" (or \"none\" / \"off\") keeps a chunk without a\n// status colour neutral; by default it takes a lighter\n// wash of its document's colour\n// Unknown keys are ignored; a missing key → no tint (neutral). Keys match a type\n// or status ignoring case, so an ontology class type (`Rfc`) finds `doc.rfc.*`.\nexport type ColorScheme = Record<string, string>;\n\n// DocSummary is one row of the document `documents_summary` op (Path-tree color).\nexport interface DocSummary {\n document_id: string;\n title: string;\n root_chunk_id?: string;\n type?: string;\n status?: string;\n color_enabled: boolean;\n color_scheme?: ColorScheme;\n // brief — the document's annotation brief, present only when the document\n // has an annotation (tenant scope). The Path tree shows it under the name.\n brief?: string;\n}\n\n// DocumentMeta is the enriched get_document result (the viewer's own document).\nexport interface DocumentMeta {\n document_id: string;\n title: string;\n root_chunk_id?: string;\n type?: string;\n status?: string;\n color_enabled: boolean;\n color_scheme?: ColorScheme;\n}\n\n// DEFAULT_SCHEME seeds a new document's palette. The hexes are mid-tone so the\n// low-alpha wash reads on BOTH the dark and light explorer themes; the scheme\n// editor starts from this, and the resolver falls back to it when a document has\n// color_enabled but no stored scheme yet.\nexport const DEFAULT_SCHEME: ColorScheme = {\n \"doc.rfc.draft\": \"#c99a3a\",\n \"doc.rfc.review\": \"#6a7bd6\",\n \"doc.rfc.confirmed\": \"#3a9ad6\",\n \"doc.rfc.done\": \"#3aa06a\",\n // plan documents share the RFC lifecycle vocabulary (draft→review→confirmed→done).\n \"doc.plan.draft\": \"#c99a3a\",\n \"doc.plan.review\": \"#6a7bd6\",\n \"doc.plan.confirmed\": \"#3a9ad6\",\n \"doc.plan.done\": \"#3aa06a\",\n \"doc.document.done\": \"#3aa06a\",\n \"doc.research.done\": \"#8a6ad6\",\n \"doc.publication.draft\": \"#c99a3a\",\n // Any other type — an ontology class (Guide, Benchmark, …) or one added later —\n // is coloured by its status alone, so retyping a document never blanks it.\n \"doc.*.draft\": \"#c99a3a\",\n \"doc.*.review\": \"#6a7bd6\",\n \"doc.*.confirmed\": \"#3a9ad6\",\n \"doc.*.done\": \"#3aa06a\",\n \"chunk.draft\": \"#c99a3a\",\n \"chunk.review\": \"#6a7bd6\",\n \"chunk.confirmed\": \"#3a9ad6\",\n \"chunk.done\": \"#3aa06a\",\n // PR-workflow chunk statuses (a plan document's PR chunks): queued → active → done.\n \"chunk.backlog\": \"#8a8f98\",\n \"chunk.implementation\": \"#d1863a\",\n \"chunk.merged\": \"#3aa06a\",\n};\n\n// TINT_ALPHA washes every scheme color into a tile background — a tint, not a\n// fill — so the row text stays readable (the loomcycle tinted-tile pattern).\nconst TINT_ALPHA = 0.16;\n\n// effectiveScheme is what the resolvers read: the stored scheme if present, else\n// the defaults (so color_enabled alone gives a sensible palette before any edit).\nexport function effectiveScheme(scheme: ColorScheme | undefined): ColorScheme {\n return scheme && Object.keys(scheme).length > 0 ? scheme : DEFAULT_SCHEME;\n}\n\n// lookup reads one scheme key: exactly, else ignoring case. Types are written\n// both ways — the built-in lowercase `rfc` and an ontology's class name `Rfc` —\n// and a document retyped from one to the other must keep its colour.\nfunction lookup(scheme: ColorScheme, key: string): string | undefined {\n if (Object.prototype.hasOwnProperty.call(scheme, key) && scheme[key]) return scheme[key];\n const want = key.toLowerCase();\n for (const k of Object.keys(scheme)) {\n if (k.toLowerCase() === want && scheme[k]) return scheme[k];\n }\n return undefined;\n}\n\n// docColor resolves a document's raw tile color from its (type,status): tries\n// doc.<type>.<status>, then doc.<type>, then the any-type keys doc.*.<status> and\n// doc.*. Returns undefined for no match.\nexport function docColor(\n type: string | undefined,\n status: string | undefined,\n scheme: ColorScheme,\n): string | undefined {\n const t = type ?? \"\";\n const s = status ?? \"\";\n return (\n (t && s ? lookup(scheme, `doc.${t}.${s}`) : undefined) ??\n (t ? lookup(scheme, `doc.${t}`) : undefined) ??\n (s ? lookup(scheme, `doc.*.${s}`) : undefined) ??\n lookup(scheme, \"doc.*\")\n );\n}\n\n// chunkColor resolves a chunk tile's raw color from its status (chunk.<status>).\nexport function chunkColor(status: string | undefined, scheme: ColorScheme): string | undefined {\n const s = status ?? \"\";\n return s ? lookup(scheme, `chunk.${s}`) : undefined;\n}\n\n// chunkInheritsDocColor reports whether a chunk with no colour of its own takes\n// its document's colour. Corpus chunks (sections of a law, of a regulation)\n// carry no status, and should not get a placeholder one just to be coloured —\n// status is a meaningful field that search filters on — so by default they wear\n// their document's colour; `chunk.inherit: \"false\"` turns that off.\nexport function chunkInheritsDocColor(scheme: ColorScheme): boolean {\n const v = String(scheme[\"chunk.inherit\"] ?? \"\")\n .trim()\n .toLowerCase();\n return !(v === \"false\" || v === \"none\" || v === \"off\" || v === \"0\");\n}\n\n// hexToTint converts a #rgb / #rrggbb color to an rgba() wash at alpha\n// (TINT_ALPHA by default); undefined for a value it can't parse (→ no tint).\nexport function hexToTint(hex: string, alpha: number = TINT_ALPHA): string | undefined {\n const m = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(hex.trim());\n if (!m) return undefined;\n let h = m[1];\n if (h.length === 3) h = h[0] + h[0] + h[1] + h[1] + h[2] + h[2];\n const r = parseInt(h.slice(0, 2), 16);\n const g = parseInt(h.slice(2, 4), 16);\n const b = parseInt(h.slice(4, 6), 16);\n return `rgba(${r}, ${g}, ${b}, ${alpha})`;\n}\n\n// tintStyle is the inline style for a tinted row/tile: a low-alpha wash\n// background + a full-color left accent. undefined (→ no style) when the color is\n// absent or unparseable, so a caller spreads it unconditionally.\nexport function tintStyle(color: string | undefined): CSSProperties | undefined {\n if (!color) return undefined;\n const bg = hexToTint(color);\n if (!bg) return undefined;\n return { background: bg, borderLeft: `3px solid ${color}` };\n}\n\n// washStyle is the lighter tint a chunk inherits from its document: half the\n// wash and no left accent, so a chunk with a status colour of its own (a\n// passport block's pass / fail) still stands out among its neighbours.\nexport function washStyle(color: string | undefined): CSSProperties | undefined {\n if (!color) return undefined;\n const bg = hexToTint(color, TINT_ALPHA / 2);\n return bg ? { background: bg } : undefined;\n}\n\n// chunkRowStyle is a chunk-tree row's tint. The document's own row (its root\n// chunk) wears the document's colour, as its Path-tree row does; any other\n// chunk its status colour (chunk.<status>), else — unless the scheme turns it\n// off — a lighter wash of the document's colour. scheme null = colouring off.\nexport function chunkRowStyle(opts: ChunkRowColorOpts): CSSProperties | undefined {\n const c = chunkRowColor(opts);\n if (!c) return undefined;\n return c.wash ? washStyle(c.color) : tintStyle(c.color);\n}\n\ninterface ChunkRowColorOpts {\n status: string | undefined;\n isRoot: boolean;\n documentColor: string | undefined;\n scheme: ColorScheme | null;\n}\n\n// parseable keeps a colour only when it can be turned into a tint, so a\n// fallback chain skips an unparseable value as tintStyle's undefined did.\nfunction parseable(color: string | undefined): string | undefined {\n return color && hexToTint(color) ? color : undefined;\n}\n\n// chunkRowColor decides WHICH colour a chunk-tree row wears and whether it is\n// the full tint or the lighter inherited wash. chunkRowStyle (the flat tile)\n// and chunkRowTint (the tree row's gradient) both render from it, so the two\n// can never disagree about which rows are coloured.\nfunction chunkRowColor(opts: ChunkRowColorOpts): { color: string; wash: boolean } | undefined {\n const { status, isRoot, documentColor, scheme } = opts;\n if (!scheme) return undefined;\n if (isRoot) {\n const c = parseable(documentColor) ?? parseable(chunkColor(status, scheme));\n return c ? { color: c, wash: false } : undefined;\n }\n const own = parseable(chunkColor(status, scheme));\n if (own) return { color: own, wash: false };\n const inherited = chunkInheritsDocColor(scheme) ? parseable(documentColor) : undefined;\n return inherited ? { color: inherited, wash: true } : undefined;\n}\n\n// A tree row's colour is a gradient that fades out to the right, so it starts\n// stronger than the flat tile wash to read as clearly at the row's left edge.\nconst ROW_TINT_ALPHA = 0.3;\n// The wash a chunk inherits from its document. Half the full tint faded out to\n// nothing in the outline, so it sits closer to it.\nconst ROW_WASH_ALPHA = 0.22;\n\n// rowTint is the inline style for a coloured explorer tree row (the shared\n// .etree-row). It sets only the --etree-tint custom property: the stylesheet\n// paints the gradient from it and layers hover and selection above it, so an\n// inline colour can never hide the selected state. wash = the lighter tint a\n// chunk inherits from its document.\nexport function rowTint(color: string | undefined, wash = false): CSSProperties | undefined {\n if (!color) return undefined;\n const tint = hexToTint(color, wash ? ROW_WASH_ALPHA : ROW_TINT_ALPHA);\n return tint ? ({ \"--etree-tint\": tint } as CSSProperties) : undefined;\n}\n\n// chunkRowTint is chunkRowStyle's decision rendered as a tree-row gradient.\nexport function chunkRowTint(opts: ChunkRowColorOpts): CSSProperties | undefined {\n const c = chunkRowColor(opts);\n return c ? rowTint(c.color, c.wash) : undefined;\n}\n\n// statusDotColor is the colour of a row's compact status mark: the status's\n// chunk.<status> colour in the given palette, else in the default palette,\n// else undefined (the stylesheet's neutral dot).\nexport function statusDotColor(status: string | undefined, scheme?: ColorScheme): string | undefined {\n if (!status) return undefined;\n return (scheme ? parseable(chunkColor(status, scheme)) : undefined) ?? parseable(chunkColor(status, DEFAULT_SCHEME));\n}\n\n","import type { CSSProperties, KeyboardEvent, ReactNode } from \"react\";\nimport { useAnnotationCard, type CardSpec } from \"./AnnotationCard\";\n\n// The one row design both explorer trees share (RFC GZ): the Path tree and the\n// document's chunk outline. A row is a single 28px line on a fixed grid —\n// indent × depth | caret | icon | name | marks — and the whole row selects;\n// the caret is the only separate target and never selects.\n//\n// The classes are the explorer's own (.etree-*), not the agent-run tree's\n// .tree / .node .row, so styling one can never restyle the other.\n\nexport type TreeIconKind =\n | \"folder\"\n | \"document\"\n | \"volume\"\n | \"memory\"\n | \"annotation\"\n | \"image\"\n | \"diagram\"\n | \"link\";\n\n// TreeIcon draws the row icons as inline SVG at one fixed size, so every name\n// starts at the same offset (the emoji they replace varied in width per font).\n// Stroke-only shapes in currentColor, so they follow the theme.\nexport function TreeIcon({ kind }: { kind: TreeIconKind }) {\n return (\n <svg\n className={`etree-svg etree-svg-${kind}`}\n width=\"16\"\n height=\"16\"\n viewBox=\"0 0 16 16\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"1.3\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n aria-hidden=\"true\"\n focusable=\"false\"\n >\n {ICON_PATHS[kind]}\n </svg>\n );\n}\n\nconst ICON_PATHS: Record<TreeIconKind, ReactNode> = {\n folder: <path d=\"M1.75 4.25v8a1 1 0 0 0 1 1h10.5a1 1 0 0 0 1-1v-6.5a1 1 0 0 0-1-1H8L6.5 3.25H2.75a1 1 0 0 0-1 1z\" />,\n document: (\n <>\n <path d=\"M9.25 1.75h-5a1 1 0 0 0-1 1v10.5a1 1 0 0 0 1 1h7.5a1 1 0 0 0 1-1v-8.25z\" />\n <path d=\"M9.25 1.75v3.5h3.5M5.5 8.5h5M5.5 11h3.5\" />\n </>\n ),\n volume: (\n <>\n <rect x=\"1.75\" y=\"4.25\" width=\"12.5\" height=\"7.5\" rx=\"1\" />\n <path d=\"M4.5 8h.01M7 8h4.5\" />\n </>\n ),\n memory: (\n <>\n <ellipse cx=\"8\" cy=\"3.75\" rx=\"5.25\" ry=\"2\" />\n <path d=\"M2.75 3.75v8.5c0 1.1 2.35 2 5.25 2s5.25-.9 5.25-2v-8.5M2.75 8c0 1.1 2.35 2 5.25 2s5.25-.9 5.25-2\" />\n </>\n ),\n annotation: (\n <>\n <path d=\"M9.25 1.75h-5a1 1 0 0 0-1 1v10.5a1 1 0 0 0 1 1h7.5a1 1 0 0 0 1-1v-8.25z\" />\n <path d=\"M9.25 1.75v3.5h3.5M5.5 8.5l1.5 1.5 3-3\" />\n </>\n ),\n image: (\n <>\n <rect x=\"1.75\" y=\"2.75\" width=\"12.5\" height=\"10.5\" rx=\"1\" />\n <circle cx=\"5.5\" cy=\"6.25\" r=\"1.25\" />\n <path d=\"M14.25 10.5l-3.5-3.5-7.5 6.25\" />\n </>\n ),\n diagram: (\n <>\n <rect x=\"1.75\" y=\"1.75\" width=\"4.5\" height=\"3.5\" rx=\"0.5\" />\n <rect x=\"9.75\" y=\"10.75\" width=\"4.5\" height=\"3.5\" rx=\"0.5\" />\n <path d=\"M4 5.25v4.5a1 1 0 0 0 1 1h4.75\" />\n </>\n ),\n link: (\n <>\n <path d=\"M6.75 9.25a2.75 2.75 0 0 0 3.9 0l2-2a2.75 2.75 0 0 0-3.9-3.9l-.5.5\" />\n <path d=\"M9.25 6.75a2.75 2.75 0 0 0-3.9 0l-2 2a2.75 2.75 0 0 0 3.9 3.9l.5-.5\" />\n </>\n ),\n};\n\n// TreeMarks are a row's type tag and status dot at its right edge. The tag\n// shows the type's name, cut by the stylesheet to a fixed width; the full\n// label is in its title — or, on a tree row (`bare`), in the row's card, so\n// two tooltips never show at once.\nexport function TreeMarks({\n type,\n status,\n statusColor,\n extra,\n bare,\n}: {\n type?: string;\n status?: string;\n statusColor?: string;\n extra?: ReactNode;\n bare?: boolean;\n}) {\n if (!type && !status && !extra) return null;\n return (\n <span className=\"etree-marks\">\n {extra}\n {type && (\n <span className=\"etree-mark etree-mark-type\" title={bare ? undefined : `type: ${type}`}>\n {type}\n </span>\n )}\n {status && (\n <span\n className=\"etree-mark etree-mark-status\"\n role=\"img\"\n title={bare ? undefined : `status: ${status}`}\n aria-label={`status ${status}`}\n style={statusColor ? ({ \"--etree-dot\": statusColor } as CSSProperties) : undefined}\n />\n )}\n </span>\n );\n}\n\nexport interface TreeItemProps {\n // depth is 0 for a top-level row; the indent is depth × one step.\n depth: number;\n // expandable: the row has (or may have) children, so its caret is live.\n expandable: boolean;\n expanded: boolean;\n onToggle: () => void;\n selected: boolean;\n onSelect: () => void;\n // tabbable: this row is the tree's one tab stop — the selected row while it\n // is drawn, else the first row.\n tabbable: boolean;\n icon?: ReactNode;\n name: ReactNode;\n title?: string;\n marks?: ReactNode;\n // count: the slot at the row's right edge for a number (a folder's\n // documents, RFC HA). Omitted → no slot.\n count?: ReactNode;\n // card: the row's annotation card, opened by a hover or the keyboard focus.\n card?: CardSpec;\n // rowClassName marks the row itself (a search hit).\n rowClassName?: string;\n // style carries the row's tint (rowTint / chunkRowTint) — a custom property\n // only, never a background.\n style?: CSSProperties;\n className?: string;\n // children: the child rows, drawn in a role=\"group\" list only when expanded.\n children?: ReactNode;\n}\n\n// TreeItem is one treeitem: the row and, when expanded, its children.\nexport function TreeItem({\n depth,\n expandable,\n expanded,\n onToggle,\n selected,\n onSelect,\n tabbable,\n icon,\n name,\n title,\n marks,\n count,\n card,\n rowClassName,\n style,\n className,\n children,\n}: TreeItemProps) {\n const isOpen = expandable && expanded;\n const c = useAnnotationCard(card);\n return (\n <li\n className={`etree-node${className ? ` ${className}` : \"\"}${selected ? \" selected\" : \"\"}`}\n role=\"treeitem\"\n aria-level={depth + 1}\n aria-selected={selected}\n aria-expanded={expandable ? isOpen : undefined}\n tabIndex={tabbable ? 0 : -1}\n {...c.focus}\n >\n <div\n ref={c.anchorRef}\n className={`etree-row${rowClassName ? ` ${rowClassName}` : \"\"}`}\n style={{ ...style, \"--etree-depth\": depth } as CSSProperties}\n title={title}\n onClick={onSelect}\n onMouseEnter={c.hover.onMouseEnter}\n onMouseLeave={c.hover.onMouseLeave}\n >\n <button\n type=\"button\"\n className=\"etree-caret\"\n tabIndex={-1}\n aria-label={isOpen ? \"collapse\" : \"expand\"}\n aria-expanded={expandable ? isOpen : undefined}\n disabled={!expandable}\n onClick={(e) => {\n // The caret folds; it never selects the row.\n e.stopPropagation();\n if (expandable) onToggle();\n }}\n >\n {expandable && (\n <svg width=\"10\" height=\"10\" viewBox=\"0 0 10 10\" aria-hidden=\"true\" focusable=\"false\">\n <path d=\"M3.5 2l3 3-3 3\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.4\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\n </svg>\n )}\n </button>\n <span className=\"etree-icon\">{icon}</span>\n <span className=\"etree-name\">{name}</span>\n {marks}\n {count}\n </div>\n {c.card}\n {isOpen && children !== undefined && (\n <ul className=\"etree-children\" role=\"group\">\n {children}\n </ul>\n )}\n </li>\n );\n}\n\n// treeKeyDown is the tree's keyboard handler, attached to the role=\"tree\"\n// list. It works on the rendered rows (a collapsed row's children are not in\n// the DOM), and acts through the row's own click targets, so both trees get\n// the same keys without passing their state in: up / down move, right opens or\n// steps into the first child, left closes or steps to the parent, Home / End\n// jump, Enter / Space select, and a letter jumps to the next row whose name\n// starts with it.\nexport function treeKeyDown(e: KeyboardEvent<HTMLElement>) {\n // Only a focused row navigates: a key on a control inside the tree (a \"load\n // more\" or \"retry\" button) keeps its own meaning.\n const item = e.target as HTMLElement;\n if (item.getAttribute(\"role\") !== \"treeitem\" || !e.currentTarget.contains(item)) return;\n const items = Array.from(e.currentTarget.querySelectorAll<HTMLElement>('[role=\"treeitem\"]'));\n const at = items.indexOf(item);\n const row = item.querySelector<HTMLElement>(\":scope > .etree-row\");\n const caret = row?.querySelector<HTMLButtonElement>(\":scope > .etree-caret\");\n const expanded = item.getAttribute(\"aria-expanded\");\n // Focus only: the tab stop stays the one the tree rendered (the selected\n // row), so writing tabIndex here would leave the DOM out of step with React.\n const move = (to: HTMLElement | undefined | null) => to?.focus();\n switch (e.key) {\n case \"ArrowDown\":\n move(items[at + 1]);\n break;\n case \"ArrowUp\":\n move(items[at - 1]);\n break;\n case \"Home\":\n move(items[0]);\n break;\n case \"End\":\n move(items[items.length - 1]);\n break;\n case \"ArrowRight\":\n if (expanded === \"false\") caret?.click();\n else if (expanded === \"true\") move(item.querySelector<HTMLElement>(':scope > [role=\"group\"] > [role=\"treeitem\"]'));\n else return;\n break;\n case \"ArrowLeft\":\n if (expanded === \"true\") caret?.click();\n else move(item.parentElement?.closest<HTMLElement>('[role=\"treeitem\"]'));\n break;\n case \"Enter\":\n case \" \":\n row?.click();\n break;\n default: {\n if (e.key.length !== 1 || e.ctrlKey || e.metaKey || e.altKey) return;\n const ch = e.key.toLowerCase();\n const order = [...items.slice(at + 1), ...items.slice(0, at + 1)];\n move(\n order.find((el) =>\n el.querySelector(\":scope > .etree-row > .etree-name\")?.textContent?.trim().toLowerCase().startsWith(ch),\n ),\n );\n }\n }\n e.preventDefault();\n e.stopPropagation();\n}\n","import { useCallback, useContext, useEffect, useMemo, useState } from \"react\";\nimport type { ChunkRow } from \"../types\";\nimport { chunkRowTint, effectiveScheme, statusDotColor, type ColorScheme } from \"../lib/colorScheme\";\nimport { TreeIcon, TreeItem, TreeMarks, treeKeyDown, type TreeIconKind } from \"./TreeRow\";\nimport { CardScopeContext, chunkCard } from \"./AnnotationCard\";\n\n// DocumentChunkTree renders a document's chunk hierarchy (RFC AK), built from\n// the flat query_chunks list by parent_id + position. A single expand Map owned\n// by the tree, default-expanded, click-to-select.\n\nexport interface ChunkNode {\n row: ChunkRow;\n children: ChunkNode[];\n}\n\n// buildChunkTree groups chunks into parent → children (position-ordered). A\n// chunk whose parent_id is absent or not in the set is a root (the document's\n// root chunk; defensively also any orphan).\nexport function buildChunkTree(chunks: ChunkRow[]): ChunkNode[] {\n const byId = new Map<string, ChunkNode>();\n chunks.forEach((c) => byId.set(c.id, { row: c, children: [] }));\n const roots: ChunkNode[] = [];\n chunks.forEach((c) => {\n const node = byId.get(c.id)!;\n if (c.parent_id && byId.has(c.parent_id)) byId.get(c.parent_id)!.children.push(node);\n else roots.push(node);\n });\n const sortRec = (nodes: ChunkNode[]) => {\n nodes.sort((a, b) => a.row.position - b.row.position);\n nodes.forEach((n) => sortRec(n.children));\n };\n sortRec(roots);\n return roots;\n}\n\n// typeIcon returns the icon for a media chunk type (RFC BO) so the tree\n// distinguishes image / diagram chunks at a glance; undefined for a plain text\n// chunk, whose icon cell stays empty (the cell keeps its width, so titles align).\nfunction typeIcon(type: string | undefined): TreeIconKind | undefined {\n if (type === \"image\") return \"image\";\n if (type === \"mermaid\") return \"diagram\";\n return undefined;\n}\n\n// findChunkNode locates a node by id within a chunk forest.\nexport function findChunkNode(nodes: ChunkNode[], id: string): ChunkNode | undefined {\n for (const n of nodes) {\n if (n.row.id === id) return n;\n const hit = findChunkNode(n.children, id);\n if (hit) return hit;\n }\n return undefined;\n}\n\nexport interface DocumentChunkTreeProps {\n tree: ChunkNode[];\n selectedId?: string;\n onSelect: (node: ChunkNode) => void;\n // RFC BN: when colorEnabled, chunk rows are tinted by status via `scheme`\n // (falls back to the default palette). Unset → neutral rows (prior behavior).\n colorEnabled?: boolean;\n scheme?: ColorScheme;\n // The document's own colour (docColor of its type + status). Its row at the\n // top of the tree wears it, and a chunk with no status colour of its own a\n // lighter wash of it (chunkRowTint). Unset → status colours only.\n documentColor?: string;\n // RFC BN P4: chunk ids that have at least one cross-reference edge — those\n // rows get a link mark. Unset → no marks.\n linkedIds?: Set<string>;\n // The document's own type and status (RFC GZ): a row marks its type or status\n // only where it differs from the document's, so a uniform document's outline\n // carries no marks at all. Unset → every row marks what it has.\n documentType?: string;\n documentStatus?: string;\n}\n\nexport default function DocumentChunkTree({\n tree,\n selectedId,\n onSelect,\n colorEnabled,\n scheme,\n documentColor,\n linkedIds,\n documentType,\n documentStatus,\n}: DocumentChunkTreeProps) {\n const [expanded, setExpanded] = useState<Map<string, boolean>>(() => new Map());\n const toggle = useCallback((id: string) => {\n setExpanded((prev) => {\n const next = new Map(prev);\n next.set(id, prev.get(id) === false ? true : false);\n return next;\n });\n }, []);\n\n // Auto-expand ancestors of the selection.\n useEffect(() => {\n if (!selectedId) return;\n const parents = ancestorIds(tree, selectedId);\n if (parents.length === 0) return;\n setExpanded((prev) => {\n let mutated = false;\n const next = new Map(prev);\n for (const id of parents) {\n if (next.get(id) === false) {\n next.set(id, true);\n mutated = true;\n }\n }\n return mutated ? next : prev;\n });\n }, [tree, selectedId]);\n\n // Resolve the palette once (null → no tinting) and thread it down.\n const tintScheme = colorEnabled ? effectiveScheme(scheme) : null;\n // Whether the chunk list carries the chunks' briefs (RFC HA with_summary):\n // once any row has one, a row without one has no annotation of its own, and\n // its card is not read for one.\n const briefsListed = useMemo(() => someRow(tree, (r) => r.summary !== undefined), [tree]);\n\n if (tree.length === 0) {\n return (\n <div className=\"empty\">\n <p>No chunks.</p>\n </div>\n );\n }\n // One tab stop: the selected row while it is drawn (every chunk above it\n // open), else the first row.\n const selectedDrawn =\n !!selectedId &&\n (tree.some((n) => n.row.id === selectedId) ||\n (() => {\n const parents = ancestorIds(tree, selectedId);\n return parents.length > 0 && parents.every((id) => expanded.get(id) !== false);\n })());\n const tabStop = selectedDrawn ? selectedId : tree[0].row.id;\n return (\n <ul className=\"etree chunk-tree\" role=\"tree\" aria-label=\"Chunk outline\" onKeyDown={treeKeyDown}>\n {tree.map((n) => (\n <ChunkTreeNode\n key={n.row.id}\n node={n}\n depth={0}\n tabStop={tabStop}\n expanded={expanded}\n toggle={toggle}\n selectedId={selectedId}\n onSelect={onSelect}\n tintScheme={tintScheme}\n documentColor={documentColor}\n isRoot\n linkedIds={linkedIds}\n documentType={documentType}\n documentStatus={documentStatus}\n briefsListed={briefsListed}\n />\n ))}\n </ul>\n );\n}\n\nfunction someRow(nodes: ChunkNode[], test: (r: ChunkRow) => boolean): boolean {\n return nodes.some((n) => test(n.row) || someRow(n.children, test));\n}\n\nfunction ancestorIds(roots: ChunkNode[], id: string): string[] {\n const path: string[] = [];\n const walk = (nodes: ChunkNode[], parents: string[]): boolean => {\n for (const n of nodes) {\n if (n.row.id === id) {\n path.push(...parents);\n return true;\n }\n if (walk(n.children, [...parents, n.row.id])) return true;\n }\n return false;\n };\n walk(roots, []);\n return path;\n}\n\ninterface NodeProps {\n node: ChunkNode;\n expanded: Map<string, boolean>;\n toggle: (id: string) => void;\n selectedId?: string;\n onSelect: (node: ChunkNode) => void;\n tintScheme: ColorScheme | null;\n documentColor?: string;\n // A top-level node: the document's root chunk, i.e. the document itself.\n isRoot?: boolean;\n linkedIds?: Set<string>;\n documentType?: string;\n documentStatus?: string;\n depth: number;\n // The id of the tree's one tab stop.\n tabStop?: string;\n briefsListed?: boolean;\n}\n\nfunction ChunkTreeNode({\n node,\n expanded,\n toggle,\n selectedId,\n onSelect,\n tintScheme,\n documentColor,\n isRoot = false,\n linkedIds,\n documentType,\n documentStatus,\n depth,\n tabStop,\n briefsListed,\n}: NodeProps) {\n const hasChildren = node.children.length > 0;\n const isOpen = expanded.get(node.row.id) !== false; // default-expanded\n const isSelected = selectedId === node.row.id;\n const icon = isRoot ? \"document\" : typeIcon(node.row.type);\n const type = node.row.type !== documentType ? node.row.type : undefined;\n const status = node.row.status !== documentStatus ? node.row.status : undefined;\n const cardScope = useContext(CardScopeContext);\n return (\n <TreeItem\n className=\"chunk-node\"\n depth={depth}\n expandable={hasChildren}\n expanded={isOpen}\n onToggle={() => toggle(node.row.id)}\n selected={isSelected}\n onSelect={() => onSelect(node)}\n tabbable={node.row.id === tabStop}\n icon={icon ? <TreeIcon kind={icon} /> : undefined}\n name={node.row.title || \"(untitled)\"}\n card={chunkCard(node.row, cardScope, briefsListed)}\n marks={\n <TreeMarks\n bare\n type={type}\n status={status}\n statusColor={statusDotColor(status, tintScheme ?? undefined)}\n extra={\n linkedIds?.has(node.row.id) ? (\n <span className=\"etree-mark etree-mark-link\" role=\"img\" aria-label=\"linked\">\n <TreeIcon kind=\"link\" />\n </span>\n ) : undefined\n }\n />\n }\n style={chunkRowTint({ status: node.row.status, isRoot, documentColor, scheme: tintScheme })}\n >\n {hasChildren\n ? node.children.map((c) => (\n <ChunkTreeNode\n key={c.row.id}\n node={c}\n expanded={expanded}\n toggle={toggle}\n selectedId={selectedId}\n onSelect={onSelect}\n tintScheme={tintScheme}\n documentColor={documentColor}\n linkedIds={linkedIds}\n documentType={documentType}\n documentStatus={documentStatus}\n depth={depth + 1}\n tabStop={tabStop}\n briefsListed={briefsListed}\n />\n ))\n : undefined}\n </TreeItem>\n );\n}\n","import { useState } from \"react\";\nimport type { Annotation, AnnotationLevel } from \"../types\";\nimport {\n ABSTRACT_MAX_CHARS,\n BRIEF_MAX_CHARS,\n annotationDraftProblem,\n codePoints,\n writtenAtLabel,\n writtenByLabel,\n} from \"../lib/annotation\";\n\n// AnnotationBrief is the one-line brief shown under a title. A stale record is\n// still shown, with a muted marker, so the reader can weigh it.\nexport function AnnotationBrief({ record }: { record?: Annotation }) {\n if (!record) return null;\n return (\n <p className=\"annotation-brief\" title=\"Annotation brief\">\n {record.brief}\n {record.stale && <StaleBadge />}\n </p>\n );\n}\n\nfunction StaleBadge() {\n return (\n <span\n className=\"annotation-badge annotation-stale\"\n title=\"The text has changed since this annotation was written\"\n >\n stale\n </span>\n );\n}\n\nexport interface AnnotationPanelProps {\n // The records of one chunk, ordered branch → document → path. Empty → the\n // panel draws only for a reader who can write or regenerate one.\n records: Annotation[];\n // newLevel is the level a hand-written annotation takes when there is none.\n newLevel: AnnotationLevel;\n // onSave writes an edit (always as a manual record); absent → no Edit.\n onSave?: (level: AnnotationLevel, brief: string, abstract: string) => Promise<void>;\n // onRegenerate asks the host to have the annotation rewritten; absent → no\n // Regenerate.\n onRegenerate?: (level: AnnotationLevel) => Promise<void>;\n // Starts expanded (tests and a host that wants the abstract open).\n defaultOpen?: boolean;\n}\n\n// AnnotationPanel shows a chunk's abstract and its provenance — level, language,\n// model, when and by whom it was written, whether a person wrote it, whether it\n// is stale — collapsed under one summary line. The abstract is rendered as plain\n// text: it is model output, never markup.\nexport default function AnnotationPanel({\n records,\n newLevel,\n onSave,\n onRegenerate,\n defaultOpen,\n}: AnnotationPanelProps) {\n const [open, setOpen] = useState(!!defaultOpen);\n const [editing, setEditing] = useState<AnnotationLevel | null>(null);\n // The record being regenerated: every button waits, only its own says so.\n const [busyLevel, setBusyLevel] = useState<AnnotationLevel | null>(null);\n const busy = busyLevel !== null;\n const [err, setErr] = useState<string | null>(null);\n\n if (records.length === 0 && !onSave && !onRegenerate) return null;\n\n const regenerate = async (level: AnnotationLevel) => {\n if (!onRegenerate) return;\n setBusyLevel(level);\n setErr(null);\n try {\n await onRegenerate(level);\n } catch (e) {\n setErr(e instanceof Error ? e.message : String(e));\n } finally {\n setBusyLevel(null);\n }\n };\n\n const anyStale = records.some((r) => r.stale);\n const anyManual = records.some((r) => r.manual);\n\n return (\n <details\n className=\"annotation-panel\"\n open={open || editing !== null}\n onToggle={(e) => setOpen(e.currentTarget.open)}\n >\n <summary>\n <span className=\"annotation-title\">Annotation</span>\n {records.length === 0 ? (\n <span className=\"annotation-none\">none</span>\n ) : (\n records.map((r) => (\n <span className=\"annotation-badge\" key={r.level}>\n {r.level}\n </span>\n ))\n )}\n {anyManual && (\n <span className=\"annotation-badge annotation-manual\" title=\"Written or edited by a person\">\n manual\n </span>\n )}\n {anyStale && <StaleBadge />}\n </summary>\n {records.map((r) =>\n editing === r.level ? (\n <AnnotationEditor\n key={r.level}\n level={r.level}\n brief={r.brief}\n abstract={r.abstract}\n onCancel={() => setEditing(null)}\n onSave={async (b, a) => {\n await onSave!(r.level, b, a);\n setEditing(null);\n }}\n />\n ) : (\n <div className=\"annotation-record\" key={r.level}>\n {records.length > 1 && <p className=\"annotation-brief\">{r.brief}</p>}\n {r.abstract && <p className=\"annotation-abstract\">{r.abstract}</p>}\n <dl className=\"annotation-meta\">\n <dt>level</dt>\n <dd>{r.level}</dd>\n {r.language && (\n <>\n <dt>language</dt>\n <dd>{r.language}</dd>\n </>\n )}\n {r.model && (\n <>\n <dt>model</dt>\n <dd>{r.model}</dd>\n </>\n )}\n {r.written_at && (\n <>\n <dt>written</dt>\n <dd title={r.written_at}>{writtenAtLabel(r.written_at)}</dd>\n </>\n )}\n {r.written_by && (\n <>\n <dt>by</dt>\n <dd>{writtenByLabel(r.written_by)}</dd>\n </>\n )}\n {r.manual && (\n <>\n <dt>source</dt>\n <dd>written by hand</dd>\n </>\n )}\n {r.stale && (\n <>\n <dt>state</dt>\n <dd>stale: the text changed after this was written</dd>\n </>\n )}\n </dl>\n {(onSave || onRegenerate) && (\n <div className=\"annotation-actions\">\n {onSave && (\n <button type=\"button\" disabled={busy} onClick={() => setEditing(r.level)}>\n edit\n </button>\n )}\n {/* The annotation pass never rewrites a person's text, so a\n Regenerate of one would change nothing: edit it instead. */}\n {onRegenerate && !r.manual && (\n <button\n type=\"button\"\n disabled={busy}\n onClick={() => void regenerate(r.level)}\n title=\"Ask for it to be written again from the current text\"\n >\n {busyLevel === r.level ? \"regenerating…\" : \"regenerate\"}\n </button>\n )}\n </div>\n )}\n </div>\n ),\n )}\n {records.length === 0 &&\n (editing !== null && onSave ? (\n <AnnotationEditor\n level={editing}\n brief=\"\"\n abstract=\"\"\n onCancel={() => setEditing(null)}\n onSave={async (b, a) => {\n await onSave(editing, b, a);\n setEditing(null);\n }}\n />\n ) : (\n <div className=\"annotation-record\">\n <p className=\"annotation-empty\">No annotation has been written for this yet.</p>\n <div className=\"annotation-actions\">\n {onSave && (\n <button type=\"button\" disabled={busy} onClick={() => setEditing(newLevel)}>\n write\n </button>\n )}\n {onRegenerate && (\n <button type=\"button\" disabled={busy} onClick={() => void regenerate(newLevel)}>\n {busy ? \"generating…\" : \"generate\"}\n </button>\n )}\n </div>\n </div>\n ))}\n {err && <p className=\"annotation-err\">{err}</p>}\n </details>\n );\n}\n\n// AnnotationEditor is the inline brief + abstract form. It checks the length\n// caps before sending; a refusal from the runtime is shown under the form.\nfunction AnnotationEditor({\n level,\n brief: initialBrief,\n abstract: initialAbstract,\n onSave,\n onCancel,\n}: {\n level: AnnotationLevel;\n brief: string;\n abstract: string;\n onSave: (brief: string, abstract: string) => Promise<void>;\n onCancel: () => void;\n}) {\n const [brief, setBrief] = useState(initialBrief);\n const [abstract, setAbstract] = useState(initialAbstract);\n const [saving, setSaving] = useState(false);\n const [err, setErr] = useState<string | null>(null);\n const problem = annotationDraftProblem(brief, abstract);\n\n const save = async () => {\n if (problem) {\n setErr(problem);\n return;\n }\n setSaving(true);\n setErr(null);\n try {\n await onSave(brief, abstract);\n } catch (e) {\n setErr(e instanceof Error ? e.message : String(e));\n } finally {\n setSaving(false);\n }\n };\n\n return (\n <form\n className=\"annotation-editor\"\n onSubmit={(e) => {\n e.preventDefault();\n void save();\n }}\n >\n <label>\n <span>\n Brief ({level}) · {codePoints(brief)}/{BRIEF_MAX_CHARS}\n </span>\n <input value={brief} onChange={(e) => setBrief(e.target.value)} placeholder=\"One sentence\" />\n </label>\n <label>\n <span>\n Abstract · {codePoints(abstract)}/{ABSTRACT_MAX_CHARS}\n </span>\n <textarea\n rows={6}\n value={abstract}\n onChange={(e) => setAbstract(e.target.value)}\n placeholder=\"One paragraph\"\n />\n </label>\n <p className=\"annotation-hint\">Saved as written by hand: the background walk will not replace it.</p>\n {err && <p className=\"annotation-err\">{err}</p>}\n <div className=\"annotation-actions\">\n <button type=\"button\" onClick={onCancel} disabled={saving}>\n cancel\n </button>\n <button type=\"submit\" className=\"primary\" disabled={saving || !!problem}>\n {saving ? \"saving…\" : \"save\"}\n </button>\n </div>\n </form>\n );\n}\n","import { useEffect, useRef, useState, type ReactNode } from \"react\";\n\n// MermaidDiagram lazily renders a Mermaid definition to SVG. Theme is read from\n// the nearest [data-theme] ancestor (the explorer root / host <html>), defaulting\n// to the explorer's dark palette. It renders with securityLevel:\"strict\" (bundled\n// DOMPurify) — the same posture as the runtime's TeamsView diagram. mermaid is an\n// OPTIONAL peer dep, so a host without it (or a definition that fails to parse)\n// degrades gracefully to the raw code, and a bad diagram never breaks the view.\n// Shared by the Markdown ```mermaid fence (RFC BN P2) and the cross-reference\n// relationship graph (P4).\n\n// mermaidSeq gives each render a unique DOM id (mermaid.render requires one).\n// A module counter is fine in the browser (this never runs in the workflow JS\n// sandbox where Math.random / new Date are disallowed).\nlet mermaidSeq = 0;\n\n// flowchartNode finds the flowchart node a click landed in and returns the id it\n// was DECLARED with. Mermaid wraps that id in its own (`flowchart-<id>-<n>`,\n// behind the render id in newer versions), so it is matched from the right. A\n// click outside any node — or a diagram that is not a flowchart — is undefined.\nexport function flowchartNode(target: Element | null): string | undefined {\n const node = target?.closest(\"g.node\");\n return node ? /flowchart-(.+)-\\d+$/.exec(node.id)?.[1] : undefined;\n}\n\nexport default function MermaidDiagram({\n code,\n onNodeClick,\n}: {\n code: string;\n // Called with a flowchart node's declared id when it is clicked. Makes the\n // nodes read as clickable; omit for a diagram that is only a picture.\n onNodeClick?: (nodeId: string) => void;\n}): ReactNode {\n const ref = useRef<HTMLDivElement>(null);\n const [state, setState] = useState<{ svg?: string; err?: boolean }>({});\n\n useEffect(() => {\n let cancelled = false;\n (async () => {\n try {\n const mermaid = (await import(\"mermaid\")).default;\n const attr = ref.current?.closest(\"[data-theme]\")?.getAttribute(\"data-theme\");\n const dark = attr ? attr === \"dark\" : true; // explorer default is dark\n mermaid.initialize({ startOnLoad: false, theme: dark ? \"dark\" : \"default\", securityLevel: \"strict\" });\n const { svg } = await mermaid.render(`lc-mmd-${mermaidSeq++}`, code);\n if (!cancelled) setState({ svg });\n } catch {\n if (!cancelled) setState({ err: true });\n }\n })();\n return () => {\n cancelled = true;\n };\n }, [code]);\n\n if (state.err) {\n // No ref here: the effect already captured the theme on the first (loading)\n // render, and a <pre> ref would conflict with the <div> ref type below.\n return (\n <pre className=\"md-pre md-mermaid-error\" title=\"diagram failed to render\">\n <code>{code}</code>\n </pre>\n );\n }\n if (state.svg) {\n return (\n <div\n ref={ref}\n className={onNodeClick ? \"md-mermaid md-mermaid-nav\" : \"md-mermaid\"}\n onClick={\n onNodeClick &&\n ((e) => {\n const id = flowchartNode(e.target as Element);\n if (id) onNodeClick(id);\n })\n }\n dangerouslySetInnerHTML={{ __html: state.svg }}\n />\n );\n }\n return (\n <div ref={ref} className=\"md-mermaid md-mermaid-loading\">\n rendering diagram…\n </div>\n );\n}\n","import { lazy, Suspense, useEffect, useMemo, useState, type FormEvent } from \"react\";\nimport type { EditorDiagnostic, EditorLanguage, ParseResult } from \"@loomcycle/code-editor\";\nimport \"@loomcycle/code-editor/styles.css\";\nimport type { BrowseScope, ChunkDetail, DocScope } from \"../types\";\nimport { useExplorerData } from \"../lib/dataLayer\";\nimport MermaidDiagram from \"./Mermaid\";\nimport { readImageAsBase64 } from \"../lib/imageUpload\";\n\n// The shared code editor (RFC FW), loaded when a chunk is first edited: the\n// reading view never fetches it. CodeEditor draws a plain textarea over the same\n// text until CodeMirror itself has loaded, so the dialog is never blank.\nconst CodeEditor = lazy(() => import(\"@loomcycle/code-editor\").then((m) => ({ default: m.CodeEditor })));\nlet parseJsonLoad: Promise<(text: string) => ParseResult> | null = null;\nfunction loadParseJson() {\n parseJsonLoad ??= import(\"@loomcycle/code-editor\").then((m) => m.parseJson);\n parseJsonLoad.catch(() => {\n parseJsonLoad = null;\n });\n return parseJsonLoad;\n}\n\n// ChunkEditorModal edits one chunk's content — title, type, status, tags, the\n// Markdown body, and (optional) typed fields as JSON. The body and the fields\n// are edited in the shared code editor: the body in its markdown mode with soft\n// wrap (a Mermaid chunk's source in text mode, beside its live preview), the\n// fields in json mode with the parse error marked where it is. Save is an\n// optimistic-concurrency update_chunk carrying the chunk's revision; a stale\n// revision returns a \"revision conflict\" the modal surfaces with a reload hint.\n// Structural edits (reparent / reorder / link / delete) are NOT here.\nexport interface ChunkEditorModalProps {\n chunk: ChunkDetail;\n scope: DocScope;\n // browse (RFC AS) — edit a chunk under the browsed subject's document, not\n // necessarily the caller's own (server re-authorizes). Unset → own subject.\n browse?: BrowseScope;\n onClose: () => void;\n onSaved: (updated: ChunkDetail) => void;\n}\n\nexport default function ChunkEditorModal({ chunk, scope, browse, onClose, onSaved }: ChunkEditorModalProps) {\n const data = useExplorerData();\n const [title, setTitle] = useState(chunk.title);\n const [type, setType] = useState(chunk.type ?? \"\");\n const [status, setStatus] = useState(chunk.status ?? \"\");\n const [body, setBody] = useState(chunk.body ?? \"\");\n const [fieldsText, setFieldsText] = useState(\n chunk.fields ? JSON.stringify(chunk.fields, null, 2) : \"\",\n );\n // Tags (RFC BS) edit as a comma-separated list; the editor is authoritative, so\n // save always replace-sets to this value (empty clears). Nested tags use a slash.\n const [tagsText, setTagsText] = useState((chunk.tags ?? []).join(\", \"));\n const [busy, setBusy] = useState(false);\n const [err, setErr] = useState<string | null>(null);\n const [conflict, setConflict] = useState(false);\n\n const isMermaid = type === \"mermaid\";\n const isImage = type === \"image\" || !!chunk.asset;\n const bodyLanguage: EditorLanguage = isMermaid || isImage ? \"text\" : \"markdown\";\n\n // RFC BO — a debounced copy of the body drives the live Mermaid preview so it\n // re-renders as the author edits the source, but not on every keystroke.\n const [preview, setPreview] = useState(body);\n useEffect(() => {\n if (!isMermaid) return;\n const t = setTimeout(() => setPreview(body), 400);\n return () => clearTimeout(t);\n }, [body, isMermaid]);\n\n // The fields' parse error, marked in the editor and blocking save. Any JSON\n // value is accepted (as JSON.parse takes it); the editor's own parser is asked\n // only where it fails, for the place and a clearer message.\n const [parseJson, setParseJson] = useState<((text: string) => ParseResult) | null>(null);\n useEffect(() => {\n let cancelled = false;\n loadParseJson()\n .then((fn) => !cancelled && setParseJson(() => fn))\n .catch(() => {});\n return () => {\n cancelled = true;\n };\n }, []);\n const fieldsError = useMemo<EditorDiagnostic | null>(() => {\n if (fieldsText.trim() === \"\") return null;\n try {\n JSON.parse(fieldsText);\n return null;\n } catch (e) {\n const r = parseJson?.(fieldsText);\n if (r && !r.ok) return { from: r.error.offset, to: r.error.to, severity: \"error\", message: r.error.message };\n return { from: 0, to: 0, severity: \"error\", message: e instanceof Error ? e.message : String(e) };\n }\n }, [fieldsText, parseJson]);\n const fieldsDiagnostics = useMemo(() => (fieldsError ? [fieldsError] : []), [fieldsError]);\n\n // RFC BO — replace an image chunk's bytes in place (set_asset bumps the\n // revision, so we hand the updated chunk back and close rather than risk a\n // stale-revision save afterward).\n const replaceImage = async (file: File) => {\n setErr(null);\n setBusy(true);\n try {\n const { mediaType, data: b64 } = await readImageAsBase64(file);\n const updated = await data.documentSetAsset(chunk.id, mediaType, b64, file.name, scope, browse);\n onSaved(updated);\n onClose();\n } catch (ex) {\n setErr(ex instanceof Error ? ex.message : String(ex));\n setBusy(false);\n }\n };\n\n const bodyLabel = isMermaid ? \"Mermaid source\" : isImage ? \"Caption (optional)\" : \"Body (Markdown)\";\n\n const submit = async (e: FormEvent) => {\n e.preventDefault();\n setErr(null);\n setConflict(false);\n if (fieldsError) {\n setErr(`fields must be valid JSON: ${fieldsError.message}`);\n return;\n }\n const patch: { body: string; title: string; type: string; status: string; tags: string[]; fields?: unknown } = {\n body,\n title,\n type,\n status,\n // Parse the comma-separated list; replace-set is intentional (the box shows\n // the chunk's tags, so saving makes it exactly what's in the box).\n tags: tagsText.split(\",\").map((t) => t.trim()).filter((t) => t !== \"\"),\n };\n // Send fields only when non-empty (a blank box leaves fields untouched\n // rather than clobbering them).\n if (fieldsText.trim() !== \"\") patch.fields = JSON.parse(fieldsText);\n setBusy(true);\n try {\n const updated = await data.documentUpdateChunk(chunk.id, chunk.revision, patch, scope, browse);\n onSaved(updated);\n onClose();\n } catch (ex) {\n const msg = ex instanceof Error ? ex.message : String(ex);\n setErr(msg);\n setConflict(/revision conflict/i.test(msg));\n setBusy(false);\n }\n };\n\n return (\n <div className=\"modal-overlay\" onClick={onClose}>\n <form className=\"modal chunk-editor\" onClick={(e) => e.stopPropagation()} onSubmit={submit}>\n {/* RFC BN P1: Save/Cancel pinned to the top so a long chunk body never\n needs scrolling to reach the save button. */}\n <div className=\"modal-header sticky-top\">\n <h3>Edit chunk</h3>\n <div className=\"modal-buttons modal-buttons-top\">\n <button type=\"button\" onClick={onClose} disabled={busy}>\n cancel\n </button>\n <button type=\"submit\" className=\"primary\" disabled={busy || !!fieldsError}>\n {busy ? \"saving…\" : \"save\"}\n </button>\n </div>\n </div>\n {err && (\n <div className=\"modal-err\">\n {err}\n {conflict && \" — reopen the chunk to load the latest, then reapply your edit.\"}\n </div>\n )}\n <label className=\"path-field\">\n <span>Title</span>\n <input className=\"path-modal-input\" value={title} onChange={(e) => setTitle(e.target.value)} />\n </label>\n <div className=\"chunk-editor-row\">\n <label className=\"path-field\">\n <span>Type</span>\n <input\n className=\"path-modal-input\"\n value={type}\n placeholder=\"(none)\"\n onChange={(e) => setType(e.target.value)}\n />\n </label>\n <label className=\"path-field\">\n <span>Status</span>\n <input\n className=\"path-modal-input\"\n value={status}\n placeholder=\"(none)\"\n onChange={(e) => setStatus(e.target.value)}\n />\n </label>\n <label className=\"path-field\">\n <span>Tags</span>\n <input\n className=\"path-modal-input\"\n value={tagsText}\n placeholder=\"area/sub, priority/high\"\n title=\"Comma-separated; nest with a slash: area/sub, priority/high\"\n onChange={(e) => setTagsText(e.target.value)}\n />\n </label>\n </div>\n {isImage && (\n <label className=\"path-field\">\n <span>Replace image</span>\n <input\n type=\"file\"\n accept=\"image/png,image/jpeg,image/gif,image/webp\"\n disabled={busy}\n onChange={(e) => {\n const f = e.target.files?.[0];\n if (f) void replaceImage(f);\n }}\n />\n </label>\n )}\n <div className={`chunk-editor-main${isMermaid ? \" with-preview\" : \"\"}`}>\n <div className=\"path-field chunk-editor-body\">\n <span>{bodyLabel}</span>\n <Suspense fallback={<textarea className=\"modal-textarea\" value={body} readOnly aria-label={bodyLabel} />}>\n <CodeEditor\n value={body}\n onChange={setBody}\n language={bodyLanguage}\n wrap\n ariaLabel={bodyLabel}\n className=\"chunk-body-input\"\n />\n </Suspense>\n </div>\n {isMermaid && (\n <div className=\"path-field chunk-editor-preview\">\n <span>Preview</span>\n <div className=\"chunk-mermaid-preview\">\n {preview.trim() ? (\n <MermaidDiagram code={preview} />\n ) : (\n <p className=\"doc-empty-body\">(enter Mermaid source)</p>\n )}\n </div>\n </div>\n )}\n </div>\n <div className=\"path-field chunk-editor-fields\">\n <span>Fields (JSON, optional)</span>\n <Suspense\n fallback={<textarea className=\"modal-textarea\" value={fieldsText} readOnly aria-label=\"Fields (JSON)\" />}\n >\n <CodeEditor\n value={fieldsText}\n onChange={setFieldsText}\n language=\"json\"\n diagnostics={fieldsDiagnostics}\n ariaLabel=\"Fields (JSON)\"\n placeholder=\"{}\"\n className=\"chunk-fields-input\"\n />\n </Suspense>\n {fieldsError && <span className=\"chunk-fields-error\">{fieldsError.message}</span>}\n </div>\n </form>\n </div>\n );\n}\n","import { useEffect, useState, type FormEvent } from \"react\";\nimport type { BrowseScope, ChunkDetail, DocScope } from \"../types\";\nimport { useExplorerData } from \"../lib/dataLayer\";\nimport { subjectTypeChoices } from \"../lib/subjectType\";\n\n// SubjectTypeModal changes the kind of a subject: the type of its document's root\n// chunk, picked from the entity types in force. It is an update_chunk like any other\n// edit; the runtime tells subscribers the subject was re-typed, so relations whose\n// kind no longer fits get re-checked. The subject's natural key does not change.\nexport interface SubjectTypeModalProps {\n chunk: ChunkDetail;\n scope: DocScope;\n browse?: BrowseScope;\n onClose: () => void;\n onSaved: (updated: ChunkDetail) => void;\n}\n\nexport default function SubjectTypeModal({ chunk, scope, browse, onClose, onSaved }: SubjectTypeModalProps) {\n const data = useExplorerData();\n const [inForce, setInForce] = useState<string[] | null>(null);\n const [choice, setChoice] = useState(chunk.type ?? \"\");\n const [busy, setBusy] = useState(false);\n const [err, setErr] = useState<string | null>(null);\n // Set when the type was changed but the runtime withheld the announcement.\n const [notice, setNotice] = useState<string | null>(null);\n\n useEffect(() => {\n let cancelled = false;\n data\n .documentEntityTypes?.(scope, browse)\n .then((types) => {\n if (!cancelled) setInForce(types);\n })\n .catch((e) => {\n if (!cancelled) setErr(e instanceof Error ? e.message : String(e));\n });\n return () => {\n cancelled = true;\n };\n }, [data, scope, browse]);\n\n const choices = inForce ? subjectTypeChoices(inForce, chunk.type) : [];\n const unchanged = choice.toLowerCase() === (chunk.type ?? \"\").toLowerCase();\n\n const submit = async (e: FormEvent) => {\n e.preventDefault();\n if (unchanged || busy) return;\n setErr(null);\n setBusy(true);\n try {\n const updated = await data.documentUpdateChunk(chunk.id, chunk.revision, { type: choice }, scope, browse);\n onSaved(updated);\n if (updated.not_announced) {\n setNotice(updated.not_announced);\n setBusy(false);\n return;\n }\n onClose();\n } catch (ex) {\n setErr(ex instanceof Error ? ex.message : String(ex));\n setBusy(false);\n }\n };\n\n return (\n <div className=\"modal-overlay\" onClick={onClose}>\n <form className=\"modal\" onClick={(e) => e.stopPropagation()} onSubmit={submit}>\n <h3>Change type</h3>\n <p className=\"modal-context\">\n “{chunk.title || \"(untitled)\"}” is a subject (<code>{chunk.entity?.natural_key}</code>). Its key\n stays as it is; relations about it are re-checked against the new type.\n </p>\n {err && <div className=\"modal-err\">{err}</div>}\n {notice ? (\n <div className=\"modal-err\">The type was changed, but subscribers were not told: {notice}</div>\n ) : (\n <label className=\"path-field\">\n <span>Type</span>\n {inForce === null ? (\n <span className=\"doc-empty-body\">{err ? \"\" : \"loading types…\"}</span>\n ) : (\n <select\n className=\"path-modal-input\"\n value={choice}\n disabled={busy}\n onChange={(e) => setChoice(e.target.value)}\n >\n {choices.map((t) => (\n <option key={t} value={t}>\n {t}\n </option>\n ))}\n </select>\n )}\n </label>\n )}\n <div className=\"modal-buttons\">\n <button type=\"button\" onClick={onClose} disabled={busy}>\n {notice ? \"close\" : \"cancel\"}\n </button>\n {!notice && (\n <button type=\"submit\" className=\"primary\" disabled={busy || unchanged || inForce === null}>\n {busy ? \"saving…\" : \"change type\"}\n </button>\n )}\n </div>\n </form>\n </div>\n );\n}\n","import { useEffect, useMemo, useState } from \"react\";\nimport type { AcceptClassificationAnswer, BrowseScope, ClassifyAnswer, DocScope } from \"../types\";\nimport { useExplorerData } from \"../lib/dataLayer\";\nimport {\n acceptSummary,\n canApply,\n classDisposition,\n classifyErrorText,\n formatShare,\n pendingClassification,\n resultLabel,\n summarizeStep,\n} from \"../lib/classify\";\n\n// Classification is the RFC FO classification surface of the document viewer,\n// rendered between the toolbar and the chunk split:\n// - the Classify panel — opened from the toolbar, it first runs classify with\n// write=report (nothing written) and shows the answer; Apply then runs it\n// with write=propose and reloads the document.\n// - a Pending block whenever the root chunk's classification record waits for\n// an operator, with Accept (accept_classification).\n// Every answer string (quotes, class and concept names, warnings) is rendered as\n// a plain text node — never Markdown or HTML. Refusals show inline.\n//\n// The host keys this component by document, so its state never outlives one.\nexport interface ClassificationProps {\n documentId: string;\n scope: DocScope;\n browse?: BrowseScope;\n // The root chunk's fields (undefined until loaded) — the pending record's source.\n rootFields: unknown;\n // Non-zero while the panel is open; each change to a non-zero value (the\n // toolbar's Classify toggle) runs a fresh report. 0 = closed.\n requestKey: number;\n onClose: () => void;\n // Reloads the document after a write (Apply / Accept).\n onChanged: () => void;\n}\n\nexport default function Classification({\n documentId,\n scope,\n browse,\n rootFields,\n requestKey,\n onClose,\n onChanged,\n}: ClassificationProps) {\n const data = useExplorerData();\n const [answer, setAnswer] = useState<ClassifyAnswer | null>(null);\n const [busy, setBusy] = useState(false);\n const [err, setErr] = useState<string | null>(null);\n const [accepting, setAccepting] = useState(false);\n const [acceptErr, setAcceptErr] = useState<string | null>(null);\n const [accepted, setAccepted] = useState<AcceptClassificationAnswer | null>(null);\n\n const pending = useMemo(\n () => (data.documentAcceptClassification ? pendingClassification(rootFields) : undefined),\n [data, rootFields],\n );\n\n // Each opening runs a report — nothing is written until Apply.\n useEffect(() => {\n if (requestKey === 0 || !data.documentClassify) return;\n let cancelled = false;\n setBusy(true);\n setErr(null);\n setAnswer(null);\n data\n .documentClassify(documentId, \"report\", scope, browse)\n .then((a) => !cancelled && setAnswer(a))\n .catch((e) => !cancelled && setErr(classifyErrorText(e)))\n .finally(() => !cancelled && setBusy(false));\n return () => {\n cancelled = true;\n };\n }, [data, documentId, scope, browse, requestKey]);\n\n const apply = async () => {\n if (!data.documentClassify) return;\n setBusy(true);\n setErr(null);\n try {\n setAnswer(await data.documentClassify(documentId, \"propose\", scope, browse));\n onChanged();\n } catch (e) {\n setErr(classifyErrorText(e));\n } finally {\n setBusy(false);\n }\n };\n\n const accept = async () => {\n if (!data.documentAcceptClassification) return;\n setAccepting(true);\n setAcceptErr(null);\n try {\n setAccepted(await data.documentAcceptClassification(documentId, scope, browse));\n onChanged();\n } catch (e) {\n setAcceptErr(classifyErrorText(e));\n } finally {\n setAccepting(false);\n }\n };\n\n const open = requestKey > 0;\n if (!open && !pending && !accepted && !acceptErr) return null;\n const acceptedSummary = accepted ? acceptSummary(accepted) : undefined;\n\n return (\n <div className=\"doc-classify\">\n {pending && (\n <div className=\"doc-classify-pending\">\n <span className=\"doc-classify-label\">Pending classification</span>\n {pending.proposedType && (\n <span>\n class <strong>{pending.proposedType}</strong>\n </span>\n )}\n {pending.proposedTags.length > 0 && (\n <span>\n tags{\" \"}\n {pending.proposedTags.map((t) => (\n <span className=\"chunk-tag\" key={t}>\n {t}\n </span>\n ))}\n </span>\n )}\n {pending.statementCount > 0 && (\n <span>\n {pending.statementCount} proposed statement{pending.statementCount === 1 ? \"\" : \"s\"}\n </span>\n )}\n <button type=\"button\" disabled={accepting} onClick={() => void accept()}>\n {accepting ? \"Accepting…\" : \"Accept\"}\n </button>\n </div>\n )}\n {acceptErr && (\n <div className=\"doc-classify-err\" role=\"alert\">\n {acceptErr}\n <button type=\"button\" className=\"doc-classify-dismiss\" onClick={() => setAcceptErr(null)} aria-label=\"Dismiss\">\n ×\n </button>\n </div>\n )}\n {acceptedSummary && (\n <div className=\"doc-classify-notice\" role=\"status\">\n <span>{acceptedSummary.applied}</span>\n {acceptedSummary.notices.map((n, i) => (\n <span className=\"doc-classify-warn\" key={i}>\n {n}\n </span>\n ))}\n <button type=\"button\" className=\"doc-classify-dismiss\" onClick={() => setAccepted(null)} aria-label=\"Dismiss\">\n ×\n </button>\n </div>\n )}\n {open && (\n <div className=\"doc-classify-panel\">\n <div className=\"doc-classify-head\">\n <h4>Classify</h4>\n {answer && <span className={`doc-classify-result ${answer.result}`}>{resultLabel(answer)}</span>}\n {answer?.write === \"report\" && <span className=\"doc-classify-hint\">report only — nothing written</span>}\n <button type=\"button\" className=\"doc-classify-dismiss\" onClick={onClose} aria-label=\"Close\">\n ×\n </button>\n </div>\n {!answer && !err && <p className=\"doc-classify-hint\">Classifying…</p>}\n {err && (\n <p className=\"doc-classify-err\" role=\"alert\">\n {err}\n </p>\n )}\n {answer && <ClassifyAnswerView answer={answer} />}\n {answer && canApply(answer) && (\n <div className=\"doc-classify-actions\">\n <button\n type=\"button\"\n disabled={busy}\n onClick={() => void apply()}\n title=\"Apply a unique rule match to the document; file everything else for review\"\n >\n {busy ? \"Applying…\" : \"Apply\"}\n </button>\n </div>\n )}\n </div>\n )}\n </div>\n );\n}\n\nexport function ClassifyAnswerView({ answer }: { answer: ClassifyAnswer }) {\n const disposition = classDisposition(answer);\n const fields = Object.entries(answer.fields ?? {});\n const issuers = answer.issued_by ?? [];\n const concepts = answer.concepts ?? [];\n const steps = (answer.steps ?? []).map(summarizeStep);\n const written = answer.statements?.length ?? 0;\n return (\n <>\n <dl className=\"doc-classify-rows\">\n {answer.class && (\n <>\n <dt>class</dt>\n <dd>\n <strong>{answer.class}</strong>\n {disposition && <span className=\"doc-classify-hint\"> ({disposition})</span>}\n </dd>\n </>\n )}\n {answer.work_key && (\n <>\n <dt>work key</dt>\n <dd className=\"doc-classify-mono\">{answer.work_key}</dd>\n </>\n )}\n {fields.length > 0 && (\n <>\n <dt>fields</dt>\n <dd className=\"doc-classify-mono\">\n {fields.map(([k, v]) => `${k}=${typeof v === \"string\" ? v : JSON.stringify(v)}`).join(\" · \")}\n </dd>\n </>\n )}\n {issuers.length > 0 && (\n <>\n <dt>issued by</dt>\n <dd>\n {issuers.map((iss, i) => (\n <span className=\"doc-classify-item\" key={`${iss.instance}-${i}`} title={iss.quote}>\n {iss.instance}\n {iss.quote && <span className=\"doc-classify-hint\"> “{iss.quote}”</span>}\n </span>\n ))}\n </dd>\n </>\n )}\n {concepts.length > 0 && (\n <>\n <dt>concepts</dt>\n <dd>\n {concepts.map((c) => (\n <span className=\"doc-classify-item\" key={c.tag} title={c.tag}>\n {c.concept}\n <span className=\"doc-classify-hint\"> {formatShare(c.share)}</span>\n </span>\n ))}\n </dd>\n </>\n )}\n {written > 0 && (\n <>\n <dt>statements</dt>\n <dd>\n {written} written\n {answer.statements!.some((s) => s.status === \"proposed\") && (\n <span className=\"doc-classify-hint\"> (proposed ones wait for review)</span>\n )}\n </dd>\n </>\n )}\n </dl>\n {steps.length > 0 && (\n <ol className=\"doc-classify-steps\">\n {steps.map((s, i) => (\n <li key={`${s.label}-${i}`}>\n <span className=\"doc-classify-step\">{s.label}</span>\n {s.method && <span className=\"doc-classify-hint\"> [{s.method}]</span>}\n {s.chosen ? <> → <strong>{s.chosen}</strong></> : <span className=\"doc-classify-hint\"> no choice</span>}\n {s.neighbours != null && <span className=\"doc-classify-hint\"> · {s.neighbours} neighbours</span>}\n {s.reason && <span className=\"doc-classify-hint\"> — {s.reason}</span>}\n {s.candidates.length > 0 && (\n <details className=\"doc-classify-candidates\">\n <summary>\n {s.candidates.length} candidate{s.candidates.length === 1 ? \"\" : \"s\"}\n </summary>\n <ul>\n {s.candidates.map((c, j) => (\n <li key={`${c.class}-${j}`}>\n <strong>{c.class}</strong>\n {c.detail && <span className=\"doc-classify-hint\"> {c.detail}</span>}\n </li>\n ))}\n </ul>\n </details>\n )}\n </li>\n ))}\n </ol>\n )}\n {answer.warnings && answer.warnings.length > 0 && (\n <ul className=\"doc-classify-warnings\">\n {answer.warnings.map((w, i) => (\n <li className=\"doc-classify-warn\" key={i}>\n {w}\n </li>\n ))}\n </ul>\n )}\n </>\n );\n}\n","import { useEffect, useMemo, useState } from \"react\";\nimport type { BrowseScope, ChunkDetail, DocScope } from \"../types\";\nimport { useExplorerData } from \"../lib/dataLayer\";\nimport { DEFAULT_SCHEME, type ColorScheme } from \"../lib/colorScheme\";\n\n// ColorSchemeEditor edits a document's RFC BN color settings — the color_enabled\n// flag + the per-(doc-type/status) and per-(chunk-status) palette — persisted in\n// the document's ROOT chunk fields. It fetches the root chunk on open (for the\n// revision + any sibling fields it must preserve) and writes back with\n// update_chunk. A \"copy to all documents of this type\" action stamps the same\n// palette onto every same-type document in scope, so a tree of like documents\n// stays visually consistent without per-doc editing.\nexport interface ColorSchemeEditorProps {\n documentId: string;\n rootChunkId: string;\n docType?: string;\n docStatus?: string;\n // chunkStatuses — the distinct statuses present in this document's chunks, so\n // the editor offers a color for each one actually in use (plus the defaults).\n chunkStatuses: string[];\n scope: DocScope;\n browse?: BrowseScope;\n onClose: () => void;\n // onSaved fires after a successful save so the viewer reloads its color meta +\n // re-tints the tree.\n onSaved: () => void;\n}\n\n// normalizeHex coerces a scheme color to the #rrggbb an <input type=\"color\">\n// requires (it rejects #rgb and names); a bad value falls back to neutral grey.\nfunction normalizeHex(v: string | undefined): string {\n const m = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec((v ?? \"\").trim());\n if (!m) return \"#888888\";\n let h = m[1];\n if (h.length === 3) h = h[0] + h[0] + h[1] + h[1] + h[2] + h[2];\n return \"#\" + h.toLowerCase();\n}\n\nexport default function ColorSchemeEditor({\n documentId,\n rootChunkId,\n docType,\n docStatus,\n chunkStatuses,\n scope,\n browse,\n onClose,\n onSaved,\n}: ColorSchemeEditorProps) {\n const data = useExplorerData();\n const [root, setRoot] = useState<ChunkDetail | null>(null);\n const [enabled, setEnabled] = useState(false);\n const [scheme, setScheme] = useState<ColorScheme>({});\n const [busy, setBusy] = useState(false);\n const [status, setStatus] = useState<string | null>(null);\n const [err, setErr] = useState<string | null>(null);\n\n // The keys the editor exposes: the defaults, plus this document's own doc key\n // and every chunk-status key actually in use — so a document with a bespoke\n // type/status still gets a picker. Stable + grouped (doc.* then chunk.*).\n const keys = useMemo(() => {\n const set = new Set<string>(Object.keys(DEFAULT_SCHEME));\n if (docType) set.add(`doc.${docType}.${docStatus || \"draft\"}`);\n for (const s of chunkStatuses) if (s) set.add(`chunk.${s}`);\n return [...set].sort();\n }, [docType, docStatus, chunkStatuses]);\n\n // Load the root chunk once for its revision + existing fields + stored scheme.\n useEffect(() => {\n let cancelled = false;\n data\n .documentGetChunk(rootChunkId, scope, browse)\n .then((d) => {\n if (cancelled) return;\n setRoot(d);\n const f = (d.fields ?? {}) as Record<string, unknown>;\n setEnabled(f.color_enabled === true);\n const stored = (f.color_scheme as ColorScheme) ?? {};\n // Seed from defaults so every picker shows a sensible starting color,\n // with the document's stored overrides on top.\n setScheme({ ...DEFAULT_SCHEME, ...stored });\n })\n .catch((e) => !cancelled && setErr(e instanceof Error ? e.message : String(e)));\n return () => {\n cancelled = true;\n };\n }, [data, rootChunkId, scope, browse]);\n\n const setColor = (key: string, hex: string) =>\n setScheme((prev) => ({ ...prev, [key]: hex }));\n\n // fieldsWith merges the color settings into an existing chunk's fields, so a\n // save never clobbers other typed fields the root chunk carries.\n const fieldsWith = (existing: unknown): Record<string, unknown> => ({\n ...((existing ?? {}) as Record<string, unknown>),\n color_enabled: enabled,\n color_scheme: scheme,\n });\n\n const save = async () => {\n if (!root) return;\n setBusy(true);\n setErr(null);\n setStatus(null);\n try {\n await data.documentUpdateChunk(\n rootChunkId,\n root.revision,\n { fields: fieldsWith(root.fields) },\n scope,\n browse,\n );\n onSaved();\n onClose();\n } catch (e) {\n setErr(e instanceof Error ? e.message : String(e));\n setBusy(false);\n }\n };\n\n // copyToType stamps THIS palette onto every OTHER document of the same type in\n // scope (best-effort; reports how many were updated). Each target is read for\n // its own root revision + fields so the write is a safe merge.\n const copyToType = async () => {\n if (!docType) {\n setErr(\"this document has no type to match\");\n return;\n }\n setBusy(true);\n setErr(null);\n setStatus(null);\n try {\n const { documents } = await data.documentsSummary({ underPath: \"/\" }, scope, browse);\n const targets = (documents ?? []).filter(\n (d) => d.type === docType && d.document_id !== documentId && d.root_chunk_id,\n );\n let applied = 0;\n for (const t of targets) {\n try {\n const tr = await data.documentGetChunk(t.root_chunk_id as string, scope, browse);\n await data.documentUpdateChunk(\n t.root_chunk_id as string,\n tr.revision,\n { fields: fieldsWith(tr.fields) },\n scope,\n browse,\n );\n applied++;\n } catch {\n // Skip a target that failed (revision race / gone); keep going.\n }\n }\n setStatus(`Applied to ${applied} other ${docType} document(s).`);\n onSaved();\n } catch (e) {\n setErr(e instanceof Error ? e.message : String(e));\n } finally {\n setBusy(false);\n }\n };\n\n const docKeys = keys.filter((k) => k.startsWith(\"doc.\"));\n const chunkKeys = keys.filter((k) => k.startsWith(\"chunk.\"));\n\n return (\n <div className=\"modal-overlay\" onClick={onClose}>\n <div className=\"modal scheme-editor\" onClick={(e) => e.stopPropagation()}>\n <div className=\"scheme-editor-head\">\n <h3>Document colors</h3>\n <div className=\"scheme-editor-actions\">\n <button type=\"button\" onClick={onClose} disabled={busy}>\n cancel\n </button>\n <button type=\"button\" className=\"primary\" onClick={() => void save()} disabled={busy || !root}>\n {busy ? \"saving…\" : \"save\"}\n </button>\n </div>\n </div>\n {err && <div className=\"modal-err\">{err}</div>}\n {!root ? (\n <p className=\"modal-context\">Loading…</p>\n ) : (\n <>\n <label className=\"scheme-toggle\">\n <input\n type=\"checkbox\"\n checked={enabled}\n onChange={(e) => setEnabled(e.target.checked)}\n />\n <span>Enable coloring for this document</span>\n </label>\n <p className=\"modal-context\">\n Document rows are tinted by type + status; chunk tiles by status. Colors apply as a\n semi-transparent wash so text stays readable.\n </p>\n\n <div className=\"scheme-group\">\n <h4>Document (type · status)</h4>\n {docKeys.map((k) => (\n <ColorRow key={k} label={k.slice(\"doc.\".length)} value={scheme[k]} onChange={(hex) => setColor(k, hex)} />\n ))}\n </div>\n <div className=\"scheme-group\">\n <h4>Chunks (status)</h4>\n {chunkKeys.map((k) => (\n <ColorRow key={k} label={k.slice(\"chunk.\".length)} value={scheme[k]} onChange={(hex) => setColor(k, hex)} />\n ))}\n </div>\n\n <div className=\"scheme-editor-foot\">\n <button type=\"button\" onClick={() => void copyToType()} disabled={busy || !docType} title={docType ? `Apply this palette to every other ${docType} document` : \"This document has no type\"}>\n copy to all {docType || \"same-type\"} documents\n </button>\n {status && <span className=\"scheme-status\">{status}</span>}\n </div>\n </>\n )}\n </div>\n </div>\n );\n}\n\nfunction ColorRow({ label, value, onChange }: { label: string; value: string | undefined; onChange: (hex: string) => void }) {\n const hex = normalizeHex(value);\n return (\n <label className=\"scheme-row\">\n <input type=\"color\" value={hex} onChange={(e) => onChange(e.target.value)} />\n <span className=\"scheme-key\">{label}</span>\n <code className=\"scheme-hex\">{hex}</code>\n </label>\n );\n}\n","import { useContext } from \"react\";\nimport { CardScopeContext, chunkCard, documentCard, useButtonCard, type CardSpec } from \"./AnnotationCard\";\n\n// ChunkTarget renders the far end of a link — a reference, a backlink, a related\n// chunk, an unlinked mention — as something the reader can follow.\n//\n// A chunk in THIS document selects in place. A chunk in ANOTHER document opens\n// that document at the chunk; it keeps the ↗ mark, because that click replaces\n// what is on screen and the reader should know before making it. Cross-document\n// targets used to be an inert label: the viewer showed one document and had\n// nowhere to go, so the links the edge list advertised could not be followed at\n// all.\n//\n// Each target carries the annotation card (RFC GZ) in place of a tooltip: a\n// chunk of this document shows its own annotation, a chunk of another document\n// that document's summary — its brief is the document's, not the chunk's, so\n// the card falls back to the link's title when there is none.\n//\n// With no onOpenDocument (a host that cannot leave its document), a\n// cross-document target stays a label rather than a button that does nothing.\nexport interface ChunkTargetProps {\n // The far chunk, its title, and the document it lives in.\n id: string;\n title?: string;\n targetDocumentId?: string;\n // The document on screen. A target with no document id of its own is treated\n // as belonging to it (an endpoint the runtime could not enrich).\n documentId: string;\n onSelectChunk: (id: string) => void;\n onOpenDocument?: (documentId: string, chunkId: string, title?: string) => void;\n}\n\nexport default function ChunkTarget({\n id,\n title,\n targetDocumentId,\n documentId,\n onSelectChunk,\n onOpenDocument,\n}: ChunkTargetProps) {\n const label = title || id.slice(0, 8);\n const src = useContext(CardScopeContext);\n const external = !!targetDocumentId && targetDocumentId !== documentId;\n const spec: CardSpec = external\n ? documentCard(targetDocumentId!, label, src)\n : chunkCard({ id, document_id: documentId, title: label, position: 0, revision: 0 }, src);\n const c = useButtonCard(spec);\n if (!external) {\n return (\n <>\n <button type=\"button\" className=\"doc-ref-target\" onClick={() => onSelectChunk(id)} {...c.props}>\n {label}\n </button>\n {c.card}\n </>\n );\n }\n if (!onOpenDocument) {\n return (\n <span className=\"doc-ref-target external\">\n {label} ↗\n </span>\n );\n }\n return (\n <>\n <button\n type=\"button\"\n className=\"doc-ref-target external\"\n onClick={() => onOpenDocument(targetDocumentId!, id, title)}\n {...c.props}\n >\n {label} ↗\n </button>\n {c.card}\n </>\n );\n}\n","import { useState } from \"react\";\nimport type { StatementFields } from \"../types\";\nimport {\n clipQuote,\n evidencePreview,\n methodLabel,\n statusLabel,\n validityLabel,\n verdictHint,\n} from \"../lib/statement\";\n\n// StatementRuling is how a reference row hands an operator's ruling on a proposed\n// statement to its host: accept (an optional reason) or reject (a reason). It\n// resolves once the ruling is stored — the host refetches the edges — and rejects\n// with the runtime's refusal, which the row shows inline.\nexport type StatementRuling = (id: string, accept: boolean, reason?: string) => Promise<void>;\n\n// StatementMeta is what a reference row shows of the RFC FN envelope beyond the\n// link itself: a status badge for a statement that does not simply hold, how it\n// was made when that is unusual, whether it has been judged (the reason is the\n// tooltip), when it is valid, and the first evidence quotes. Rendered inside the\n// row's flex container; the quote list wraps onto its own line. Quotes are plain\n// text nodes — never Markdown or HTML.\nexport function StatementMeta({ statement }: { statement: StatementFields }) {\n const status = statusLabel(statement);\n const method = methodLabel(statement);\n const verdict = verdictHint(statement);\n const validity = validityLabel(statement);\n const { rows, more } = evidencePreview(statement);\n return (\n <>\n {status && <span className={`doc-stmt-status ${status}`}>{status}</span>}\n {method && (\n <span className=\"doc-stmt-method\" title=\"how this relation was made\">\n {method}\n </span>\n )}\n {verdict && (\n <span className=\"doc-stmt-verdict\" title={verdict}>\n judged\n </span>\n )}\n {validity && <span className=\"doc-stmt-valid\">{validity}</span>}\n {rows.length > 0 && (\n <ul className=\"doc-stmt-evidence\">\n {rows.map((ev) => (\n <li key={ev.id} title={ev.quote}>\n “{clipQuote(ev.quote)}”\n {ev.part === \"title\" && <span className=\"doc-stmt-part\"> (title)</span>}\n {ev.stale && <span className=\"doc-stmt-stale\"> (source changed)</span>}\n </li>\n ))}\n {more > 0 && <li className=\"doc-stmt-more\">+{more} more</li>}\n </ul>\n )}\n </>\n );\n}\n\n// StatementReview is the Accept / Reject control on a proposed statement.\n// Reject opens an inline reason field (a rejection must say why); a refusal from\n// the runtime is shown next to the buttons.\nexport function StatementReview({ id, onRule }: { id: string; onRule: StatementRuling }) {\n const [rejecting, setRejecting] = useState(false);\n const [reason, setReason] = useState(\"\");\n const [busy, setBusy] = useState(false);\n const [err, setErr] = useState<string | null>(null);\n\n const rule = async (accept: boolean) => {\n setBusy(true);\n setErr(null);\n try {\n await onRule(id, accept, accept ? undefined : reason.trim());\n setRejecting(false);\n setReason(\"\");\n } catch (e) {\n setErr(e instanceof Error ? e.message : String(e));\n } finally {\n setBusy(false);\n }\n };\n\n return (\n <span className=\"doc-stmt-review\">\n {rejecting ? (\n <>\n <input\n type=\"text\"\n aria-label=\"Reason for rejecting\"\n placeholder=\"why reject?\"\n value={reason}\n disabled={busy}\n onChange={(e) => setReason(e.target.value)}\n onKeyDown={(e) => {\n if (e.key === \"Enter\" && reason.trim()) void rule(false);\n if (e.key === \"Escape\") setRejecting(false);\n }}\n autoFocus\n />\n <button\n type=\"button\"\n className=\"danger\"\n disabled={busy || !reason.trim()}\n onClick={() => void rule(false)}\n >\n Reject\n </button>\n <button type=\"button\" disabled={busy} onClick={() => setRejecting(false)}>\n Cancel\n </button>\n </>\n ) : (\n <>\n <button type=\"button\" disabled={busy} onClick={() => void rule(true)}>\n Accept\n </button>\n <button type=\"button\" disabled={busy} onClick={() => setRejecting(true)}>\n Reject…\n </button>\n </>\n )}\n {err && (\n <span className=\"doc-stmt-err\" role=\"alert\">\n {err}\n </span>\n )}\n </span>\n );\n}\n","import { useRef, useState } from \"react\";\nimport type { BrowseScope, DocEdge } from \"../types\";\nimport { useExplorerData } from \"../lib/dataLayer\";\nimport type { DocRulingAnswer } from \"../lib/dataLayer\";\nimport { ruleDocumentProposals, rulingNote } from \"../lib/bulkReview\";\nimport { chunkCount, undoRulings, type RulingAction, type RulingOutcome, type RulingScope } from \"../lib/ruling\";\nimport ChunkTarget from \"./ChunkTarget\";\nimport { StatementMeta } from \"./Statement\";\n\n// ProposalReview is the Connections panel's bulk review of one document's\n// proposals (RFC FS P1): pick rows, or take every proposal filed from the\n// document, and accept or reject them in one ruling. Every ruling counts\n// first (a dry run) and asks before it rules; a rejection needs a reason; the\n// result offers an undo when the data layer can revert.\nexport interface ProposalReviewProps {\n documentId: string;\n proposals: DocEdge[];\n // The document's edge list stopped at its page cap, so proposals past it are\n // not listed here (the \"all\" actions still reach them).\n incomplete?: boolean;\n scope: RulingScope;\n browse?: BrowseScope;\n // Called after a ruling or an undo changed statements: the host refetches.\n onChanged: () => void;\n onSelectChunk: (id: string) => void;\n onOpenDocument?: (documentId: string, chunkId: string, title?: string) => void;\n}\n\n// SAMPLE is how many of the dry run's sample the confirm lists.\nconst SAMPLE = 3;\n\ntype Step =\n | { kind: \"idle\" }\n | { kind: \"reason\"; action: RulingAction; all: boolean }\n | { kind: \"counting\"; action: RulingAction; all: boolean }\n | { kind: \"confirm\"; action: RulingAction; all: boolean; dry: DocRulingAnswer; changed: boolean }\n | { kind: \"ruling\"; action: RulingAction; ruled?: number; total?: number };\n\ninterface Result {\n text: string;\n rulingIds: string[];\n undone?: boolean;\n}\n\nexport default function ProposalReview({\n documentId,\n proposals,\n incomplete,\n scope,\n browse,\n onChanged,\n onSelectChunk,\n onOpenDocument,\n}: ProposalReviewProps) {\n const data = useExplorerData();\n const [selected, setSelected] = useState<ReadonlySet<string>>(new Set());\n const [step, setStep] = useState<Step>({ kind: \"idle\" });\n const [reason, setReason] = useState(\"\");\n const [err, setErr] = useState<string | null>(null);\n const [result, setResult] = useState<Result | null>(null);\n const confirmRef = useRef<((ok: boolean) => void) | null>(null);\n\n // Only rows still listed count as picked: a reload drops the ruled ones.\n const listed = new Set(proposals.map((p) => p.id!));\n const picked = [...selected].filter((id) => listed.has(id));\n const busy = step.kind !== \"idle\" && step.kind !== \"reason\";\n\n const begin = (action: RulingAction, all: boolean) => {\n setErr(null);\n setResult(null);\n if (action === \"reject\") setStep({ kind: \"reason\", action, all });\n else void rule(action, all, \"\");\n };\n\n const rule = async (action: RulingAction, all: boolean, why: string) => {\n setStep({ kind: \"counting\", action, all });\n let out: RulingOutcome;\n try {\n out = await ruleDocumentProposals(\n data,\n { documentId, action, ids: all ? undefined : picked, reason: why.trim() || undefined, scope, browse },\n {\n confirm: (dry, reasonFor) =>\n new Promise<boolean>((resolve) => {\n confirmRef.current = resolve;\n setStep({ kind: \"confirm\", action, all, dry, changed: reasonFor !== \"first\" });\n }),\n onProgress: (p) => setStep({ kind: \"ruling\", action, ruled: p.ruled, total: p.total }),\n },\n );\n } catch (e) {\n out = { rulingIds: [], ruled: 0, failed: 0, skipped: 0, total: 0, cancelled: false, failures: [], error: e };\n }\n confirmRef.current = null;\n setStep({ kind: \"idle\" });\n setReason(\"\");\n if (out.rulingIds.length > 0) {\n setSelected(new Set());\n setResult({ text: rulingNote(action, out), rulingIds: out.rulingIds });\n onChanged();\n } else if (out.error === undefined && !out.cancelled) {\n setResult({ text: \"Nothing to rule: no proposals match.\", rulingIds: [] });\n }\n if (out.error !== undefined) setErr(out.error instanceof Error ? out.error.message : String(out.error));\n };\n\n const answer = (ok: boolean) => {\n if (ok && step.kind === \"confirm\") setStep({ kind: \"ruling\", action: step.action });\n confirmRef.current?.(ok);\n };\n\n const undo = async () => {\n if (!result || !data.documentRevertRuling) return;\n const r = result;\n const u = await undoRulings((id) => data.documentRevertRuling!(id, scope, browse), r.rulingIds);\n const parts = [`${u.reverted} came back to review`];\n if (u.changed > 0) parts.push(`${u.changed} changed since and left as ruled`);\n if (u.errors.length > 0) parts.push(`not undone: ${u.errors.join(\"; \")}`);\n setResult({ ...r, undone: true, text: parts.join(\"; \") + \".\" });\n onChanged();\n };\n\n const toggle = (id: string) =>\n setSelected((cur) => {\n const next = new Set(cur);\n if (next.has(id)) next.delete(id);\n else next.add(id);\n return next;\n });\n const allPicked = proposals.length > 0 && picked.length === proposals.length;\n // Nothing listed and nothing past the list: no \"all\" to rule.\n const noneToRule = proposals.length === 0 && !incomplete;\n\n return (\n <div className=\"doc-conn-group doc-bulk\">\n <h5>Proposals from this document ({proposals.length})</h5>\n <div className=\"doc-bulk-bar\">\n <label>\n <input\n type=\"checkbox\"\n aria-label=\"select every proposal shown\"\n checked={allPicked}\n disabled={busy || proposals.length === 0}\n onChange={() => setSelected(allPicked ? new Set() : new Set(listed))}\n />{\" \"}\n all shown\n </label>\n <button type=\"button\" disabled={busy || picked.length === 0} onClick={() => begin(\"accept\", false)}>\n Accept selected ({picked.length})\n </button>\n <button type=\"button\" className=\"danger\" disabled={busy || picked.length === 0} onClick={() => begin(\"reject\", false)}>\n Reject selected…\n </button>\n <button type=\"button\" disabled={busy || noneToRule} onClick={() => begin(\"accept\", true)}>\n Accept all from this document\n </button>\n <button type=\"button\" className=\"danger\" disabled={busy || noneToRule} onClick={() => begin(\"reject\", true)}>\n Reject all…\n </button>\n </div>\n\n {step.kind === \"reason\" && (\n <form\n className=\"doc-bulk-step\"\n onSubmit={(e) => {\n e.preventDefault();\n if (reason.trim()) void rule(step.action, step.all, reason);\n }}\n >\n <input\n type=\"text\"\n aria-label=\"Reason for rejecting\"\n placeholder=\"why reject?\"\n value={reason}\n onChange={(e) => setReason(e.target.value)}\n autoFocus\n />\n <button type=\"submit\" className=\"danger\" disabled={!reason.trim()}>\n Count\n </button>\n <button type=\"button\" onClick={() => setStep({ kind: \"idle\" })}>\n Cancel\n </button>\n </form>\n )}\n {step.kind === \"counting\" && <p className=\"doc-conn-empty\">counting…</p>}\n {step.kind === \"confirm\" && <BulkConfirm step={step} onAnswer={answer} />}\n {step.kind === \"ruling\" && (\n <p className=\"doc-conn-empty\">\n {step.total ? `ruled ${step.ruled ?? 0} of ${step.total}…` : \"ruling…\"}\n </p>\n )}\n {err && (\n <p className=\"doc-stmt-err\" role=\"alert\">\n {err}\n </p>\n )}\n {result && (\n <p className=\"doc-bulk-result\" role=\"status\">\n {result.text}\n {result.rulingIds.length > 0 && !result.undone && data.documentRevertRuling && (\n <button type=\"button\" onClick={() => void undo()}>\n Undo\n </button>\n )}\n </p>\n )}\n\n {proposals.length === 0 ? (\n <p className=\"doc-conn-empty\">none</p>\n ) : (\n <ul className=\"doc-conn-list\">\n {proposals.map((e) => (\n <li className=\"doc-conn-row\" key={e.id}>\n <input\n type=\"checkbox\"\n aria-label={`select ${e.from_title ?? e.from_id} ${e.kind} ${e.to_title ?? e.to_id}`}\n checked={selected.has(e.id!)}\n disabled={busy}\n onChange={() => toggle(e.id!)}\n />\n <ChunkTarget\n id={e.from_id}\n title={e.from_title}\n targetDocumentId={e.from_document_id}\n documentId={documentId}\n onSelectChunk={onSelectChunk}\n onOpenDocument={onOpenDocument}\n />\n <span className=\"doc-ref-kind\">{e.kind}</span>\n <ChunkTarget\n id={e.to_id}\n title={e.to_title}\n targetDocumentId={e.to_document_id}\n documentId={documentId}\n onSelectChunk={onSelectChunk}\n onOpenDocument={onOpenDocument}\n />\n <StatementMeta statement={e} />\n </li>\n ))}\n </ul>\n )}\n </div>\n );\n}\n\n// BulkConfirm is the dry run before a document's ruling: how many, a sample,\n// what will be skipped.\nexport function BulkConfirm({\n step,\n onAnswer,\n}: {\n step: { action: RulingAction; all: boolean; dry: DocRulingAnswer; changed: boolean };\n onAnswer: (ok: boolean) => void;\n}) {\n const { dry } = step;\n const verb = step.action === \"accept\" ? \"Accept\" : \"Reject\";\n const chunks = chunkCount(dry.matched);\n return (\n <div className=\"doc-bulk-step doc-bulk-confirm\">\n {step.changed && <p className=\"doc-bulk-warn\">The proposals changed since the last count; counted again.</p>}\n <p>\n {verb} {dry.matched} statement{dry.matched === 1 ? \"\" : \"s\"}\n {step.all ? \" filed from this document\" : \"\"}\n {chunks > 1 ? `, in ${chunks} rulings of up to 1,000` : \"\"}?\n {dry.skipped > 0 && ` ${dry.skipped} of them are not yours to rule and will be skipped.`}\n </p>\n {(dry.sample ?? []).length > 0 && (\n <ul className=\"doc-bulk-sample\">\n {(dry.sample ?? []).slice(0, SAMPLE).map((s) => (\n <li key={s.id}>\n {s.from_title || s.from_id} <span className=\"doc-ref-kind\">{s.kind}</span> {s.to_title || s.to_id}\n </li>\n ))}\n </ul>\n )}\n <button type=\"button\" className={step.action === \"reject\" ? \"danger\" : undefined} onClick={() => onAnswer(true)}>\n {verb} {dry.matched}\n </button>\n <button type=\"button\" onClick={() => onAnswer(false)}>\n Cancel\n </button>\n </div>\n );\n}\n","import { useEffect, useState } from \"react\";\nimport type {\n Backlink,\n BrowseScope,\n DocScope,\n RelatedChunk,\n UnlinkedMention,\n} from \"../types\";\nimport { useExplorerData } from \"../lib/dataLayer\";\nimport type { ReviewPanel } from \"../lib/bulkReview\";\nimport ChunkTarget from \"./ChunkTarget\";\nimport ProposalReview from \"./ProposalReview\";\nimport { StatementMeta } from \"./Statement\";\n\n// Connections is the RFC BS per-chunk connection surface, a collapsible companion\n// to CrossReferences. It shows three lists for the SELECTED chunk, each fetched\n// lazily (only once the section is expanded, and refetched when the selection\n// changes while open — collapsed keeps the viewer quiet):\n// - Backlinks — chunks that link TO this one (\"what links here\").\n// - Related — semantic neighbours (vector similarity). REFUSES with no\n// embedder configured → a muted note, not an error.\n// - Unlinked mentions — chunks that name this one but don't link it (candidates).\n// Every target is clickable: a same-document one selects in place (onSelectChunk),\n// a cross-document one (↗) opens that document at the chunk (onOpenDocument) —\n// the same rule CrossReferences uses, through the same ChunkTarget.\n//\n// With `review` (RFC FS), the panel also lists the document's own proposals —\n// whichever chunk is selected — with row selection and bulk Accept / Reject.\n// The host passes it only when its data layer can rule in bulk.\nexport type ConnectionsReview = ReviewPanel;\n\nexport interface ConnectionsProps {\n documentId: string;\n selectedId?: string;\n scope: DocScope;\n browse?: BrowseScope;\n onSelectChunk: (id: string) => void;\n onOpenDocument?: (documentId: string, chunkId: string, title?: string) => void;\n // Bumped by the host when the document's edges changed (an operator ruled on a\n // proposal) so an open panel refetches its backlinks.\n refreshKey?: number;\n review?: ConnectionsReview;\n}\n\nconst RELATED_LIMIT = 8;\nconst MENTIONS_LIMIT = 20;\n\n// isEmbedderError recognizes the `related` op's refusal when the deployment has no\n// embedder/vector backend, so the UI can say \"not configured\" rather than surface\n// a raw error — related is a best-effort enhancement, never load-bearing.\nfunction isEmbedderError(msg: string): boolean {\n return /embedder|embedding|vector|semantic|not configured/i.test(msg);\n}\n\nexport default function Connections({\n documentId,\n selectedId,\n scope,\n browse,\n onSelectChunk,\n onOpenDocument,\n refreshKey,\n review,\n}: ConnectionsProps) {\n const data = useExplorerData();\n const [open, setOpen] = useState(false);\n const [loading, setLoading] = useState(false);\n const [loadedId, setLoadedId] = useState<string | undefined>(undefined);\n const [backlinks, setBacklinks] = useState<Backlink[]>([]);\n const [related, setRelated] = useState<RelatedChunk[]>([]);\n const [relatedNote, setRelatedNote] = useState<string | null>(null);\n const [mentions, setMentions] = useState<UnlinkedMention[]>([]);\n const [mentionsTruncated, setMentionsTruncated] = useState(false);\n\n // Fetch only while expanded AND a chunk is selected; the three reads are\n // independent (allSettled) so a `related` refusal never blanks backlinks/\n // mentions. Cancelled on unmount / re-selection so a stale resolution can't\n // clobber the newer one.\n useEffect(() => {\n if (!open || !selectedId) return;\n const id = selectedId;\n let cancelled = false;\n setLoading(true);\n Promise.allSettled([\n data.documentBacklinks(id, scope, browse),\n data.documentRelated(id, scope, browse, RELATED_LIMIT),\n data.documentUnlinkedMentions(id, scope, browse, MENTIONS_LIMIT),\n ]).then(([b, r, m]) => {\n if (cancelled) return;\n setBacklinks(b.status === \"fulfilled\" ? b.value.backlinks ?? [] : []);\n if (r.status === \"fulfilled\") {\n setRelated(r.value.related ?? []);\n setRelatedNote(null);\n } else {\n setRelated([]);\n const msg = r.reason instanceof Error ? r.reason.message : String(r.reason);\n setRelatedNote(isEmbedderError(msg) ? \"semantic search not configured\" : msg);\n }\n if (m.status === \"fulfilled\") {\n setMentions(m.value.unlinked_mentions ?? []);\n setMentionsTruncated(!!m.value.truncated);\n } else {\n setMentions([]);\n setMentionsTruncated(false);\n }\n setLoadedId(id);\n setLoading(false);\n });\n return () => {\n cancelled = true;\n };\n }, [data, open, selectedId, scope, browse, refreshKey]);\n\n // The three lists differ only in which fields name the far chunk.\n const target = (id: string, title?: string, targetDocumentId?: string) => (\n <ChunkTarget\n id={id}\n title={title}\n targetDocumentId={targetDocumentId}\n documentId={documentId}\n onSelectChunk={onSelectChunk}\n onOpenDocument={onOpenDocument}\n />\n );\n // Data is current only when it was fetched for THIS selection and no fetch is in\n // flight — otherwise show \"loading…\" (this also covers the first frame after\n // expanding, before the effect sets loading, so no stale \"none\" flashes).\n const ready = !!(open && selectedId && !loading && loadedId === selectedId);\n\n return (\n <div className=\"doc-conn\">\n <button\n type=\"button\"\n className=\"doc-conn-toggle\"\n onClick={() => setOpen((o) => !o)}\n >\n {open ? \"▼\" : \"▶\"} Connections\n </button>\n {open && (\n <div className=\"doc-conn-body\">\n {review && (\n <ProposalReview\n documentId={documentId}\n proposals={review.proposals}\n incomplete={review.incomplete}\n scope={review.scope}\n browse={browse}\n onChanged={review.onChanged}\n onSelectChunk={onSelectChunk}\n onOpenDocument={onOpenDocument}\n />\n )}\n {!selectedId ? (\n <p className=\"doc-conn-empty\">Select a chunk.</p>\n ) : !ready ? (\n <p className=\"doc-conn-empty\">loading…</p>\n ) : (\n <>\n <div className=\"doc-conn-group\">\n <h5>Backlinks</h5>\n {backlinks.length === 0 ? (\n <p className=\"doc-conn-empty\">none</p>\n ) : (\n <ul className=\"doc-conn-list\">\n {backlinks.map((e, i) => (\n <li className=\"doc-conn-row\" key={`${e.from_id}-${e.kind}-${i}`}>\n {target(e.from_id, e.from_title, e.from_document_id)}\n <span className=\"doc-ref-kind\">{e.kind}</span>\n {e.auto && (\n <span className=\"doc-conn-auto\" title=\"Auto-linked from a [[wikilink]]\">\n auto\n </span>\n )}\n <StatementMeta statement={e} />\n </li>\n ))}\n </ul>\n )}\n </div>\n\n <div className=\"doc-conn-group\">\n <h5>Related</h5>\n {relatedNote ? (\n <p className=\"doc-conn-empty\">{relatedNote}</p>\n ) : related.length === 0 ? (\n <p className=\"doc-conn-empty\">none</p>\n ) : (\n <ul className=\"doc-conn-list\">\n {related.map((r, i) => (\n <li className=\"doc-conn-row\" key={`${r.chunk_id}-${i}`}>\n {target(r.chunk_id, r.title, r.document_id)}\n <span className=\"doc-conn-score\" title=\"similarity score\">\n {r.score.toFixed(2)}\n </span>\n </li>\n ))}\n </ul>\n )}\n </div>\n\n <div className=\"doc-conn-group\">\n <h5>Unlinked mentions</h5>\n {mentions.length === 0 ? (\n <p className=\"doc-conn-empty\">none</p>\n ) : (\n <ul className=\"doc-conn-list\">\n {mentions.map((m, i) => (\n <li className=\"doc-conn-row\" key={`${m.chunk_id}-${i}`}>\n {target(m.chunk_id, m.title, m.document_id)}\n </li>\n ))}\n {mentionsTruncated && (\n <li className=\"doc-conn-more\" aria-hidden>\n (more…)\n </li>\n )}\n </ul>\n )}\n </div>\n </>\n )}\n </div>\n )}\n </div>\n );\n}\n","import { useState } from \"react\";\nimport type { DocEdge } from \"../types\";\nimport { isProposed } from \"../lib/statement\";\nimport ChunkTarget from \"./ChunkTarget\";\nimport MermaidDiagram from \"./Mermaid\";\nimport { StatementMeta, StatementReview, type StatementRuling } from \"./Statement\";\n\n// CrossReferences renders the RFC BN P4 cross-reference surface for a document:\n// - a References list for the SELECTED chunk (its outgoing + incoming edges),\n// each target clickable: a same-document one selects in place, a\n// cross-document one (↗) opens that document at the chunk.\n// - a collapsible whole-document relationship GRAPH (a Mermaid flowchart of the\n// document's edges), capped to the first N with a \"show all\" expand so a\n// heavily cross-linked document doesn't render an unreadable diagram. Its\n// nodes follow the same rule as the list.\n// Fed by the paged get_edges load (all edges touching the document); renders\n// nothing when the document has no edges. Since RFC FN each edge is a statement: a row\n// also shows its status / method / verdict / validity / evidence, and a proposed\n// one gets Accept / Reject when the host passes onRuleStatement.\nexport interface CrossReferencesProps {\n edges: DocEdge[];\n documentId: string;\n selectedId?: string;\n onSelectChunk: (id: string) => void;\n // Opens ANOTHER document at a chunk. Omitted → cross-document targets are\n // labels only.\n onOpenDocument?: (documentId: string, chunkId: string, title?: string) => void;\n // Rules on a proposed statement, then refetches the edges. Omitted → proposals\n // are shown but not reviewable here.\n onRuleStatement?: StatementRuling;\n // The edge list stopped before the end (the load's page cap): both the list\n // and the graph may be missing links, so the panel says so.\n incomplete?: boolean;\n}\n\n// GRAPH_CAP is the default number of edges the relationship graph draws before\n// requiring an explicit \"show all\" (keeps a big graph readable + cheap).\nconst GRAPH_CAP = 24;\n\nexport default function CrossReferences({\n edges,\n documentId,\n selectedId,\n onSelectChunk,\n onOpenDocument,\n onRuleStatement,\n incomplete,\n}: CrossReferencesProps) {\n const [showGraph, setShowGraph] = useState(false);\n const [showAll, setShowAll] = useState(false);\n\n if (edges.length === 0) return null;\n\n const refs = selectedId\n ? edges.filter((e) => e.from_id === selectedId || e.to_id === selectedId)\n : [];\n const graphEdges = showAll ? edges : edges.slice(0, GRAPH_CAP);\n const graphDef = buildGraph(graphEdges);\n const followNode = (node: string) => {\n const hit = graphEndpoint(graphEdges, node);\n if (!hit) return;\n if (!hit.documentId || hit.documentId === documentId) onSelectChunk(hit.id);\n else onOpenDocument?.(hit.documentId, hit.id, hit.title);\n };\n\n return (\n <div className=\"doc-refs\">\n {incomplete && (\n <p className=\"doc-refs-incomplete\">\n Showing the first {edges.length} links of this document; it has more, which are not shown\n here or in the graph.\n </p>\n )}\n {selectedId && (\n <div className=\"doc-refs-list-wrap\">\n <h4>References</h4>\n {refs.length === 0 ? (\n <p className=\"doc-refs-empty\">This chunk has no links.</p>\n ) : (\n <ul className=\"doc-refs-list\">\n {refs.map((e, i) => (\n <RefRow\n key={`${e.from_id}-${e.to_id}-${e.kind}-${i}`}\n edge={e}\n selectedId={selectedId}\n documentId={documentId}\n onSelectChunk={onSelectChunk}\n onOpenDocument={onOpenDocument}\n onRuleStatement={onRuleStatement}\n />\n ))}\n </ul>\n )}\n </div>\n )}\n\n <div className=\"doc-graph\">\n <button type=\"button\" className=\"doc-graph-toggle\" onClick={() => setShowGraph((s) => !s)}>\n {showGraph ? \"▼\" : \"▶\"} relationship graph ({edges.length})\n </button>\n {showGraph && (\n <>\n <MermaidDiagram code={graphDef} onNodeClick={followNode} />\n {edges.length > GRAPH_CAP && (\n <button type=\"button\" className=\"doc-graph-more\" onClick={() => setShowAll((s) => !s)}>\n {showAll ? `show top ${GRAPH_CAP}` : `show all ${edges.length}`}\n </button>\n )}\n </>\n )}\n </div>\n </div>\n );\n}\n\nexport function RefRow({\n edge,\n selectedId,\n documentId,\n onSelectChunk,\n onOpenDocument,\n onRuleStatement,\n}: {\n edge: DocEdge;\n selectedId: string;\n documentId: string;\n onSelectChunk: (id: string) => void;\n onOpenDocument?: (documentId: string, chunkId: string, title?: string) => void;\n onRuleStatement?: StatementRuling;\n}) {\n const outgoing = edge.from_id === selectedId;\n const otherId = outgoing ? edge.to_id : edge.from_id;\n const otherTitle = outgoing ? edge.to_title : edge.from_title;\n const otherDoc = outgoing ? edge.to_document_id : edge.from_document_id;\n return (\n <li className=\"doc-ref\">\n <span className=\"doc-ref-kind\">{edge.kind}</span>\n <span className=\"doc-ref-arrow\" aria-hidden>\n {outgoing ? \"→\" : \"←\"}\n </span>\n <ChunkTarget\n id={otherId}\n title={otherTitle}\n targetDocumentId={otherDoc}\n documentId={documentId}\n onSelectChunk={onSelectChunk}\n onOpenDocument={onOpenDocument}\n />\n <StatementMeta statement={edge} />\n {onRuleStatement && isProposed(edge) && (\n <StatementReview id={edge.id!} onRule={onRuleStatement} />\n )}\n </li>\n );\n}\n\n// buildGraph renders the document's edges as a Mermaid left-to-right flowchart.\n// Node ids are the chunk ids (prefixed + stripped to mermaid-safe chars); labels\n// are the endpoint titles, sanitized of mermaid metacharacters and truncated.\n// Mermaid dedups nodes by id, so re-declaring a node's label across edges is fine.\n// A statement that does not hold yet (proposed) is drawn dotted.\nexport function buildGraph(edges: DocEdge[]): string {\n const lines = [\"graph LR\"];\n for (const e of edges) {\n const from = `${nodeId(e.from_id)}[\"${label(e.from_title, e.from_id)}\"]`;\n const to = `${nodeId(e.to_id)}[\"${label(e.to_title, e.to_id)}\"]`;\n const kind = (e.kind || \"link\").replace(/[|\"]/g, \" \");\n const arrow = e.status === \"proposed\" ? \"-.->\" : \"-->\";\n lines.push(` ${from} ${arrow}|${kind}| ${to}`);\n }\n return lines.join(\"\\n\");\n}\n\n// graphEndpoint maps a drawn node back to the chunk it stands for, with the\n// document that chunk lives in — what a click on the node needs to follow it.\nexport function graphEndpoint(\n edges: DocEdge[],\n node: string,\n): { id: string; documentId?: string; title?: string } | undefined {\n for (const e of edges) {\n if (nodeId(e.from_id) === node) {\n return { id: e.from_id, documentId: e.from_document_id, title: e.from_title };\n }\n if (nodeId(e.to_id) === node) {\n return { id: e.to_id, documentId: e.to_document_id, title: e.to_title };\n }\n }\n return undefined;\n}\n\nexport function nodeId(id: string): string {\n return \"n\" + id.replace(/[^a-zA-Z0-9]/g, \"\");\n}\n\nfunction label(title: string | undefined, id: string): string {\n const base = (title ?? \"\").replace(/[\"[\\]{}|<>]/g, \" \").replace(/\\s+/g, \" \").trim();\n const text = base || id.slice(0, 6);\n return text.length > 30 ? text.slice(0, 29) + \"…\" : text;\n}\n","// DocUnavailable stands in for a document that could not be read: deleted, in a\n// scope other than the one being browsed, or not the reader's to see. It is\n// reached most easily by following a reference — an edge outlives the document\n// it points at — and it has to say so in place, because the alternative is an\n// empty pane that looks like a viewer bug. The host's trail stays above it, so\n// the way back is still there.\nexport interface DocUnavailableProps {\n documentId: string;\n scope: string;\n // The runtime's own reason, when it gave one.\n detail?: string;\n}\n\nexport default function DocUnavailable({ documentId, scope, detail }: DocUnavailableProps) {\n return (\n <div className=\"doc-unavailable\" role=\"alert\">\n <p className=\"doc-unavailable-lead\">This document can’t be opened.</p>\n <p>\n It may have been deleted, live in a scope other than <code>{scope}</code>, or not be\n yours to read.\n </p>\n <p className=\"doc-unavailable-detail\">\n <code>{documentId}</code>\n {detail && <> — {detail}</>}\n </p>\n </div>\n );\n}\n","import { useEffect, useState } from \"react\";\nimport type { BrowseScope, ChunkRevision, DocScope } from \"../types\";\nimport { useExplorerData } from \"../lib/dataLayer\";\n\n// HistoryModal is the RFC BS read-only edit-history surface for one chunk. It\n// lists the chunk's revisions (number + time + actor); clicking a revision shows\n// that version's body verbatim, and a from→to picker renders a unified diff\n// between any two. Restore is deliberately NOT here (this pass is read-only) —\n// mirroring ChunkEditorModal, which owns the write path.\nexport interface HistoryModalProps {\n chunkId: string;\n chunkTitle?: string;\n scope: DocScope;\n // browse (RFC AS) — read the history under the browsed subject's document.\n browse?: BrowseScope;\n onClose: () => void;\n}\n\n// Which output pane is showing: a single version's body, or a two-revision diff.\ntype OutputMode = \"none\" | \"version\" | \"diff\";\n\n// formatTs renders a revision timestamp. `created_at` is Unix NANOSECONDS (RFC BS\n// history), so divide by 1e6 for a JS Date; a stray string is tolerated via\n// Date.parse. Falls back to the raw value when it isn't a usable instant.\nfunction formatTs(createdAt: number): string {\n const ms = typeof createdAt === \"number\" ? createdAt / 1e6 : Date.parse(String(createdAt));\n if (!Number.isFinite(ms) || ms <= 0) return String(createdAt ?? \"\");\n return new Date(ms).toLocaleString();\n}\n\nexport default function HistoryModal({ chunkId, chunkTitle, scope, browse, onClose }: HistoryModalProps) {\n return (\n <div className=\"modal-overlay\" onClick={onClose}>\n <div className=\"modal history-modal\" onClick={(e) => e.stopPropagation()}>\n <div className=\"modal-header sticky-top\">\n <h3>History{chunkTitle ? ` — ${chunkTitle}` : \"\"}</h3>\n <div className=\"modal-buttons modal-buttons-top\">\n <button type=\"button\" onClick={onClose}>\n close\n </button>\n </div>\n </div>\n <HistoryView chunkId={chunkId} scope={scope} browse={browse} />\n </div>\n </div>\n );\n}\n\n// HistoryView is the history itself — the revisions, one version, a diff —\n// shown in the modal above and in the document's history side panel.\nexport function HistoryView({\n chunkId,\n scope,\n browse,\n}: {\n chunkId: string;\n scope: DocScope;\n browse?: BrowseScope;\n}) {\n const data = useExplorerData();\n const [revisions, setRevisions] = useState<ChunkRevision[]>([]);\n const [loading, setLoading] = useState(true);\n const [err, setErr] = useState<string | null>(null);\n\n const [mode, setMode] = useState<OutputMode>(\"none\");\n const [selectedRev, setSelectedRev] = useState<number | null>(null);\n const [body, setBody] = useState<string>(\"\");\n const [busy, setBusy] = useState(false); // a version/diff fetch is in flight\n\n const [fromRev, setFromRev] = useState<number | null>(null);\n const [toRev, setToRev] = useState<number | null>(null);\n const [diff, setDiff] = useState<string>(\"\");\n\n // Load the revision list on open. Default the diff picker to the full span\n // (oldest → newest) so a single \"diff\" click is meaningful without fiddling.\n useEffect(() => {\n let cancelled = false;\n setLoading(true);\n setErr(null);\n data\n .documentHistory(chunkId, scope, browse)\n .then((r) => {\n if (cancelled) return;\n const revs = r.revisions ?? [];\n setRevisions(revs);\n if (revs.length >= 2) {\n const nums = revs.map((x) => x.revision);\n setFromRev(Math.min(...nums));\n setToRev(Math.max(...nums));\n }\n })\n .catch((e) => !cancelled && setErr(e instanceof Error ? e.message : String(e)))\n .finally(() => !cancelled && setLoading(false));\n return () => {\n cancelled = true;\n };\n }, [data, chunkId, scope, browse]);\n\n const viewVersion = async (rev: number) => {\n setErr(null);\n setBusy(true);\n setSelectedRev(rev);\n setMode(\"version\");\n try {\n const r = await data.documentGetVersion(chunkId, rev, scope, browse);\n setBody(r.body ?? \"\");\n } catch (e) {\n setErr(e instanceof Error ? e.message : String(e));\n } finally {\n setBusy(false);\n }\n };\n\n const runDiff = async () => {\n if (fromRev === null || toRev === null) return;\n setErr(null);\n setBusy(true);\n setMode(\"diff\");\n try {\n const r = await data.documentDiff(chunkId, fromRev, toRev, scope, browse);\n setDiff(r.diff ?? \"\");\n } catch (e) {\n setErr(e instanceof Error ? e.message : String(e));\n } finally {\n setBusy(false);\n }\n };\n\n return (\n <>\n {err && <div className=\"modal-err\">{err}</div>}\n\n {loading ? (\n <p className=\"doc-empty-body\">loading…</p>\n ) : revisions.length === 0 ? (\n <p className=\"doc-empty-body\">No history recorded for this chunk.</p>\n ) : (\n <>\n <div className=\"doc-hist-revs\">\n {revisions.map((rev) => (\n <button\n key={rev.revision}\n type=\"button\"\n className={\n \"doc-hist-rev\" +\n (mode === \"version\" && selectedRev === rev.revision ? \" active\" : \"\")\n }\n onClick={() => void viewVersion(rev.revision)}\n >\n <span className=\"doc-hist-rev-num\">rev {rev.revision}</span>\n <span className=\"doc-hist-rev-time\">{formatTs(rev.created_at)}</span>\n <span className=\"doc-hist-rev-actor\">{rev.actor || \"unknown\"}</span>\n </button>\n ))}\n </div>\n\n {revisions.length >= 2 && (\n <div className=\"doc-hist-diffbar\">\n <span>Compare</span>\n <select\n value={fromRev ?? \"\"}\n onChange={(e) => setFromRev(e.target.value === \"\" ? null : Number(e.target.value))}\n aria-label=\"diff from revision\"\n >\n {revisions.map((r) => (\n <option key={r.revision} value={r.revision}>\n rev {r.revision}\n </option>\n ))}\n </select>\n <span aria-hidden>→</span>\n <select\n value={toRev ?? \"\"}\n onChange={(e) => setToRev(e.target.value === \"\" ? null : Number(e.target.value))}\n aria-label=\"diff to revision\"\n >\n {revisions.map((r) => (\n <option key={r.revision} value={r.revision}>\n rev {r.revision}\n </option>\n ))}\n </select>\n <button\n type=\"button\"\n onClick={() => void runDiff()}\n disabled={busy || fromRev === null || toRev === null}\n >\n diff\n </button>\n </div>\n )}\n\n <div className=\"doc-hist-output\">\n {busy ? (\n <p className=\"doc-empty-body\">loading…</p>\n ) : mode === \"diff\" ? (\n <DiffView text={diff} />\n ) : mode === \"version\" ? (\n <pre className=\"md-pre doc-hist-version\">\n <code>{body || \"(empty)\"}</code>\n </pre>\n ) : (\n <p className=\"doc-empty-body\">\n Select a revision to view it, or compare two.\n </p>\n )}\n </div>\n </>\n )}\n </>\n );\n}\n\n// DiffView renders a unified diff, coloring added (+) / removed (-) / hunk (@@)\n// lines. `+++`/`---` file headers stay neutral so they don't read as content\n// changes. Line breaks come from the explicit \"\\n\" text nodes inside the <pre>,\n// so spacing stays single (a per-line <div> would double it).\nfunction DiffView({ text }: { text: string }) {\n if (!text.trim()) return <p className=\"doc-empty-body\">(no differences)</p>;\n const lines = text.split(\"\\n\");\n return (\n <pre className=\"md-pre doc-hist-diff\">\n {lines.map((ln, i) => {\n const cls =\n ln.startsWith(\"+\") && !ln.startsWith(\"+++\")\n ? \"diff-add\"\n : ln.startsWith(\"-\") && !ln.startsWith(\"---\")\n ? \"diff-del\"\n : ln.startsWith(\"@@\")\n ? \"diff-hunk\"\n : \"\";\n return (\n <span key={i} className={cls}>\n {ln}\n {\"\\n\"}\n </span>\n );\n })}\n </pre>\n );\n}\n","// remarkBareBreak turns a bare <br> in a chunk body into a line break. An\n// extraction writes one between a table cell's paragraphs, the only break a\n// GFM cell can hold. react-markdown renders no raw HTML (no rehype-raw), so\n// it would otherwise drop the tag and run the paragraphs together. Only the\n// bare tag is read: any other HTML, a <br> with attributes included, stays\n// as react-markdown leaves it. The runtime's renderer reads the same tag the\n// same way (internal/files/render isBareBreak).\n\ntype MdNode = { type: string; value?: string; children?: MdNode[] };\n\nconst BARE_BREAK = /^<br\\s*\\/?>$/i;\n\nfunction walk(node: MdNode): void {\n const kids = node.children;\n if (!kids) return;\n for (let i = 0; i < kids.length; i++) {\n const k = kids[i];\n if (k.type === \"html\" && BARE_BREAK.test(k.value ?? \"\")) {\n kids[i] = { type: \"break\" };\n } else {\n walk(k);\n }\n }\n}\n\nexport default function remarkBareBreak() {\n return (tree: MdNode) => walk(tree);\n}\n","import ReactMarkdown from \"react-markdown\";\nimport remarkGfm from \"remark-gfm\";\nimport type { Components } from \"react-markdown\";\nimport MermaidDiagram from \"./Mermaid\";\nimport remarkBareBreak from \"../lib/remarkBareBreak\";\n\n// Markdown renders a chunk body as GitHub-flavored Markdown (RFC BN): headings,\n// paragraphs, inline styles, links, fenced code, blockquotes, lists, TABLES, and\n// ```mermaid diagrams. It uses react-markdown + remark-gfm; react-markdown is\n// safe by default (it does not emit raw HTML — no rehype-raw — and its default\n// urlTransform strips javascript:/other dangerous hrefs). ```mermaid fences\n// render through the shared MermaidDiagram (lazy, securityLevel:\"strict\",\n// graceful fallback to a code block). A bare <br> (a table cell's paragraph\n// break, as an extraction writes it) is a line break (remarkBareBreak).\n\nexport default function Markdown({ source }: { source: string }) {\n return (\n <div className=\"md\">\n <ReactMarkdown remarkPlugins={[remarkGfm, remarkBareBreak]} components={MD_COMPONENTS}>\n {source}\n </ReactMarkdown>\n </div>\n );\n}\n\nconst MD_COMPONENTS: Components = {\n // react-markdown already sanitized the href; add target/rel for external links.\n a({ href, children }) {\n const url = href ?? \"\";\n const external = /^https?:\\/\\//i.test(url);\n return (\n <a href={url} target={external ? \"_blank\" : undefined} rel={external ? \"noopener noreferrer\" : undefined}>\n {children}\n </a>\n );\n },\n // Let the code renderer own the block wrapper so a mermaid fence isn't wrapped\n // in a <pre> (and a normal code block gets exactly one <pre>).\n pre({ children }) {\n return <>{children}</>;\n },\n code({ className, children }) {\n const lang = /language-(\\w+)/.exec(className ?? \"\")?.[1];\n const raw = String(children ?? \"\");\n if (lang === \"mermaid\") {\n return <MermaidDiagram code={raw.replace(/\\n$/, \"\")} />;\n }\n // Fenced block (has a language) or a multi-line block without one → <pre>.\n if (lang || raw.includes(\"\\n\")) {\n return (\n <pre className=\"md-pre\">\n <code className={className}>{children}</code>\n </pre>\n );\n }\n return <code>{children}</code>; // inline\n },\n};\n","import { useEffect, useId, useRef, useState, type KeyboardEvent, type ReactNode } from \"react\";\n\n// MoreMenu is the document header's \"more\" button (RFC GZ): one menu holding\n// every document action that is not \"edit\". Items come in groups; a rule\n// separates the groups.\n//\n// Follows the ARIA menu-button pattern, as DownloadMenu did: Enter / Space /\n// ArrowDown open onto the first item (ArrowUp onto the last), the arrows wrap,\n// Home / End jump, Escape closes and returns focus to the button, Tab and an\n// outside click close it. A disabled item stays in the list (aria-disabled),\n// so the reader can see why an action is not there, and does nothing.\n\nexport interface MoreMenuItem {\n key: string;\n label: ReactNode;\n // title explains the action (and, when disabled, why).\n title?: string;\n disabled?: boolean;\n // danger draws the item apart (delete).\n danger?: boolean;\n run: () => void;\n}\n\nexport interface MoreMenuProps {\n // groups of items; empty groups are dropped.\n groups: MoreMenuItem[][];\n // busy names an action still running (a download being rendered): the button\n // shows it and stays disabled until it ends.\n busy?: string;\n label?: string;\n}\n\nexport default function MoreMenu({ groups, busy, label = \"More actions\" }: MoreMenuProps) {\n const shown = groups.filter((g) => g.length > 0);\n const items = shown.flat();\n const [openAt, setOpenAt] = useState<number | null>(null);\n const open = openAt !== null;\n const rootRef = useRef<HTMLDivElement>(null);\n const buttonRef = useRef<HTMLButtonElement>(null);\n const itemRefs = useRef<(HTMLButtonElement | null)[]>([]);\n const menuId = useId();\n\n useEffect(() => {\n if (openAt !== null) itemRefs.current[openAt]?.focus();\n }, [openAt]);\n\n useEffect(() => {\n if (!open) return;\n const onDown = (e: MouseEvent) => {\n if (rootRef.current && !rootRef.current.contains(e.target as Node)) setOpenAt(null);\n };\n document.addEventListener(\"mousedown\", onDown);\n return () => document.removeEventListener(\"mousedown\", onDown);\n }, [open]);\n\n const close = () => {\n setOpenAt(null);\n buttonRef.current?.focus();\n };\n\n const focusItem = (i: number) => itemRefs.current[(i + items.length) % items.length]?.focus();\n\n const onItemKeyDown = (e: KeyboardEvent<HTMLButtonElement>, i: number) => {\n switch (e.key) {\n case \"ArrowDown\":\n e.preventDefault();\n focusItem(i + 1);\n break;\n case \"ArrowUp\":\n e.preventDefault();\n focusItem(i - 1);\n break;\n case \"Home\":\n e.preventDefault();\n focusItem(0);\n break;\n case \"End\":\n e.preventDefault();\n focusItem(items.length - 1);\n break;\n case \"Escape\":\n e.preventDefault();\n close();\n break;\n case \"Tab\":\n setOpenAt(null);\n break;\n }\n };\n\n let index = 0;\n return (\n <div className=\"doc-more-menu\" ref={rootRef}>\n <button\n ref={buttonRef}\n type=\"button\"\n className={`doc-more-button${open ? \" active\" : \"\"}`}\n title={busy ? `${busy}…` : label}\n aria-label={label}\n aria-haspopup=\"menu\"\n aria-expanded={open}\n aria-controls={open ? menuId : undefined}\n aria-busy={busy ? true : undefined}\n disabled={!!busy || items.length === 0}\n onClick={() => setOpenAt(open ? null : 0)}\n onKeyDown={(e) => {\n if (e.key === \"ArrowDown\") {\n e.preventDefault();\n setOpenAt(0);\n } else if (e.key === \"ArrowUp\") {\n e.preventDefault();\n setOpenAt(items.length - 1);\n } else if (e.key === \"Escape\" && open) {\n e.preventDefault();\n setOpenAt(null);\n }\n }}\n >\n {busy ? <span className=\"doc-more-busy\">{busy}…</span> : <MoreGlyph />}\n </button>\n {open && (\n <div className=\"doc-more-list\" role=\"menu\" id={menuId} aria-label={label}>\n {shown.map((group, g) => (\n <div className=\"doc-more-group\" role=\"group\" key={g}>\n {g > 0 && <div className=\"doc-more-rule\" role=\"separator\" />}\n {group.map((item) => {\n const i = index++;\n return (\n <button\n key={item.key}\n ref={(el) => {\n itemRefs.current[i] = el;\n }}\n type=\"button\"\n role=\"menuitem\"\n tabIndex={-1}\n className={item.danger ? \"danger\" : undefined}\n title={item.title}\n aria-disabled={item.disabled || undefined}\n data-key={item.key}\n onClick={() => {\n if (item.disabled) return;\n close();\n item.run();\n }}\n onKeyDown={(e) => onItemKeyDown(e, i)}\n >\n {item.label}\n </button>\n );\n })}\n </div>\n ))}\n </div>\n )}\n </div>\n );\n}\n\n// Three dots, drawn like the tree icons so it follows the theme.\nfunction MoreGlyph() {\n return (\n <svg width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" aria-hidden=\"true\" focusable=\"false\" fill=\"currentColor\">\n <circle cx=\"3.5\" cy=\"8\" r=\"1.4\" />\n <circle cx=\"8\" cy=\"8\" r=\"1.4\" />\n <circle cx=\"12.5\" cy=\"8\" r=\"1.4\" />\n </svg>\n );\n}\n","import type { ReactNode } from \"react\";\n\n// The collapsible panes' shared parts (RFC GZ). The Path tree, the chunk\n// outline and the side panel all collapse the same way: a labelled button on\n// the pane's edge, a double-click on the divider, a keyboard shortcut, and a\n// remembered state. A collapsed pane leaves a thin rail with its icon and a\n// count that opens it again.\n\nexport type PaneIconKind =\n | \"tree\"\n | \"outline\"\n | \"annotation\"\n | \"references\"\n | \"classification\"\n | \"history\"\n | \"search\"\n | \"collapse-left\"\n | \"collapse-right\"\n | \"close\";\n\n// PaneIcon draws the rail and header icons, stroke-only in currentColor like\n// the tree icons, at one size.\nexport function PaneIcon({ kind }: { kind: PaneIconKind }) {\n return (\n <svg\n className=\"pane-svg\"\n width=\"16\"\n height=\"16\"\n viewBox=\"0 0 16 16\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"1.4\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n aria-hidden=\"true\"\n focusable=\"false\"\n >\n {PANE_PATHS[kind]}\n </svg>\n );\n}\n\nconst PANE_PATHS: Record<PaneIconKind, ReactNode> = {\n tree: <path d=\"M1.75 4.25v8a1 1 0 0 0 1 1h10.5a1 1 0 0 0 1-1v-6.5a1 1 0 0 0-1-1H8L6.5 3.25H2.75a1 1 0 0 0-1 1z\" />,\n outline: <path d=\"M2.5 3.5h.01M5 3.5h8.5M4.5 8h.01M7 8h6.5M4.5 12.5h.01M7 12.5h6.5\" />,\n annotation: (\n <>\n <path d=\"M2.75 2.75h10.5v8h-6l-3 2.5v-2.5h-1.5z\" />\n <path d=\"M5.5 5.75h5M5.5 8h3\" />\n </>\n ),\n references: (\n <>\n <path d=\"M6.75 9.25a2.75 2.75 0 0 0 3.9 0l2-2a2.75 2.75 0 0 0-3.9-3.9l-.5.5\" />\n <path d=\"M9.25 6.75a2.75 2.75 0 0 0-3.9 0l-2 2a2.75 2.75 0 0 0 3.9 3.9l.5-.5\" />\n </>\n ),\n classification: (\n <>\n <path d=\"M8.5 1.75h5v5l-6.75 6.75-5-5z\" />\n <circle cx=\"11\" cy=\"4.25\" r=\"0.75\" />\n </>\n ),\n history: (\n <>\n <circle cx=\"8\" cy=\"8\" r=\"5.75\" />\n <path d=\"M8 5v3.25l2 1.25\" />\n </>\n ),\n search: (\n <>\n <circle cx=\"7\" cy=\"7\" r=\"4.25\" />\n <path d=\"M10.25 10.25l3.5 3.5\" />\n </>\n ),\n \"collapse-left\": <path d=\"M10 3.5L5.5 8l4.5 4.5\" />,\n \"collapse-right\": <path d=\"M6 3.5L10.5 8 6 12.5\" />,\n close: <path d=\"M4 4l8 8M12 4l-8 8\" />,\n};\n\n// CollapseButton hides a pane. `shortcut` is the key that does the same, in\n// the aria-keyshortcuts form.\nexport function CollapseButton({\n label,\n side,\n onClick,\n shortcut,\n}: {\n label: string;\n side: \"left\" | \"right\";\n onClick: () => void;\n shortcut?: string;\n}) {\n return (\n <button\n type=\"button\"\n className=\"pane-collapse\"\n onClick={onClick}\n aria-label={`Collapse the ${label}`}\n title={`Collapse the ${label}${shortcut ? ` (${shortcut})` : \"\"}`}\n aria-keyshortcuts={shortcut}\n >\n <PaneIcon kind={side === \"left\" ? \"collapse-left\" : \"collapse-right\"} />\n </button>\n );\n}\n\n// PaneRail is a collapsed pane: one button with the pane's icon and count.\n// A click opens it again.\nexport function PaneRail({\n label,\n icon,\n count,\n countLabel,\n onExpand,\n shortcut,\n side,\n}: {\n label: string;\n icon: PaneIconKind;\n // count shown under the icon; undefined shows none.\n count?: number;\n // countLabel names what is counted, for the button's label (\"chunks\").\n countLabel?: string;\n onExpand: () => void;\n shortcut?: string;\n side: \"left\" | \"right\";\n}) {\n const counted = count !== undefined && countLabel ? `, ${count} ${countLabel}` : \"\";\n return (\n <div className={`pane-rail pane-rail-${side}`}>\n <button\n type=\"button\"\n className=\"pane-rail-button\"\n onClick={onExpand}\n aria-label={`Show the ${label}${counted}`}\n title={`Show the ${label}${shortcut ? ` (${shortcut})` : \"\"}`}\n aria-keyshortcuts={shortcut}\n aria-expanded={false}\n >\n <PaneIcon kind={icon} />\n {count !== undefined && <span className=\"pane-rail-count\">{count}</span>}\n </button>\n </div>\n );\n}\n","import { useCallback, useState } from \"react\";\n\n// Per-browser layout memory (RFC GZ): which panes are collapsed and which side\n// panel is open, kept like the splitter widths. Storage can be missing or\n// refuse (a private window, a sandboxed host), so every read falls back to the\n// default and every write is best-effort.\n\nexport function readStored(key: string): string | null {\n try {\n return globalThis.localStorage?.getItem(key) ?? null;\n } catch {\n return null;\n }\n}\n\nexport function writeStored(key: string, value: string | null): void {\n try {\n if (value === null) globalThis.localStorage?.removeItem(key);\n else globalThis.localStorage?.setItem(key, value);\n } catch {\n // Not remembered; the layout still works for this visit.\n }\n}\n\n// usePersistedFlag is a boolean kept under `key` (\"1\" / \"0\").\nexport function usePersistedFlag(key: string, fallback = false): [boolean, (v: boolean | ((cur: boolean) => boolean)) => void] {\n const [value, setValue] = useState<boolean>(() => {\n const s = readStored(key);\n return s === null ? fallback : s === \"1\";\n });\n const set = useCallback(\n (v: boolean | ((cur: boolean) => boolean)) =>\n setValue((cur) => {\n const next = typeof v === \"function\" ? v(cur) : v;\n writeStored(key, next ? \"1\" : \"0\");\n return next;\n }),\n [key],\n );\n return [value, set];\n}\n\n// usePersistedChoice is one of `choices` (or null) kept under `key`; a stored\n// value that is no longer a choice reads as null.\nexport function usePersistedChoice<T extends string>(\n key: string,\n choices: readonly T[],\n): [T | null, (v: T | null | ((cur: T | null) => T | null)) => void] {\n const [value, setValue] = useState<T | null>(() => {\n const s = readStored(key);\n return s !== null && (choices as readonly string[]).includes(s) ? (s as T) : null;\n });\n const set = useCallback(\n (v: T | null | ((cur: T | null) => T | null)) =>\n setValue((cur) => {\n const next = typeof v === \"function\" ? v(cur) : v;\n writeStored(key, next);\n return next;\n }),\n [key],\n );\n return [value, set];\n}\n\n// isTypingTarget: a key pressed here is text, not a shortcut.\nexport function isTypingTarget(t: EventTarget | null): boolean {\n const el = t as HTMLElement | null;\n if (!el || !el.tagName) return false;\n const tag = el.tagName;\n return tag === \"INPUT\" || tag === \"TEXTAREA\" || tag === \"SELECT\" || el.isContentEditable === true;\n}\n\n// shortcutApplies: a page-level key belongs to this explorer when the focus is\n// inside it or nowhere in particular (the page body), never in a text field or\n// a dialog, and never with a modifier other than Shift.\nexport function shortcutApplies(e: KeyboardEvent, root: HTMLElement | null): boolean {\n if (e.defaultPrevented || e.ctrlKey || e.metaKey || e.altKey) return false;\n if (isTypingTarget(e.target)) return false;\n const t = e.target as Node | null;\n if (!root) return false;\n if (t && (t as HTMLElement).closest?.(\".modal-overlay\")) return false;\n return t === document.body || t === document.documentElement || (!!t && root.contains(t));\n}\n","import { useEffect, useState, type RefObject } from \"react\";\n\n// useNarrow reports whether the element is narrower than `below` px, and\n// follows it as it is resized. The explorer sizes itself to its host's slot,\n// not to the window, so this watches the element rather than a media query.\n// Without ResizeObserver (a test DOM) it reads the width once.\nexport function useNarrow(ref: RefObject<HTMLElement | null>, below: number): boolean {\n const [narrow, setNarrow] = useState(false);\n useEffect(() => {\n const el = ref.current;\n if (!el) return;\n const measure = (w: number) => setNarrow(w > 0 && w < below);\n measure(el.getBoundingClientRect().width);\n if (typeof ResizeObserver === \"undefined\") return;\n const ro = new ResizeObserver((entries) => {\n for (const e of entries) measure(e.contentRect.width);\n });\n ro.observe(el);\n return () => ro.disconnect();\n }, [ref, below]);\n return narrow;\n}\n","import { memo, useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from \"react\";\nimport type {\n Annotation,\n AnnotationLevel,\n AnnotationTarget,\n AssistantContext,\n BrowseScope,\n ChunkDetail,\n ChunkRow,\n DocEdge,\n DocScope,\n Principal,\n} from \"../types\";\nimport { readImageAsBase64, imageFileFromPaste } from \"../lib/imageUpload\";\nimport { useExplorerData } from \"../lib/dataLayer\";\nimport { loadDocumentEdges } from \"../lib/edgePages\";\nimport { landingChunk, type DocLocation } from \"../lib/docTrail\";\nimport { isSubjectRoot } from \"../lib/subjectType\";\nimport { bulkReviewScope, documentProposals, reviewPanel } from \"../lib/bulkReview\";\nimport { annotationLevelFor, annotationsApply, loadAnnotations } from \"../lib/annotation\";\nimport { pendingClassification } from \"../lib/classify\";\nimport { copyToClipboard } from \"../lib/clipboard\";\nimport { downloadEntries, runDownload, type DownloadKind } from \"../lib/documentDownload\";\nimport {\n docColor,\n effectiveScheme,\n statusDotColor,\n tintStyle,\n type DocumentMeta,\n} from \"../lib/colorScheme\";\nimport DocumentChunkTree, { buildChunkTree, type ChunkNode } from \"./DocumentChunkTree\";\nimport AnnotationPanel, { AnnotationBrief } from \"./AnnotationPanel\";\nimport ChunkEditorModal from \"./ChunkEditorModal\";\nimport SubjectTypeModal from \"./SubjectTypeModal\";\nimport Classification from \"./Classification\";\nimport ColorSchemeEditor from \"./ColorSchemeEditor\";\nimport Connections from \"./Connections\";\nimport CrossReferences from \"./CrossReferences\";\nimport DocUnavailable from \"./DocUnavailable\";\nimport HistoryModal, { HistoryView } from \"./HistoryModal\";\nimport Markdown from \"./Markdown\";\nimport MermaidDiagram from \"./Mermaid\";\nimport MoreMenu, { type MoreMenuItem } from \"./MoreMenu\";\nimport Splitter from \"./Splitter\";\nimport { TreeMarks } from \"./TreeRow\";\nimport { CollapseButton, PaneIcon, PaneRail, type PaneIconKind } from \"./Pane\";\nimport { CardScopeContext, useButtonCard, type CardScope, type CardSpec } from \"./AnnotationCard\";\nimport { shortcutApplies, usePersistedChoice, usePersistedFlag } from \"../lib/persisted\";\nimport { useNarrow } from \"../lib/useNarrow\";\n\n// imageAlt derives an image chunk's alt text: the fields.alt override, else the\n// chunk title, else a generic label (RFC BO).\nfunction imageAlt(chunk: ChunkDetail): string {\n const f = (chunk.fields ?? {}) as { alt?: unknown };\n if (typeof f.alt === \"string\" && f.alt.trim() !== \"\") return f.alt;\n return chunk.title || \"image\";\n}\n\n// DETAIL_BATCH is how many chunk bodies are read at once. The chunk list\n// carries no bodies, so the page reads each chunk; a batch keeps a long\n// document from opening hundreds of requests at a time, and in document order\n// the text at the top arrives first.\nconst DETAIL_BATCH = 8;\n\n// DocumentViewerBody is the reading-first view of one chunked-graph document\n// (RFC AK, laid out by RFC GZ): one header line (path, title, marks, edit and a\n// \"more\" menu), the chunk outline on the left, and the whole document on the\n// right as one scrolling page — every chunk in order, headed by its depth.\n// Picking a chunk in the outline scrolls the page to it; scrolling moves the\n// outline's current row. Each chunk carries its own action bar (on hover or\n// keyboard focus).\n//\n// The annotation, references, classification and history panels open one at a\n// time beside the body, from a rail of icons at its right edge that shows a\n// count or a dot for each. The outline collapses to a rail of its own.\n//\n// This is the context-consuming body: it reads the injected ExplorerDataLayer\n// via useExplorerData() and is embedded by both the standalone <DocumentViewer>\n// root and the <PathExplorer> tree — neither re-wraps it in a data provider.\nexport interface DocumentViewerBodyProps {\n documentId: string;\n scope: DocScope;\n // titleHint shows immediately (e.g. the Path-tree name) until the root chunk\n // title loads.\n titleHint?: string;\n // browse (RFC AS) selects whose subject's document to read — threaded into the\n // off-run document calls. Unset → the caller's own subject (default).\n browse?: BrowseScope;\n // principal — only `subject` is read; passed into the renderAssistant context.\n principal?: Principal;\n // renderAssistant — an OPTIONAL host-provided Document Assistant slot. When\n // provided, an \"assistant\" entry appears in the menu and this renders into the\n // panel; when omitted, no assistant affordance is shown. The host owns the\n // run: it reads {documentId, scope, subject}.\n renderAssistant?: (ctx: AssistantContext) => ReactNode;\n // initialChunkId — the chunk to land on instead of the root, for a document\n // opened AT a chunk (a followed reference, or a return along the trail). It is\n // read when the document loads; the host remounts the body to land again.\n initialChunkId?: string;\n // onOpenDocument — the host's \"leave this document\" handler. `target` is the\n // referenced document + chunk; `from` is this document as the reader leaves it\n // (the current chunk and the loaded title), which is what a way back needs.\n // Omitted → cross-document targets are labels only.\n onOpenDocument?: (target: DocLocation, from: DocLocation) => void;\n // onTitle reports this document's title once its root chunk has loaded, so a\n // host that opened it by id can name it.\n onTitle?: (documentId: string, title: string) => void;\n // onChunkSelect reports the chunk the reader is on as it changes (undefined =\n // the document's root) — picked or scrolled to — so a host navigator can\n // follow it.\n onChunkSelect?: (chunkId: string | undefined) => void;\n // focusChunk moves to a chunk inside the mounted document without a remount:\n // each new `seq` scrolls to `chunkId` (absent = the root). A host navigator\n // uses it when the reader picks another chunk of the open document.\n focusChunk?: { chunkId?: string; seq: number };\n // onRegenerateAnnotation — the host's way to have an annotation written again\n // (it owns the run). Omitted → no Regenerate. Its promise settling reloads the\n // annotation; a rejection is shown in the panel.\n onRegenerateAnnotation?: (target: AnnotationTarget) => void | Promise<void>;\n // canEditAnnotations — whether to offer Edit (the operator plane writes\n // annotations by hand; the runtime refuses anyone else). Default false.\n canEditAnnotations?: boolean;\n // onAnnotationChanged — told after an edit or a regenerate settles, so a host\n // showing briefs elsewhere (the Path tree) can read them again.\n onAnnotationChanged?: () => void;\n // pathLabel — where the document sits, shown first in the header line (the\n // Path console passes the path). Omitted → the header starts with the title.\n pathLabel?: ReactNode;\n // documentActions — the host's actions on the document's Path entry, listed\n // in the \"more\" menu. Each is offered only when given.\n documentActions?: {\n rename?: () => void;\n transfer?: () => void;\n delete?: () => void;\n };\n}\n\n// The side panels (RFC GZ): one open at a time, closed by default, the choice\n// remembered per browser.\ntype Panel = \"annotation\" | \"references\" | \"classification\" | \"history\";\nconst PANELS: readonly Panel[] = [\"annotation\", \"references\", \"classification\", \"history\"];\nconst PANEL_LABEL: Record<Panel, string> = {\n annotation: \"annotation\",\n references: \"references\",\n classification: \"classification\",\n history: \"history\",\n};\n\n// Where the layout is remembered, beside the splitter widths.\nconst PANEL_KEY = \"loomcycle.explorer.panel\";\nconst OUTLINE_KEY = \"loomcycle.explorer.collapsed.outline\";\n// Below this width the outline folds to its rail and a side panel overlays\n// the body instead of pushing it.\nconst NARROW_PX = 640;\n// Below this width an open side panel lies over the body: pushing it would\n// leave the text too little room to read. The open outline takes its own\n// share first, so with it showing the panel needs a wider viewer to sit beside\n// the body.\nconst OVERLAY_PX = 960;\nconst OVERLAY_WITH_OUTLINE_PX = 1200;\n\nexport default function DocumentViewerBody({\n documentId,\n scope,\n titleHint,\n browse: browseProp,\n principal,\n renderAssistant,\n initialChunkId,\n onOpenDocument,\n onTitle,\n onChunkSelect,\n focusChunk,\n onRegenerateAnnotation,\n canEditAnnotations,\n onAnnotationChanged,\n pathLabel,\n documentActions,\n}: DocumentViewerBodyProps) {\n const data = useExplorerData();\n\n // Memoize browse on its primitives so a parent passing an inline object\n // literal (`browse={{scopeId}}`) doesn't churn the fetch effects every render.\n const browse = useMemo<BrowseScope | undefined>(\n () =>\n browseProp && (browseProp.scopeId || browseProp.tenant)\n ? { scopeId: browseProp.scopeId, tenant: browseProp.tenant }\n : undefined,\n [browseProp?.scopeId, browseProp?.tenant],\n );\n\n const [chunks, setChunks] = useState<ChunkRow[]>([]);\n // selectedId is the chunk the reader is on: picked in the outline, scrolled\n // to, or landed on. Chunk actions in the menu act on it.\n const [selectedId, setSelectedId] = useState<string | undefined>(undefined);\n // Every chunk's body, by id, read after the list (which carries none). A\n // chunk is read again only when its revision moves.\n const [details, setDetails] = useState<Map<string, ChunkDetail>>(() => new Map());\n const [detailErrs, setDetailErrs] = useState<Map<string, string>>(() => new Map());\n // The chunks whose Markdown source is shown in place of the rendered text.\n const [sourceOpen, setSourceOpen] = useState<Set<string>>(() => new Set());\n const fileInputRef = useRef<HTMLInputElement>(null); // hidden upload input (RFC BO)\n const [editing, setEditing] = useState<ChunkDetail | null>(null);\n const [retyping, setRetyping] = useState<ChunkDetail | null>(null);\n const [historyFor, setHistoryFor] = useState<ChunkDetail | null>(null); // RFC BS chunk history\n const [confirmDelete, setConfirmDelete] = useState(false); // RFC BP delete confirm\n const [err, setErr] = useState<string | null>(null);\n const [loading, setLoading] = useState(false);\n // Which document the chunk list on hand belongs to, and why a load failed —\n // together they tell \"still loading\" from \"cannot be read\".\n const [loadedFor, setLoadedFor] = useState<string | undefined>(undefined);\n const [loadErr, setLoadErr] = useState<string | null>(null);\n const [reload, setReload] = useState(0);\n const [assistantOpen, setAssistantOpen] = useState(false);\n const [meta, setMeta] = useState<DocumentMeta | null>(null);\n const [colorsOpen, setColorsOpen] = useState(false);\n const [edges, setEdges] = useState<DocEdge[]>([]);\n // The edge load stopped before the end of the list (its page cap).\n const [edgesIncomplete, setEdgesIncomplete] = useState(false);\n // Bumped after an operator rules on a proposed statement: refetches the edges\n // (and an open Connections panel) without reloading the whole document.\n const [edgesReload, setEdgesReload] = useState(0);\n // RFC FO — the Classify report: non-zero while requested (each change runs a\n // fresh report), 0 closed. rootFields is the root chunk's fields, where a\n // pending classification waits.\n const [classifyKey, setClassifyKey] = useState(0);\n const [rootFields, setRootFields] = useState<unknown>(undefined);\n // The annotations of the document (its root chunk's records) and of the\n // current chunk when that is not the root. Tenant scope only; otherwise\n // they stay empty and nothing is fetched.\n const [docAnnotations, setDocAnnotations] = useState<Annotation[]>([]);\n const [chunkAnnotations, setChunkAnnotations] = useState<Annotation[]>([]);\n const [annotationReload, setAnnotationReload] = useState(0);\n const [panel, setPanelStored] = usePersistedChoice<Panel>(PANEL_KEY, PANELS);\n // Whether the reader has opened or closed a panel on this visit. A panel\n // only remembered from an earlier visit is not reopened over the body.\n // State, not a ref: picking the remembered panel leaves the stored choice\n // unchanged, and the view must still redraw to show it.\n const [panelTouched, setPanelTouched] = useState(false);\n const setPanel = useCallback(\n (v: Panel | null | ((cur: Panel | null) => Panel | null)) => {\n setPanelTouched(true);\n setPanelStored(v);\n },\n [setPanelStored],\n );\n const [outlineCollapsed, setOutlineCollapsed] = usePersistedFlag(OUTLINE_KEY);\n // On a narrow body the outline is a rail unless the reader opens it, and\n // then it takes the width until a chunk is picked.\n const viewerRef = useRef<HTMLDivElement>(null);\n const narrow = useNarrow(viewerRef, NARROW_PX);\n const [narrowOutline, setNarrowOutline] = useState(false);\n const outlineHidden = narrow ? !narrowOutline : outlineCollapsed;\n const overlay = useNarrow(viewerRef, outlineHidden ? OVERLAY_PX : OVERLAY_WITH_OUTLINE_PX);\n const setOutlineHidden = useCallback(\n (hide: boolean) => (narrow ? setNarrowOutline(!hide) : setOutlineCollapsed(hide)),\n [narrow, setOutlineCollapsed],\n );\n const [downloading, setDownloading] = useState<string | undefined>(undefined);\n const [copied, setCopied] = useState<string | null>(null);\n\n const refresh = useCallback(() => setReload((n) => n + 1), []);\n // A reload the reader asked for reads every body again, not only the ones\n // whose revision moved.\n const hardReload = useCallback(() => {\n setDetails(new Map());\n setDetailErrs(new Map());\n setReload((n) => n + 1);\n }, []);\n\n // Host callbacks + the landing chunk through refs: none of them should re-run\n // a fetch effect when a host passes a fresh closure each render.\n const initialChunkRef = useRef(initialChunkId);\n initialChunkRef.current = initialChunkId;\n const onTitleRef = useRef(onTitle);\n onTitleRef.current = onTitle;\n\n // The page scroller, and the chunk the page is held on: set when the reader\n // picks a chunk (or lands on one), it is scrolled to — again as the text above\n // it loads and moves it — until the reader scrolls the page themselves.\n const pageRef = useRef<HTMLDivElement>(null);\n const pinRef = useRef<string | null>(null);\n // Where the page was last scrolled to on the pin's behalf: a scroll that\n // ends anywhere else came from the reader (or a script), whatever moved it.\n const pinnedTop = useRef<number | null>(null);\n const [pinSeq, setPinSeq] = useState(0);\n const goTo = useCallback((id: string | undefined) => {\n if (!id) return;\n pinRef.current = id;\n setSelectedId(id);\n setPinSeq((n) => n + 1);\n // On a narrow body the outline was laid over the page to pick from.\n setNarrowOutline(false);\n }, []);\n\n const tree = useMemo(() => buildChunkTree(chunks), [chunks]);\n // The page order: the outline walked depth first.\n const flat = useMemo(() => {\n const out: { row: ChunkRow; depth: number }[] = [];\n const walk = (nodes: ChunkNode[], depth: number) =>\n nodes.forEach((n) => {\n out.push({ row: n.row, depth });\n walk(n.children, depth + 1);\n });\n walk(tree, 0);\n return out;\n }, [tree]);\n const rootTitle = useMemo(() => {\n const root = chunks.find((c) => !c.parent_id);\n return root?.title || titleHint || \"document\";\n }, [chunks, titleHint]);\n const selectedDetail = (selectedId && details.get(selectedId)) || null;\n\n // Color (RFC BN). rootChunkId comes from the meta (or the loaded root chunk);\n // chunkStatuses seeds the editor's per-status pickers; the header tints to the\n // document's own doc.<type>.<status> color when coloring is enabled.\n const rootChunkId = useMemo(\n () => meta?.root_chunk_id ?? chunks.find((c) => !c.parent_id)?.id,\n [meta, chunks],\n );\n const rootDetail = (rootChunkId && details.get(rootChunkId)) || null;\n // Report the chunk the reader is on; the root reads as the document itself.\n const onChunkSelectRef = useRef(onChunkSelect);\n onChunkSelectRef.current = onChunkSelect;\n useEffect(() => {\n if (!selectedId) return;\n onChunkSelectRef.current?.(selectedId === rootChunkId ? undefined : selectedId);\n }, [selectedId, rootChunkId]);\n\n const chunkStatuses = useMemo(\n () => [...new Set(chunks.map((c) => c.status).filter((s): s is string => !!s))],\n [chunks],\n );\n const colorEnabled = !!meta?.color_enabled;\n const tintScheme = colorEnabled ? effectiveScheme(meta?.color_scheme) : undefined;\n // Chunk ids with at least one edge → a link mark on those outline rows.\n const linkedIds = useMemo(() => {\n const s = new Set<string>();\n for (const e of edges) {\n s.add(e.from_id);\n s.add(e.to_id);\n }\n return s;\n }, [edges]);\n // The document's own colour: the header's tint, the root row's in the chunk\n // outline, and the wash a chunk without a status colour inherits.\n const documentColor = useMemo(\n () => (colorEnabled ? docColor(meta?.type, meta?.status, effectiveScheme(meta?.color_scheme)) : undefined),\n [colorEnabled, meta?.type, meta?.status, meta?.color_scheme],\n );\n const headerTint = useMemo(() => tintStyle(documentColor), [documentColor]);\n // The document's type and status: from its meta, else its root chunk.\n const rootRow = useMemo(() => chunks.find((c) => !c.parent_id), [chunks]);\n const docType = meta?.type ?? rootRow?.type;\n const docStatus = meta?.status ?? rootRow?.status;\n\n // Load the chunk list when the document / scope / reload changes. Default the\n // selection to the landing chunk.\n const selectedIdRef = useRef(selectedId);\n selectedIdRef.current = selectedId;\n useEffect(() => {\n let cancelled = false;\n setLoading(true);\n setErr(null);\n setLoadErr(null);\n data\n .documentQueryChunks(documentId, scope, browse)\n .then((resp) => {\n if (cancelled) return;\n const rows = resp.chunks ?? [];\n setChunks(rows);\n setLoadedFor(`${scope}:${documentId}`);\n if (pinRef.current === null && !selectedIdRef.current) goTo(landingChunk(rows, initialChunkRef.current));\n })\n .catch((e) => {\n if (cancelled) return;\n // Drop the previous document's chunks: a failed load must not leave them\n // on screen under the new document's name.\n setChunks([]);\n setLoadErr(e instanceof Error ? e.message : String(e));\n })\n .finally(() => !cancelled && setLoading(false));\n return () => {\n cancelled = true;\n };\n }, [data, documentId, scope, reload, browse, goTo]);\n\n // Read the bodies the page does not have yet, or whose revision moved, in\n // document order and a batch at a time.\n const detailsRef = useRef(details);\n detailsRef.current = details;\n useEffect(() => {\n const want = flat\n .map((f) => f.row)\n .filter((r) => r.document_id === documentId && detailsRef.current.get(r.id)?.revision !== r.revision);\n if (want.length === 0) return;\n let cancelled = false;\n (async () => {\n for (let i = 0; i < want.length && !cancelled; i += DETAIL_BATCH) {\n const batch = want.slice(i, i + DETAIL_BATCH);\n const got = await Promise.allSettled(batch.map((r) => data.documentGetChunk(r.id, scope, browse)));\n if (cancelled) return;\n setDetails((prev) => {\n const next = new Map(prev);\n got.forEach((g, k) => g.status === \"fulfilled\" && next.set(batch[k].id, g.value));\n return next;\n });\n setDetailErrs((prev) => {\n const next = new Map(prev);\n got.forEach((g, k) => {\n if (g.status === \"rejected\") {\n next.set(batch[k].id, g.reason instanceof Error ? g.reason.message : String(g.reason));\n } else next.delete(batch[k].id);\n });\n return next;\n });\n }\n })();\n return () => {\n cancelled = true;\n };\n }, [data, flat, documentId, scope, browse]);\n\n // A document always has a root chunk, so a load that failed — or answered with\n // no chunks at all — is a document that is not there to read (deleted, another\n // scope, no access). Said in place rather than left as an empty pane.\n const unavailable =\n !loading &&\n (loadErr !== null || (loadedFor === `${scope}:${documentId}` && chunks.length === 0));\n\n // Report the title once THIS document's root chunk is on hand (the list still\n // holds the previous document's rows until the new load lands).\n const loadedTitle = useMemo(\n () => chunks.find((c) => !c.parent_id && c.document_id === documentId)?.title,\n [chunks, documentId],\n );\n useEffect(() => {\n if (loadedTitle) onTitleRef.current?.(documentId, loadedTitle);\n }, [documentId, loadedTitle]);\n\n // Load the document's color metadata (RFC BN) alongside the chunk list. It\n // drives the outline tint, the header tint and marks, and seeds the color\n // editor. Best-effort — a failure just leaves the document uncolored.\n useEffect(() => {\n let cancelled = false;\n data\n .documentGet(documentId, scope, browse)\n .then((m) => !cancelled && setMeta(m))\n .catch(() => !cancelled && setMeta(null));\n return () => {\n cancelled = true;\n };\n }, [data, documentId, scope, reload, browse]);\n\n // Load the cross-reference edges (RFC BN P4), every page up to the cap —\n // powers the outline's link marks, the References list, and the relationship\n // graph. Best-effort.\n useEffect(() => {\n let cancelled = false;\n loadDocumentEdges(data, documentId, scope, browse)\n .then((r) => {\n if (cancelled) return;\n setEdges(r.edges);\n setEdgesIncomplete(r.incomplete);\n })\n .catch(() => {\n if (cancelled) return;\n setEdges([]);\n setEdgesIncomplete(false);\n });\n return () => {\n cancelled = true;\n };\n }, [data, documentId, scope, reload, browse, edgesReload]);\n\n // RFC FO — the root chunk's fields, for the pending-classification block. The\n // chunk list carries no fields; the root's body read above does. Only when\n // the data layer can accept a classification (nothing to act on otherwise).\n useEffect(() => {\n if (!data.documentAcceptClassification || !rootDetail || rootDetail.document_id !== documentId) {\n setRootFields(undefined);\n return;\n }\n setRootFields(rootDetail.fields);\n }, [data, documentId, rootDetail]);\n // How many classification items wait for a ruling: the proposed type, each\n // proposed tag, each proposed statement. 0 → nothing pending.\n const pendingCount = useMemo(() => {\n if (!data.documentAcceptClassification) return 0;\n const p = pendingClassification(rootFields);\n return p ? (p.proposedType ? 1 : 0) + p.proposedTags.length + p.statementCount : 0;\n }, [data, rootFields]);\n const classificationPending = pendingCount > 0;\n\n // The document's annotation, read from its root chunk. Best-effort: a failed\n // read shows no annotation rather than an error over the document.\n useEffect(() => {\n if (!rootChunkId || !annotationsApply(scope)) {\n setDocAnnotations([]);\n return;\n }\n let cancelled = false;\n loadAnnotations(data, rootChunkId, scope, browse)\n .then((r) => !cancelled && setDocAnnotations(r))\n .catch(() => !cancelled && setDocAnnotations([]));\n return () => {\n cancelled = true;\n };\n }, [data, rootChunkId, scope, reload, browse, annotationReload]);\n\n // The current chunk's own branch annotation (the root's is the document's,\n // above) — read only while the annotation panel is open, since the current\n // chunk moves as the reader scrolls.\n const annotationOpen = panel === \"annotation\";\n useEffect(() => {\n if (!annotationOpen || !selectedId || selectedId === rootChunkId || !annotationsApply(scope)) {\n setChunkAnnotations([]);\n return;\n }\n let cancelled = false;\n setChunkAnnotations([]);\n loadAnnotations(data, selectedId, scope, browse)\n .then((r) => !cancelled && setChunkAnnotations(r))\n .catch(() => !cancelled && setChunkAnnotations([]));\n return () => {\n cancelled = true;\n };\n }, [data, annotationOpen, selectedId, rootChunkId, scope, reload, browse, annotationReload]);\n\n // Edit and Regenerate. Edit needs a data layer that can write one; Regenerate\n // needs the host's callback. Neither is offered outside the tenant scope.\n const saveAnnotation = useMemo(() => {\n if (!canEditAnnotations || !data.documentSetAnnotation || !annotationsApply(scope)) return undefined;\n return (chunkId: string) => async (level: AnnotationLevel, brief: string, abstract: string) => {\n await data.documentSetAnnotation!({ id: chunkId, level, brief, abstract }, scope, browse);\n setAnnotationReload((n) => n + 1);\n onAnnotationChanged?.();\n };\n }, [data, scope, browse, canEditAnnotations, onAnnotationChanged]);\n const regenerateAnnotation = useMemo(() => {\n if (!onRegenerateAnnotation || !annotationsApply(scope)) return undefined;\n return (chunkId: string) => async (level: AnnotationLevel) => {\n // A folder's record names its folder: that, not this document, is what a\n // path-level Regenerate rewrites.\n const folder = [...docAnnotations, ...chunkAnnotations].find(\n (a) => a.chunk_id === chunkId && a.level === level,\n )?.folder;\n try {\n await onRegenerateAnnotation({ documentId, chunkId, level, scope, ...(folder ? { folder } : {}) });\n } finally {\n setAnnotationReload((n) => n + 1);\n onAnnotationChanged?.();\n }\n };\n }, [onRegenerateAnnotation, documentId, scope, docAnnotations, chunkAnnotations, onAnnotationChanged]);\n // The document's brief is the document record's; a path record on the same\n // root describes the folder. A folder's _annotation document has only the\n // path record: that is its brief.\n const documentBrief =\n docAnnotations.find((a) => a.level === \"document\") ?? docAnnotations.find((a) => a.level === \"path\");\n // The current chunk's records, matched by id: the list can still be the\n // previous chunk's for a moment after the reader moves on.\n const selectedAnnotations = useMemo(\n () => chunkAnnotations.filter((a) => a.chunk_id === selectedId),\n [chunkAnnotations, selectedId],\n );\n const annotationOffered =\n !!rootChunkId && (docAnnotations.length > 0 || !!saveAnnotation || !!regenerateAnnotation);\n\n // RFC FN — the operator's ruling on a proposed statement. Offered only when the\n // data layer implements both rulings (they are optional on a custom one). A\n // refusal propagates to the row, which shows it inline.\n // Called through `data` (not detached) so a class-based data layer keeps `this`.\n const ruleStatement = useMemo(() => {\n if (!data.documentAcceptStatement || !data.documentRejectStatement) return undefined;\n return async (id: string, ok: boolean, reason?: string) => {\n if (ok) await data.documentAcceptStatement!(id, scope, browse, reason);\n else await data.documentRejectStatement!(id, reason ?? \"\", scope, browse);\n setEdgesReload((n) => n + 1);\n };\n }, [data, scope, browse]);\n\n // RFC FS — bulk review of this document's proposals in the Connections panel:\n // offered when the data layer can rule in bulk and the review routes reach\n // this document's scope (reviewPanel).\n const reviewScope = useMemo(() => bulkReviewScope(data, scope), [data, scope]);\n const proposals = useMemo(() => documentProposals(edges, documentId), [edges, documentId]);\n const onReviewChanged = useCallback(() => setEdgesReload((n) => n + 1), []);\n const review = useMemo(\n () => reviewPanel(reviewScope, proposals, edgesIncomplete, onReviewChanged),\n [reviewScope, proposals, edgesIncomplete, onReviewChanged],\n );\n // The references of the current chunk: what its panel toggle counts.\n const refCount = useMemo(\n () => (selectedId ? edges.filter((e) => e.from_id === selectedId || e.to_id === selectedId).length : 0),\n [edges, selectedId],\n );\n\n // A host's focus request for the open document. Declared before the reset\n // below on purpose: on a document change the reset runs after it and the\n // landing chunk (initialChunkId) decides instead.\n const focusSeq = focusChunk?.seq;\n const focusRef = useRef(focusChunk);\n focusRef.current = focusChunk;\n const rootRef = useRef(rootChunkId);\n rootRef.current = rootChunkId;\n const chunksRef = useRef(chunks);\n chunksRef.current = chunks;\n useEffect(() => {\n if (focusSeq === undefined) return;\n const wanted = focusRef.current?.chunkId;\n // Once the chunk list is in, an id that is not one of this document's\n // chunks (another document's, a deleted one) lands on the root rather than\n // selecting nothing; before it is in, the request is taken as given.\n const target =\n chunksRef.current.length > 0 ? landingChunk(chunksRef.current, wanted) : (wanted ?? rootRef.current);\n goTo(target);\n }, [focusSeq, goTo]);\n\n // Reset the view when the document changes.\n useEffect(() => {\n pinRef.current = null;\n setSelectedId(undefined);\n setDetails(new Map());\n setDetailErrs(new Map());\n setSourceOpen(new Set());\n setMeta(null);\n setEdges([]);\n setEdgesIncomplete(false);\n setClassifyKey(0);\n setRootFields(undefined);\n setDocAnnotations([]);\n setChunkAnnotations([]);\n }, [documentId, scope]);\n\n // Scroll the page to the held chunk — on a pick, and again as the bodies\n // above it arrive and push it down. Instant, so the outline and the page\n // never disagree for the length of an animation.\n useEffect(() => {\n const page = pageRef.current;\n const id = pinRef.current;\n if (!page || !id) return;\n const el = page.querySelector<HTMLElement>(`[data-chunk-id=\"${id}\"]`);\n if (!el) return;\n const top = el.getBoundingClientRect().top - page.getBoundingClientRect().top + page.scrollTop;\n page.scrollTop = Math.max(0, top - 8);\n pinnedTop.current = page.scrollTop;\n }, [pinSeq, details, flat]);\n\n // The reader's own scrolling lets go of the held chunk; from then on the\n // chunk at the top of the page is the current one. Wheel, touch, keys and\n // a press say so at once; a scroll that fires none of them (a scrollbar\n // drag, a host's script) says so by ending somewhere the pin did not put the\n // page. The pin's own scroll lands where it was told, so it never lets go of\n // itself.\n useEffect(() => {\n const page = pageRef.current;\n if (!page) return;\n const release = () => {\n pinRef.current = null;\n pinnedTop.current = null;\n };\n const onScroll = () => {\n if (pinRef.current === null) return;\n const at = pinnedTop.current;\n if (at === null || Math.abs(page.scrollTop - at) > 2) {\n release();\n followRef.current(); // the outline takes up the reading position\n }\n };\n const opts = { passive: true } as const;\n page.addEventListener(\"wheel\", release, opts);\n page.addEventListener(\"touchstart\", release, opts);\n page.addEventListener(\"keydown\", release);\n page.addEventListener(\"pointerdown\", release);\n page.addEventListener(\"scroll\", onScroll, opts);\n return () => {\n page.removeEventListener(\"wheel\", release);\n page.removeEventListener(\"touchstart\", release);\n page.removeEventListener(\"keydown\", release);\n page.removeEventListener(\"pointerdown\", release);\n page.removeEventListener(\"scroll\", onScroll);\n };\n }, [unavailable]);\n\n // The outline follows the reading position: the current chunk is the first\n // whose section crosses the top third of the page. One observer for every\n // section, so a long document costs nothing while it is not scrolled.\n // followRef recomputes the current chunk from what the observer last saw —\n // for a pin let go by a scroll that crossed no section boundary.\n const followRef = useRef<() => void>(() => {});\n useEffect(() => {\n const page = pageRef.current;\n if (!page || typeof IntersectionObserver === \"undefined\" || flat.length === 0) return;\n const order = new Map(flat.map((f, i) => [f.row.id, i]));\n const visible = new Set<string>();\n const follow = () => {\n if (pinRef.current) return;\n let best: string | undefined;\n for (const id of visible) if (best === undefined || order.get(id)! < order.get(best)!) best = id;\n if (best) setSelectedId((cur) => (cur === best ? cur : best));\n };\n followRef.current = follow;\n const io = new IntersectionObserver(\n (entries) => {\n for (const e of entries) {\n const id = (e.target as HTMLElement).dataset.chunkId;\n if (!id) continue;\n if (e.isIntersecting) visible.add(id);\n else visible.delete(id);\n }\n follow();\n },\n { root: page, rootMargin: \"0px 0px -66% 0px\", threshold: 0 },\n );\n page.querySelectorAll<HTMLElement>(\"[data-chunk-id]\").forEach((el) => io.observe(el));\n return () => {\n io.disconnect();\n followRef.current = () => {};\n };\n }, [flat]);\n\n const onSelect = useCallback((n: ChunkNode) => goTo(n.row.id), [goTo]);\n\n // Leaving for another document: hand the host the target and a snapshot of\n // where the reader is now. The target's title is the CHUNK's — a stand-in until\n // that document loads and reports its own.\n const openDocument = useCallback(\n (targetDocumentId: string, chunkId: string, title?: string) =>\n onOpenDocument?.(\n { documentId: targetDocumentId, chunkId, title },\n { documentId, chunkId: selectedId, title: rootTitle },\n ),\n [onOpenDocument, documentId, selectedId, rootTitle],\n );\n\n // RFC BO authoring — create a media chunk under the current chunk (or the\n // root). The runtime marks type=image via set_asset; a diagram is a plain\n // type=mermaid chunk whose body is the source.\n const canCreate = !!data.documentCreateChunk && !!rootChunkId;\n const addImageFile = useCallback(\n async (file: File) => {\n if (!data.documentCreateChunk || !data.documentSetAsset) return;\n const parent = selectedId || rootChunkId;\n if (!parent) return;\n setErr(null);\n try {\n const { mediaType, data: b64 } = await readImageAsBase64(file);\n const created = await data.documentCreateChunk(\n documentId,\n parent,\n { title: file.name || \"image\", type: \"image\" },\n scope,\n browse,\n );\n await data.documentSetAsset(created.id, mediaType, b64, file.name, scope, browse);\n refresh();\n goTo(created.id);\n } catch (e) {\n setErr(e instanceof Error ? e.message : String(e));\n }\n },\n [data, documentId, scope, browse, selectedId, rootChunkId, refresh, goTo],\n );\n const addDiagram = useCallback(async () => {\n if (!data.documentCreateChunk) return;\n const parent = selectedId || rootChunkId;\n if (!parent) return;\n setErr(null);\n try {\n const created = await data.documentCreateChunk(\n documentId,\n parent,\n { title: \"Diagram\", type: \"mermaid\", body: \"graph TD\\n A[Start] --> B[End]\" },\n scope,\n browse,\n );\n refresh();\n goTo(created.id);\n setEditing(created); // open the editor (with live preview) on the new diagram\n } catch (e) {\n setErr(e instanceof Error ? e.message : String(e));\n }\n }, [data, documentId, scope, browse, selectedId, rootChunkId, refresh, goTo]);\n\n // RFC BP — \"add text\": a plain text chunk immediately AFTER the current chunk\n // (via after_id) when a non-root chunk is current; otherwise appended under\n // the root. Opens the editor on the new chunk.\n const currentIsRoot = !!selectedId && selectedId === rootChunkId;\n const addText = useCallback(async () => {\n if (!data.documentCreateChunk) return;\n const insertAfter = selectedId && !currentIsRoot ? selectedId : undefined;\n const parent = selectedId || rootChunkId;\n if (!parent) return;\n setErr(null);\n try {\n const created = await data.documentCreateChunk(\n documentId,\n insertAfter ? \"\" : parent, // after_id resolves the parent server-side\n { title: \"Text\", body: \"\" },\n scope,\n browse,\n insertAfter,\n );\n refresh();\n goTo(created.id);\n setEditing(created);\n } catch (e) {\n setErr(e instanceof Error ? e.message : String(e));\n }\n }, [data, documentId, scope, browse, selectedId, currentIsRoot, rootChunkId, refresh, goTo]);\n\n // \"add child\": a chunk NESTED UNDER the current one.\n //\n // \"add text\" inserts a SIBLING (after_id), which is right for prose flow and\n // wrong for structure — without this a document's hierarchy could only be\n // created by import_md or by an agent, which left the ontology's subclasses (a\n // child chunk is a subclass) unauthorable by the operator who owns them.\n //\n // Passing parent_id with no after_id appends it as the current chunk's last child.\n const addChild = useCallback(async () => {\n if (!data.documentCreateChunk || !selectedId) return;\n setErr(null);\n try {\n const created = await data.documentCreateChunk(\n documentId,\n selectedId,\n { title: \"Text\", body: \"\" },\n scope,\n browse,\n );\n refresh();\n goTo(created.id);\n setEditing(created);\n } catch (e) {\n setErr(e instanceof Error ? e.message : String(e));\n }\n }, [data, documentId, scope, browse, selectedId, refresh, goTo]);\n\n // RFC BP — the current chunk's siblings (same parent) in position order, to\n // gate move up / down at the level boundaries.\n const siblingBounds = useMemo(() => {\n const row = chunks.find((c) => c.id === selectedId);\n if (!row || !row.parent_id) return { canUp: false, canDown: false };\n const sibs = chunks\n .filter((c) => (c.parent_id ?? \"\") === row.parent_id)\n .sort((a, b) => a.position - b.position || a.id.localeCompare(b.id));\n const i = sibs.findIndex((c) => c.id === row.id);\n return { canUp: i > 0, canDown: i >= 0 && i < sibs.length - 1 };\n }, [chunks, selectedId]);\n\n const reorderSelected = useCallback(\n async (direction: \"up\" | \"down\") => {\n if (!data.documentReorderChunk || !selectedId) return;\n setErr(null);\n try {\n await data.documentReorderChunk(selectedId, direction, scope, browse);\n refresh();\n goTo(selectedId);\n } catch (e) {\n setErr(e instanceof Error ? e.message : String(e));\n }\n },\n [data, selectedId, scope, browse, refresh, goTo],\n );\n\n const deleteSelected = useCallback(async () => {\n if (!data.documentDeleteChunk || !selectedDetail) return;\n setErr(null);\n const parentId = selectedDetail.parent_id;\n try {\n await data.documentDeleteChunk(selectedDetail.id, scope, browse);\n setConfirmDelete(false);\n goTo(parentId || rootChunkId);\n refresh();\n } catch (e) {\n setErr(e instanceof Error ? e.message : String(e));\n setConfirmDelete(false);\n }\n }, [data, selectedDetail, scope, browse, rootChunkId, refresh, goTo]);\n\n // Paste a screenshot anywhere in the viewer → a new image chunk. Ignored while\n // a modal or a text field is focused (so an editor paste isn't hijacked).\n useEffect(() => {\n if (!canCreate) return;\n const onPaste = (e: ClipboardEvent) => {\n if (editing || colorsOpen) return;\n const ae = document.activeElement;\n const tag = ae?.tagName;\n if (tag === \"INPUT\" || tag === \"TEXTAREA\" || (ae as HTMLElement)?.isContentEditable) return;\n const file = imageFileFromPaste(e.clipboardData?.items);\n if (file) {\n e.preventDefault();\n void addImageFile(file);\n }\n };\n window.addEventListener(\"paste\", onPaste);\n return () => window.removeEventListener(\"paste\", onPaste);\n }, [canCreate, editing, colorsOpen, addImageFile]);\n\n // Copy an id or a link, and say so for a moment in the header.\n const copy = useCallback(async (text: string, what: string) => {\n const ok = await copyToClipboard(text);\n setCopied(ok ? `${what} copied` : `could not copy the ${what}`);\n window.setTimeout(() => setCopied(null), 1500);\n }, []);\n\n // The page's per-chunk handlers take the chunk's id, so they stay the same\n // function across renders and a chunk that did not change is not drawn again.\n const pickChunk = useCallback((id: string) => setSelectedId((cur) => (cur === id ? cur : id)), []);\n const toggleSource = useCallback(\n (id: string) =>\n setSourceOpen((s) => {\n const next = new Set(s);\n if (!next.delete(id)) next.add(id);\n return next;\n }),\n [],\n );\n const copyChunkId = useCallback((id: string) => void copy(id, \"chunk id\"), [copy]);\n\n const download = useCallback(\n async (kind: DownloadKind, label: string) => {\n setDownloading(`Preparing ${label}`);\n try {\n await runDownload(data, kind, documentId, scope, browse, rootTitle);\n } catch (e) {\n setErr(e instanceof Error ? e.message : String(e));\n } finally {\n setDownloading(undefined);\n }\n },\n [data, documentId, scope, browse, rootTitle],\n );\n\n const classifyOffered = !!data.documentClassify || classificationPending;\n // The rail: every panel this document can show. A panel remembered from\n // another document that this one does not offer stays closed here.\n const offered: Panel[] = [\n ...(annotationOffered ? ([\"annotation\"] as const) : []),\n \"references\",\n ...(classifyOffered ? ([\"classification\"] as const) : []),\n \"history\",\n ];\n // Laid over the body, a panel opens only when the reader asks for it here:\n // one left open on a wide screen would otherwise cover the page on a phone.\n const openPanel = panel && offered.includes(panel) && (!overlay || panelTouched) ? panel : null;\n // Toggles against what is SHOWN, so the icon of a remembered panel that was\n // left closed opens it instead of clearing it.\n const togglePanel = (p: Panel) => setPanel(openPanel === p ? null : p);\n\n // Keyboard: \"{\" folds the outline, \"]\" the side panel (the last one open,\n // else references). The Path console takes \"[\" for its tree.\n const lastPanel = useRef<Panel>(\"references\");\n if (openPanel) lastPanel.current = openPanel;\n const keysRef = useRef<(e: KeyboardEvent) => void>(() => {});\n keysRef.current = (e: KeyboardEvent) => {\n if (unavailable || !shortcutApplies(e, viewerRef.current)) return;\n if (e.key === \"{\") {\n setOutlineHidden(!outlineHidden);\n } else if (e.key === \"]\") {\n setPanel(openPanel ? null : offered.includes(lastPanel.current) ? lastPanel.current : \"references\");\n } else return;\n e.preventDefault();\n };\n useEffect(() => {\n const onKey = (e: KeyboardEvent) => keysRef.current(e);\n window.addEventListener(\"keydown\", onKey);\n return () => window.removeEventListener(\"keydown\", onKey);\n }, []);\n\n // The rail's annotation icon carries the document's card.\n const docCard: CardSpec = {\n title: rootTitle,\n type: docType,\n status: docStatus,\n brief: documentBrief?.brief,\n abstract: documentBrief?.abstract,\n stale: documentBrief?.stale || undefined,\n };\n const annotationStale = docAnnotations.some((a) => a.stale);\n const cardScope = useMemo<CardScope>(() => ({ data, scope, browse }), [data, scope, browse]);\n\n // Everything on the document that is not \"edit\" (RFC GZ). The chunk actions\n // act on the current chunk — the one picked or scrolled to — as the toolbar's\n // did on the selected one.\n const currentTitle = selectedDetail?.title || chunks.find((c) => c.id === selectedId)?.title || \"(untitled)\";\n const menuGroups: MoreMenuItem[][] = [\n canCreate\n ? [\n {\n key: \"add-text\",\n label: \"add text\",\n title: `Add a text chunk after “${currentTitle}”, at the same level`,\n run: () => void addText(),\n },\n {\n key: \"add-child\",\n label: \"add child\",\n title: selectedId\n ? `Add a chunk nested under “${currentTitle}” (in the ontology, a child is a subclass)`\n : \"Select a chunk first — this nests a new chunk under it\",\n disabled: !selectedId,\n run: () => void addChild(),\n },\n {\n key: \"add-image\",\n label: \"add image\",\n title: \"Add an image chunk (upload — or paste a screenshot into the view)\",\n run: () => fileInputRef.current?.click(),\n },\n { key: \"add-diagram\", label: \"add diagram\", title: \"Add a Mermaid diagram chunk\", run: () => void addDiagram() },\n ]\n : [],\n selectedId && !currentIsRoot\n ? [\n {\n key: \"chunk-up\",\n label: \"move chunk up\",\n title: `Move “${currentTitle}” up within its level`,\n disabled: !siblingBounds.canUp,\n run: () => void reorderSelected(\"up\"),\n },\n {\n key: \"chunk-down\",\n label: \"move chunk down\",\n title: `Move “${currentTitle}” down within its level`,\n disabled: !siblingBounds.canDown,\n run: () => void reorderSelected(\"down\"),\n },\n {\n key: \"chunk-delete\",\n label: \"delete chunk…\",\n title: `Delete “${currentTitle}” and its sub-chunks`,\n danger: true,\n disabled: !selectedDetail,\n run: () => setConfirmDelete(true),\n },\n ]\n : [],\n [\n {\n key: \"colors\",\n label: colorEnabled ? \"colours (on)\" : \"colours\",\n title: \"Colours — tint chunk rows and the Path tree by type/status\",\n disabled: !rootChunkId,\n run: () => setColorsOpen(true),\n },\n ...(data.documentClassify\n ? [\n {\n key: \"classify\",\n label: \"classify\",\n title:\n \"Classify — what this document is, by the confirmed ontology (a report first; nothing is written until Apply)\",\n run: () => {\n setClassifyKey((n) => n + 1);\n setPanel(\"classification\");\n },\n },\n ]\n : []),\n ...(data.documentEntityTypes && rootDetail && isSubjectRoot(rootDetail)\n ? [\n {\n key: \"change-type\",\n label: \"change subject type\",\n title: \"Change this subject's type to another type in force\",\n run: () => setRetyping(rootDetail),\n },\n ]\n : []),\n ...(renderAssistant\n ? [\n {\n key: \"assistant\",\n label: assistantOpen ? \"close assistant\" : \"assistant\",\n title: \"Document Assistant — instruct an agent to restructure/import/link chunks\",\n run: () => setAssistantOpen((o) => !o),\n },\n ]\n : []),\n ],\n downloadEntries(data).map((e) => ({\n key: `download-${e.kind}`,\n label: `download ${e.label}`,\n title: e.title,\n run: () => void download(e.kind, e.label),\n })),\n [\n ...(documentActions?.rename ? [{ key: \"rename\", label: \"rename / move\", run: documentActions.rename }] : []),\n ...(documentActions?.transfer\n ? [\n {\n key: \"transfer\",\n label: \"copy / move to…\",\n title: \"Copy or move to another scope\",\n run: documentActions.transfer,\n },\n ]\n : []),\n {\n key: \"copy-id\",\n label: \"copy document id\",\n title: \"Copy this document's id, for a workflow over the MCP/HTTP API\",\n run: () => void copy(documentId, \"document id\"),\n },\n {\n key: \"copy-link\",\n label: \"copy link\",\n title: \"Copy a loom:doc link to this document, the form agents cite it by\",\n run: () => void copy(docLink(documentId, scope), \"link\"),\n },\n { key: \"reload\", label: \"reload\", title: \"Read the document again\", run: hardReload },\n ],\n documentActions?.delete\n ? [{ key: \"delete\", label: \"delete document…\", danger: true, run: documentActions.delete }]\n : [],\n ];\n\n return (\n <CardScopeContext.Provider value={cardScope}>\n <div className={`doc-viewer${narrow ? \" narrow\" : \"\"}${overlay ? \" panel-over\" : \"\"}`} ref={viewerRef}>\n <input\n ref={fileInputRef}\n type=\"file\"\n accept=\"image/png,image/jpeg,image/gif,image/webp\"\n style={{ display: \"none\" }}\n onChange={(e) => {\n const f = e.target.files?.[0];\n e.target.value = \"\"; // allow re-selecting the same file\n if (f) void addImageFile(f);\n }}\n />\n <div className=\"doc-header\" style={headerTint}>\n {pathLabel && <div className=\"doc-header-path\">{pathLabel}</div>}\n <h1 className=\"doc-title\" title={rootTitle}>\n {rootTitle}\n </h1>\n <TreeMarks type={docType} status={docStatus} statusColor={statusDotColor(docStatus, tintScheme)} />\n <div className=\"doc-header-actions\">\n {copied && (\n <span className=\"doc-header-note\" role=\"status\">\n {copied}\n </span>\n )}\n <button\n type=\"button\"\n className=\"doc-edit\"\n onClick={() => rootDetail && setEditing(rootDetail)}\n disabled={!rootDetail}\n title=\"Edit the document's title, type, status and opening text\"\n >\n <BarIcon kind=\"edit\" />\n <span className=\"doc-edit-label\">edit</span>\n </button>\n <MoreMenu groups={menuGroups} busy={downloading} label=\"Document actions\" />\n </div>\n </div>\n {err && <div className=\"paths-err\">{err}</div>}\n {unavailable ? (\n <DocUnavailable documentId={documentId} scope={scope} detail={loadErr ?? undefined} />\n ) : (\n <div className=\"doc-body\">\n {/* The outline | page border is draggable and its width remembered\n per browser; the outline also folds to a rail with its count. */}\n <Splitter\n className=\"doc-split\"\n defaultLeftWidth={240}\n minLeftWidth={160}\n minRightWidth={320}\n storageKey=\"loomcycle.explorer.split.doc\"\n hideLeft={outlineHidden}\n hideRight={narrow && !outlineHidden}\n onHandleDoubleClick={() => setOutlineHidden(true)}\n leftRail={\n <PaneRail\n side=\"left\"\n label=\"chunk outline\"\n icon=\"outline\"\n count={chunks.length}\n countLabel={chunks.length === 1 ? \"chunk\" : \"chunks\"}\n shortcut=\"{\"\n onExpand={() => setOutlineHidden(false)}\n />\n }\n >\n <div className=\"doc-chunktree\">\n <div className=\"pane-head\">\n <span className=\"pane-head-label\">Outline</span>\n <span className=\"pane-head-count\">{chunks.length}</span>\n <CollapseButton label=\"chunk outline\" side=\"left\" shortcut=\"{\" onClick={() => setOutlineHidden(true)} />\n </div>\n {loading && chunks.length === 0 ? (\n <div className=\"empty\">\n <p>Loading…</p>\n </div>\n ) : (\n <DocumentChunkTree\n tree={tree}\n selectedId={selectedId}\n onSelect={onSelect}\n colorEnabled={colorEnabled}\n scheme={meta?.color_scheme}\n documentColor={documentColor}\n linkedIds={linkedIds}\n documentType={docType}\n documentStatus={docStatus}\n />\n )}\n </div>\n <div className=\"doc-page\" ref={pageRef} tabIndex={-1}>\n <article className=\"doc-article\" aria-label={rootTitle}>\n {flat.map(({ row, depth }) => (\n <ChunkSection\n key={row.id}\n row={row}\n depth={depth}\n detail={details.get(row.id)}\n error={detailErrs.get(row.id)}\n current={row.id === selectedId}\n source={sourceOpen.has(row.id)}\n statusColor={statusDotColor(row.status, tintScheme)}\n scope={scope}\n browse={browse}\n onPick={pickChunk}\n onToggleSource={toggleSource}\n onEdit={setEditing}\n onHistory={setHistoryFor}\n onCopyId={copyChunkId}\n />\n ))}\n </article>\n </div>\n </Splitter>\n {openPanel && (\n <aside className=\"doc-side\" id=\"doc-side\" aria-label={`${PANEL_LABEL[openPanel]} panel`}>\n <div className=\"pane-head\">\n <span className=\"pane-head-label\">{PANEL_LABEL[openPanel]}</span>\n <CollapseButton label={`${PANEL_LABEL[openPanel]} panel`} side=\"right\" shortcut=\"]\" onClick={() => setPanel(null)} />\n </div>\n <div className=\"doc-side-body\">\n {openPanel === \"annotation\" && rootChunkId && (\n <>\n <div className=\"doc-annotation\">\n <h2 className=\"doc-panel-heading\">Document</h2>\n <AnnotationBrief record={documentBrief} />\n <AnnotationPanel\n key={rootChunkId}\n records={docAnnotations}\n newLevel={annotationLevelFor(true)}\n onSave={saveAnnotation?.(rootChunkId)}\n onRegenerate={regenerateAnnotation?.(rootChunkId)}\n />\n </div>\n {selectedId && selectedId !== rootChunkId && (\n <div className=\"doc-annotation\">\n <h2 className=\"doc-panel-heading\">{currentTitle}</h2>\n <AnnotationBrief record={selectedAnnotations[0]} />\n <AnnotationPanel\n key={selectedId}\n records={selectedAnnotations}\n newLevel={annotationLevelFor(false)}\n onSave={saveAnnotation?.(selectedId)}\n onRegenerate={regenerateAnnotation?.(selectedId)}\n />\n </div>\n )}\n </>\n )}\n {openPanel === \"references\" && (\n <div className=\"doc-links-pane\">\n {edges.length === 0 && <p className=\"doc-refs-empty\">This document has no links.</p>}\n <CrossReferences\n edges={edges}\n incomplete={edgesIncomplete}\n documentId={documentId}\n selectedId={selectedId}\n onSelectChunk={goTo}\n onOpenDocument={onOpenDocument ? openDocument : undefined}\n onRuleStatement={ruleStatement}\n />\n {/* RFC BS — backlinks / related / unlinked mentions for the\n current chunk, lazily fetched when its section opens. */}\n <Connections\n documentId={documentId}\n selectedId={selectedId}\n scope={scope}\n browse={browse}\n onSelectChunk={goTo}\n onOpenDocument={onOpenDocument ? openDocument : undefined}\n refreshKey={edgesReload}\n review={review}\n />\n </div>\n )}\n {openPanel === \"classification\" &&\n (classifyKey === 0 && !classificationPending ? (\n <div className=\"doc-classify\">\n <p className=\"doc-classify-hint\">Nothing is waiting for review.</p>\n {data.documentClassify && (\n <button type=\"button\" onClick={() => setClassifyKey((n) => n + 1)}>\n classify this document\n </button>\n )}\n </div>\n ) : (\n <Classification\n key={`${scope}:${documentId}`}\n documentId={documentId}\n scope={scope}\n browse={browse}\n rootFields={rootFields}\n requestKey={classifyKey}\n onClose={() => setClassifyKey(0)}\n onChanged={refresh}\n />\n ))}\n {openPanel === \"history\" &&\n (selectedId ? (\n <>\n <h2 className=\"doc-panel-heading\">{currentTitle}</h2>\n <HistoryView key={selectedId} chunkId={selectedId} scope={scope} browse={browse} />\n </>\n ) : (\n <p className=\"doc-empty-body\">Select a chunk to see its history.</p>\n ))}\n </div>\n </aside>\n )}\n <nav className=\"doc-rail\" aria-label=\"Panels\">\n {offered.map((p) => (\n <RailButton\n key={p}\n panel={p}\n open={openPanel === p}\n onClick={() => togglePanel(p)}\n count={p === \"references\" ? refCount : p === \"classification\" ? pendingCount : undefined}\n dot={p === \"annotation\" && annotationStale}\n card={p === \"annotation\" ? docCard : undefined}\n />\n ))}\n </nav>\n </div>\n )}\n {assistantOpen && renderAssistant && (\n <div className=\"doc-assistant\">\n {renderAssistant({\n documentId,\n scope,\n subject: principal?.subject,\n // Pass the viewer's own reload so the injected assistant can refresh\n // the outline + page after a turn mutates the document.\n onChanged: refresh,\n })}\n </div>\n )}\n {editing && (\n <ChunkEditorModal\n chunk={editing}\n scope={scope}\n browse={browse}\n onClose={() => setEditing(null)}\n onSaved={refresh}\n />\n )}\n {retyping && (\n <SubjectTypeModal\n chunk={retyping}\n scope={scope}\n browse={browse}\n onClose={() => setRetyping(null)}\n onSaved={refresh}\n />\n )}\n {historyFor && (\n <HistoryModal\n chunkId={historyFor.id}\n chunkTitle={historyFor.title}\n scope={scope}\n browse={browse}\n onClose={() => setHistoryFor(null)}\n />\n )}\n {colorsOpen && rootChunkId && (\n <ColorSchemeEditor\n documentId={documentId}\n rootChunkId={rootChunkId}\n docType={meta?.type}\n docStatus={meta?.status}\n chunkStatuses={chunkStatuses}\n scope={scope}\n browse={browse}\n onClose={() => setColorsOpen(false)}\n onSaved={refresh}\n />\n )}\n {confirmDelete && selectedDetail && (\n <div className=\"modal-overlay\" onClick={() => setConfirmDelete(false)}>\n <div className=\"modal chunk-delete-confirm\" onClick={(e) => e.stopPropagation()}>\n <h3>Delete chunk</h3>\n <p className=\"modal-context\">\n Delete “{selectedDetail.title || \"(untitled)\"}” and all of its sub-chunks? This\n cannot be undone.\n </p>\n <div className=\"modal-buttons\">\n <button type=\"button\" onClick={() => setConfirmDelete(false)}>\n cancel\n </button>\n <button type=\"button\" className=\"danger\" onClick={() => void deleteSelected()}>\n delete\n </button>\n </div>\n </div>\n </div>\n )}\n </div>\n </CardScopeContext.Provider>\n );\n}\n\n// docLink is the link agents cite a document by (help topic Document/citing):\n// loom:doc/<id>, with the scope when it is not the user's own.\nexport function docLink(documentId: string, scope: DocScope): string {\n return `loom:doc/${documentId}${scope === \"user\" ? \"\" : `?scope=${scope}`}`;\n}\n\ninterface ChunkSectionProps {\n row: ChunkRow;\n depth: number;\n detail?: ChunkDetail;\n error?: string;\n current: boolean;\n source: boolean;\n statusColor?: string;\n scope: DocScope;\n browse?: BrowseScope;\n onPick: (id: string) => void;\n onToggleSource: (id: string) => void;\n onEdit: (d: ChunkDetail) => void;\n onHistory: (d: ChunkDetail) => void;\n onCopyId: (id: string) => void;\n}\n\n// ChunkSection is one chunk on the page: its heading (by depth; the root's\n// title is the document's, shown once in the header), its body, and its action\n// bar, which shows on hover or when anything in the chunk has the keyboard\n// focus. Memoized: moving the current chunk redraws two sections, not the\n// whole document.\nconst ChunkSection = memo(function ChunkSection({\n row,\n depth,\n detail,\n error,\n current,\n source,\n statusColor,\n scope,\n browse,\n onPick,\n onToggleSource,\n onEdit,\n onHistory,\n onCopyId,\n}: ChunkSectionProps) {\n const title = row.title || \"(untitled)\";\n const level = Math.min(depth + 1, 6);\n const Heading = `h${level}` as \"h2\";\n return (\n <section\n className={`doc-chunk${current ? \" current\" : \"\"}`}\n data-chunk-id={row.id}\n data-depth={depth}\n aria-label={depth === 0 ? undefined : title}\n onClick={() => onPick(row.id)}\n >\n <div className=\"doc-chunk-bar\" role=\"toolbar\" aria-label={`${title} — chunk actions`}>\n <TreeMarks type={row.type} status={row.status} statusColor={statusColor} />\n <span className=\"doc-chunk-rev\" title=\"Revision\">\n rev {row.revision}\n </span>\n {detail?.tags?.map((t) => (\n <span className=\"chunk-tag\" key={t}>\n {t}\n </span>\n ))}\n <button\n type=\"button\"\n className=\"doc-chunk-icon\"\n aria-pressed={source}\n onClick={() => onToggleSource(row.id)}\n disabled={!detail}\n aria-label=\"view source\"\n title=\"Show this chunk's Markdown source\"\n >\n <BarIcon kind=\"source\" />\n </button>\n <button\n type=\"button\"\n className=\"doc-chunk-icon\"\n onClick={() => detail && onHistory(detail)}\n disabled={!detail}\n aria-label=\"history\"\n title=\"This chunk's edit history and diffs\"\n >\n <BarIcon kind=\"history\" />\n </button>\n <button\n type=\"button\"\n className=\"doc-chunk-icon\"\n onClick={() => onCopyId(row.id)}\n aria-label=\"copy id\"\n title=\"Copy this chunk's id\"\n >\n <BarIcon kind=\"copy\" />\n </button>\n <button type=\"button\" className=\"doc-chunk-edit\" onClick={() => detail && onEdit(detail)} disabled={!detail}>\n <BarIcon kind=\"edit\" />\n edit\n </button>\n </div>\n {depth > 0 && <Heading className=\"doc-chunk-title\">{title}</Heading>}\n <ChunkBody detail={detail} error={error} source={source} scope={scope} browse={browse} />\n </section>\n );\n});\n\nconst RAIL_ICON: Record<Panel, PaneIconKind> = {\n annotation: \"annotation\",\n references: \"references\",\n classification: \"classification\",\n history: \"history\",\n};\n\n// RailButton opens one side panel. Its label says what its count counts, so\n// a screen reader hears \"references, 3\" rather than a bare number; a quiet\n// count (0) is not drawn.\nfunction RailButton({\n panel,\n open,\n onClick,\n count,\n dot,\n card,\n}: {\n panel: Panel;\n open: boolean;\n onClick: () => void;\n count?: number;\n dot?: boolean;\n card?: CardSpec;\n}) {\n const c = useButtonCard(card);\n const what =\n panel === \"references\"\n ? `${count ?? 0} on this chunk`\n : panel === \"classification\"\n ? count\n ? `${count} waiting for review`\n : \"nothing waiting\"\n : panel === \"annotation\" && dot\n ? \"out of date\"\n : undefined;\n return (\n <>\n <button\n type=\"button\"\n className={`doc-rail-button${count ? \" counted\" : \"\"}`}\n aria-pressed={open}\n aria-controls={open ? \"doc-side\" : undefined}\n aria-label={`${PANEL_LABEL[panel]}${what ? `, ${what}` : \"\"}`}\n title={card ? undefined : PANEL_LABEL[panel]}\n aria-keyshortcuts={open ? \"]\" : undefined}\n onClick={onClick}\n {...c.props}\n >\n <PaneIcon kind={RAIL_ICON[panel]} />\n {count ? <span className=\"doc-rail-count\">{count}</span> : null}\n {dot && <span className=\"doc-rail-dot\" aria-hidden=\"true\" />}\n </button>\n {c.card}\n </>\n );\n}\n\n// The chunk bar's icons, drawn like the tree icons so they follow the theme.\nfunction BarIcon({ kind }: { kind: \"source\" | \"history\" | \"copy\" | \"edit\" }) {\n return (\n <svg\n width=\"14\"\n height=\"14\"\n viewBox=\"0 0 16 16\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"1.4\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n aria-hidden=\"true\"\n focusable=\"false\"\n >\n {kind === \"source\" && <path d=\"M5.5 4.5L2 8l3.5 3.5M10.5 4.5L14 8l-3.5 3.5\" />}\n {kind === \"history\" && (\n <>\n <circle cx=\"8\" cy=\"8\" r=\"5.75\" />\n <path d=\"M8 5v3.25l2 1.25\" />\n </>\n )}\n {kind === \"edit\" && <path d=\"M10.75 2.75l2.5 2.5L5.5 13H3v-2.5zM9.25 4.25l2.5 2.5\" />}\n {kind === \"copy\" && (\n <>\n <rect x=\"5.25\" y=\"5.25\" width=\"8\" height=\"8\" rx=\"1\" />\n <path d=\"M10.75 5.25v-1.5a1 1 0 0 0-1-1h-6a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h1.5\" />\n </>\n )}\n </svg>\n );\n}\n\nfunction ChunkBody({\n detail,\n error,\n source,\n scope,\n browse,\n}: {\n detail?: ChunkDetail;\n error?: string;\n source: boolean;\n scope: DocScope;\n browse?: BrowseScope;\n}) {\n if (!detail) {\n return error ? (\n <p className=\"doc-empty-body\">This chunk could not be read: {error}</p>\n ) : (\n <p className=\"doc-chunk-loading\" aria-busy=\"true\">\n Loading…\n </p>\n );\n }\n if (source) {\n return (\n <pre className=\"md-pre doc-chunk-source\">\n <code>{detail.body}</code>\n </pre>\n );\n }\n if (detail.type === \"mermaid\") {\n // RFC BO — a diagram chunk: body IS the Mermaid source.\n return detail.body ? <MermaidDiagram code={detail.body} /> : <p className=\"doc-empty-body\">(empty diagram)</p>;\n }\n if (detail.type === \"image\" || detail.asset) {\n return <ChunkImage detail={detail} scope={scope} browse={browse} />;\n }\n return detail.body ? <Markdown source={detail.body} /> : null;\n}\n\n// ChunkImage shows an image chunk (RFC BO): its bytes are fetched WITH auth into\n// a blob object-URL for <img src> (a bare <img src=/v1/...> can't carry a\n// bearer), revoked when the chunk changes or leaves the page.\nfunction ChunkImage({ detail, scope, browse }: { detail: ChunkDetail; scope: DocScope; browse?: BrowseScope }) {\n const data = useExplorerData();\n const [url, setUrl] = useState<string | null>(null);\n const [err, setErr] = useState<string | null>(null);\n useEffect(() => {\n if (!data.documentAssetObjectUrl) return;\n let cancelled = false;\n let made: string | null = null;\n setErr(null);\n data\n .documentAssetObjectUrl(detail.id, scope, browse)\n .then((u) => {\n if (cancelled) {\n URL.revokeObjectURL(u);\n return;\n }\n made = u;\n setUrl(u);\n })\n .catch((e) => !cancelled && setErr(e instanceof Error ? e.message : String(e)));\n return () => {\n cancelled = true;\n if (made) URL.revokeObjectURL(made);\n };\n // The revision moves when the image is replaced.\n }, [data, detail.id, detail.revision, scope, browse]);\n if (err) return <p className=\"doc-empty-body\">Image failed to load: {err}</p>;\n if (!url) return <p className=\"doc-chunk-loading\">Loading image…</p>;\n return (\n <figure className=\"doc-image\">\n <img src={url} alt={imageAlt(detail)} />\n {detail.body && <figcaption>{detail.body}</figcaption>}\n </figure>\n );\n}\n","import type { CSSProperties, ReactNode } from \"react\";\nimport type { DirListing, DirMap } from \"../lib/lazyPathTree\";\nimport type { PathEntry } from \"../types\";\nimport type { CardSpec } from \"./AnnotationCard\";\nimport { ANNOTATION_ENTRY } from \"../lib/annotation\";\nimport {\n docColor,\n effectiveScheme,\n rowTint,\n statusDotColor,\n type DocSummary,\n} from \"../lib/colorScheme\";\nimport { TreeIcon, TreeItem, TreeMarks, treeKeyDown, type TreeIconKind } from \"./TreeRow\";\n\n// PathTree renders the RFC AL dirent tree from per-directory listings (see\n// lib/lazyPathTree): a directory's children exist only once it has been opened\n// and listed. The expand set, the loading and the paging are owned by the\n// caller; this component only draws them — a caret per directory, a status row\n// while a directory loads / is empty / failed, and a \"load more\" row while a\n// directory has pages left.\n\nexport interface PathNode {\n name: string;\n fullPath: string;\n kind: string; // directory | document | volume_mount | memory_entry\n resourceRef?: unknown;\n // hasChildren: a non-directory (a document) that also has names beneath it,\n // so it opens like a directory while its name still opens the document.\n hasChildren?: boolean;\n // listing is this node's children's load state; undefined = never listed\n // (and always undefined for a node that cannot be opened).\n listing?: DirListing;\n // documents: how many documents the reader may open under this folder, when\n // the runtime's listing says (RFC HA). Never worked out here from the\n // folders that happen to be open — that number would be wrong.\n documents?: number;\n // documentsCapped: the count stopped at its cap (more than `documents`).\n documentsCapped?: boolean;\n // matched: in a filtered listing, the entry's own document matched (RFC HA).\n matched?: boolean;\n children: PathNode[];\n}\n\n// buildLazyTree turns the listings into a hierarchy rooted at `dir` (\"\" =\n// root). A one-level listing already includes implicit directories (the runtime\n// synthesizes them from deeper descendants), so nothing is synthesized here.\nexport function buildLazyTree(dirs: DirMap, dir = \"\"): PathNode[] {\n const listing = dirs.get(dir);\n if (!listing) return [];\n const nodes = listing.entries.map((e): PathNode => {\n // The prefix check keeps a malformed entry (a child spelled like its own\n // directory) from recursing forever.\n const hasChildren = e.kind !== \"directory\" && e.has_children === true;\n const opens = (e.kind === \"directory\" || hasChildren) && e.full_path.startsWith(`${dir}/`);\n const documents = folderDocuments(e);\n return {\n name: e.name,\n fullPath: e.full_path,\n kind: e.kind,\n resourceRef: e.resource_ref,\n ...(hasChildren ? { hasChildren } : {}),\n ...(documents !== undefined ? { documents } : {}),\n ...(documents !== undefined && e.documents_capped === true ? { documentsCapped: true } : {}),\n ...(e.matched === true ? { matched: true } : {}),\n listing: opens ? dirs.get(e.full_path) : undefined,\n children: opens ? buildLazyTree(dirs, e.full_path) : [],\n };\n });\n nodes.sort((a, b) => {\n const ad = a.kind === \"directory\";\n const bd = b.kind === \"directory\";\n if (ad !== bd) return ad ? -1 : 1; // directories first\n return a.name.localeCompare(b.name);\n });\n return nodes;\n}\n\n// folderDocuments reads a folder entry's document count when the runtime\n// sends one (RFC HA's `documents` on a listing entry) — on a directory, or on a\n// document with names below it, where it counts those names. The capability is\n// detected from the field itself, so an older runtime simply leaves the slot\n// empty.\nexport function folderDocuments(e: PathEntry): number | undefined {\n if (e.kind !== \"directory\" && e.has_children !== true) return undefined;\n const n = (e as { documents?: unknown }).documents;\n return typeof n === \"number\" && Number.isFinite(n) && n >= 0 ? Math.floor(n) : undefined;\n}\n\n// formatCount is the count slot's text: exact below 10,000 (the runtime's cap),\n// and a capped count as \"10k+\" — the runtime stopped counting there, so the\n// number is a floor, not a total.\nexport function formatCount(n: number, capped?: boolean): string {\n if (capped) return `${n >= 1000 ? `${Math.floor(n / 1000)}k` : n}+`;\n return n >= 10000 ? `${Math.floor(n / 1000)}k` : n.toLocaleString(\"en-US\");\n}\n\n// countLabel is the count's accessible name: the number in full, and what it\n// counts (under a filter, the documents that match).\nexport function countLabel(n: number, capped: boolean | undefined, filtered: boolean | undefined): string {\n const what = filtered ? (n === 1 && !capped ? \"matching document\" : \"matching documents\") : n === 1 && !capped ? \"document\" : \"documents\";\n return `${n.toLocaleString(\"en-US\")}${capped ? \" or more\" : \"\"} ${what}`;\n}\n\n// The icon of each entry kind; an unknown kind draws as a document.\nconst KIND_ICON: Record<string, TreeIconKind> = {\n directory: \"folder\",\n document: \"document\",\n volume_mount: \"volume\",\n memory_entry: \"memory\",\n};\n\n// isAnnotationEntry: the reserved `_annotation` document of a folder.\nexport function isAnnotationEntry(node: Pick<PathNode, \"kind\" | \"name\">): boolean {\n return node.kind === \"document\" && node.name === ANNOTATION_ENTRY;\n}\n\n// nodeBrief is a row's brief (shown in its card): a document's own, and for\n// a folder the brief of its `_annotation` document — known only once the\n// folder has been listed, which is when its children's summaries arrive. No\n// extra call is made for it.\nexport function nodeBrief(node: PathNode, summaries?: Map<string, DocSummary>): string | undefined {\n if (node.kind === \"directory\") {\n const ann = node.children.find(isAnnotationEntry);\n return ann ? documentSummaryOf(ann, summaries)?.brief || undefined : undefined;\n }\n if (isAnnotationEntry(node)) return undefined; // its brief is the folder's\n return documentSummaryOf(node, summaries)?.brief || undefined;\n}\n\nexport interface PathTreeProps {\n tree: PathNode[];\n // root is the root directory's listing (its status/paging rows).\n root?: DirListing;\n expanded: ReadonlySet<string>;\n onToggle: (dir: string) => void;\n // onLoadMore fetches a directory's next page (\"\" = root); onRetry re-tries a\n // directory whose listing failed.\n onLoadMore: (dir: string) => void;\n onRetry: (dir: string) => void;\n selectedPath?: string;\n onSelect: (node: PathNode) => void;\n // RFC BN: per-document display metadata keyed by document_id, used to color a\n // document row + badge its type/status. Unset → neutral rows (prior behavior).\n summaries?: Map<string, DocSummary>;\n // Search (RFC GZ): the rows whose names match, and the one the search is on.\n searchHits?: ReadonlySet<string>;\n searchCurrent?: string;\n // filtered: the tree is a filtered listing from the runtime (RFC HA). A\n // document that matched itself is marked; one kept only for what is below\n // it is drawn quieter; counts are of matches.\n filtered?: boolean;\n}\n\n// nodeCard is a row's annotation card: what the tree already knows — the\n// document summaries it loads, and a folder's brief from its `_annotation`.\nexport function nodeCard(node: PathNode, summaries?: Map<string, DocSummary>): CardSpec {\n const summary = documentSummaryOf(node, summaries);\n return {\n title: summary?.title || node.name,\n type: node.kind === \"directory\" ? \"folder\" : summary?.type,\n status: summary?.status,\n path: node.fullPath,\n brief: nodeBrief(node, summaries),\n };\n}\n\nexport default function PathTree(props: PathTreeProps) {\n const { tree, root } = props;\n if (!root || (!root.loaded && root.loading)) {\n return (\n <div className=\"empty\">\n <p>Loading…</p>\n </div>\n );\n }\n if (root.loaded && tree.length === 0 && !root.nextCursor) {\n return (\n <div className=\"empty\">\n <p>\n {props.filtered\n ? \"Nothing in this tree matches the filter.\"\n : \"This tree is empty. Create a folder or document to begin.\"}\n </p>\n </div>\n );\n }\n const top = visibleChildren(tree);\n // One tab stop: the selected row while it is drawn, else the first row.\n const tabStop =\n props.selectedPath && isDrawn(top, props.expanded, props.selectedPath) ? props.selectedPath : top[0]?.fullPath;\n return (\n <ul className=\"etree path-tree\" role=\"tree\" aria-label=\"Path tree\" onKeyDown={treeKeyDown}>\n {top.map((n) => (\n <PathTreeNode key={n.fullPath} node={n} depth={0} tabStop={tabStop} {...props} />\n ))}\n <ListingRows dir=\"\" listing={root} {...props} />\n </ul>\n );\n}\n\n// ListingRows draws the trailing rows of a directory's children: its status\n// (loading / empty / failed) and, while pages remain, a \"load more\" button.\n// Entries are never dropped silently — a clipped directory always ends in one.\nfunction ListingRows({\n dir,\n listing,\n depth,\n onLoadMore,\n onRetry,\n filtered,\n}: { dir: string; listing?: DirListing; depth?: number } & PathTreeProps) {\n const rows: ReactNode[] = [];\n // Indented as the directory's children are (the root's rows at depth 0).\n const indent = { \"--etree-depth\": depth === undefined ? 0 : depth + 1 } as CSSProperties;\n // A folder holding only its `_annotation` draws no child row, so it reads empty.\n const shown = listing ? listing.entries.filter((e) => !isAnnotationEntry(e)).length : 0;\n if (!listing || (listing.loading && listing.entries.length === 0)) {\n rows.push(\n <li key=\"status\" className=\"path-status\" role=\"none\" style={indent}>\n <span className=\"path-implicit\">loading…</span>\n </li>,\n );\n } else if (listing.error) {\n rows.push(\n <li key=\"status\" className=\"path-status\" role=\"none\" style={indent}>\n {/* The root's failure is already the banner above the tree. */}\n {dir !== \"\" && <span className=\"path-err\">failed to load: {listing.error}</span>}{\" \"}\n <button type=\"button\" className=\"path-more\" onClick={() => onRetry(dir)}>\n retry\n </button>\n </li>,\n );\n } else if (listing.loaded && shown === 0 && !listing.nextCursor && dir !== \"\") {\n rows.push(\n <li key=\"status\" className=\"path-status\" role=\"none\" style={indent}>\n <span className=\"path-implicit\">{filtered ? \"no match\" : \"empty\"}</span>\n </li>,\n );\n }\n if (listing?.nextCursor && !listing.error) {\n rows.push(\n <li key=\"more\" className=\"path-status\" role=\"none\" style={indent}>\n <button\n type=\"button\"\n className=\"path-more\"\n disabled={listing.loading}\n onClick={() => onLoadMore(dir)}\n >\n {/* A filtered page can stop early, even empty, with more after it:\n its cursor means \"maybe more\", not \"this many more\". */}\n {listing.loading\n ? filtered\n ? \"looking…\"\n : \"loading…\"\n : filtered\n ? \"Look for more matches\"\n : `Load more (${listing.entries.length} shown)`}\n </button>\n </li>,\n );\n }\n return <>{rows}</>;\n}\n\n// documentSummaryOf returns the summary for a `document` node (by its dirent's\n// document_id), or undefined for a non-document node / missing summary.\nexport function documentSummaryOf(node: PathNode, summaries?: Map<string, DocSummary>): DocSummary | undefined {\n if (node.kind !== \"document\" || !summaries) return undefined;\n const ref = node.resourceRef as { document_id?: string } | undefined;\n return ref?.document_id ? summaries.get(ref.document_id) : undefined;\n}\n\n// visibleChildren drops a folder's `_annotation` entry from the rows drawn: its\n// brief is the folder's (nodeBrief reads it from the built tree, so the entry\n// stays in the tree and only its row is left out).\nfunction visibleChildren(nodes: PathNode[]): PathNode[] {\n return nodes.filter((n) => !isAnnotationEntry(n));\n}\n\n// isDrawn: whether the row for `path` is rendered — it exists, is not a hidden\n// `_annotation` entry, and every directory above it is open.\nfunction isDrawn(nodes: PathNode[], expanded: ReadonlySet<string>, path: string): boolean {\n for (const n of visibleChildren(nodes)) {\n if (n.fullPath === path) return true;\n const open = (n.kind === \"directory\" || n.hasChildren === true) && expanded.has(n.fullPath);\n if (open && path.startsWith(`${n.fullPath}/`) && isDrawn(n.children, expanded, path)) return true;\n }\n return false;\n}\n\nfunction PathTreeNode(props: { node: PathNode; depth: number; tabStop?: string } & PathTreeProps) {\n const {\n node,\n depth,\n tabStop,\n expanded,\n onToggle,\n selectedPath,\n onSelect,\n summaries,\n searchHits,\n searchCurrent,\n filtered,\n } = props;\n // A directory opens, and so does a document with names beneath it (RFC GC):\n // its caret lists them while the row still opens the document. Children are\n // unknown until listed, so the caret is live even before then.\n const isDir = node.kind === \"directory\" || node.hasChildren === true;\n const isOpen = isDir && expanded.has(node.fullPath);\n const isSelected = selectedPath === node.fullPath;\n const summary = documentSummaryOf(node, summaries);\n const scheme = summary ? effectiveScheme(summary.color_scheme) : undefined;\n const coloured = !!summary?.color_enabled;\n const hit = searchHits?.has(node.fullPath);\n // Under a filter a document either matched itself or is there only for the\n // names below it; folders never match themselves, so they carry no mark.\n const filterMark =\n filtered && node.kind !== \"directory\" ? (node.matched ? \"filter-match\" : \"filter-kept\") : undefined;\n return (\n <TreeItem\n className={`path-node kind-${node.kind}`}\n rowClassName={\n searchCurrent === node.fullPath ? \"search-hit search-current\" : hit ? \"search-hit\" : filterMark\n }\n card={nodeCard(node, summaries)}\n count={\n // The slot is on every folder row and stays empty until the runtime\n // sends a count (RFC HA); a document with names below it shows one\n // when it is sent.\n node.kind === \"directory\" || node.documents !== undefined ? (\n <span\n className={`etree-count${node.documentsCapped ? \" capped\" : \"\"}`}\n aria-label={\n node.documents !== undefined ? countLabel(node.documents, node.documentsCapped, filtered) : undefined\n }\n >\n {node.documents !== undefined ? formatCount(node.documents, node.documentsCapped) : undefined}\n </span>\n ) : undefined\n }\n depth={depth}\n expandable={isDir}\n expanded={isOpen}\n onToggle={() => onToggle(node.fullPath)}\n selected={isSelected}\n onSelect={() => onSelect(node)}\n tabbable={node.fullPath === tabStop}\n icon={<TreeIcon kind={isAnnotationEntry(node) ? \"annotation\" : (KIND_ICON[node.kind] ?? \"document\")} />}\n name={node.name}\n marks={\n <TreeMarks\n bare\n type={summary?.type}\n status={summary?.status}\n statusColor={statusDotColor(summary?.status, coloured ? scheme : undefined)}\n />\n }\n style={coloured && scheme ? rowTint(docColor(summary?.type, summary?.status, scheme)) : undefined}\n >\n {isOpen ? (\n <>\n {visibleChildren(node.children).map((c) => (\n <PathTreeNode key={c.fullPath} {...props} node={c} depth={depth + 1} />\n ))}\n <ListingRows {...props} dir={node.fullPath} listing={node.listing} />\n </>\n ) : undefined}\n </TreeItem>\n );\n}\n","import { useEffect, useId, useRef, useState, type KeyboardEvent } from \"react\";\n\n// CreateMenu is the Path header's one \"+\" button (RFC GZ): a small menu that\n// creates a folder or a document in `dir`. The create dialog it opens names\n// that folder in its title, so the target stays visible where it is used.\n\nexport interface CreateMenuProps {\n dir: string;\n onNewFolder: () => void;\n onNewDocument: () => void;\n}\n\nexport default function CreateMenu({ dir, onNewFolder, onNewDocument }: CreateMenuProps) {\n const items = [\n { key: \"folder\", label: \"folder\", title: `New folder in ${dir}`, run: onNewFolder },\n { key: \"document\", label: \"document\", title: `New document in ${dir}`, run: onNewDocument },\n ];\n const [openAt, setOpenAt] = useState<number | null>(null);\n const open = openAt !== null;\n const rootRef = useRef<HTMLDivElement>(null);\n const buttonRef = useRef<HTMLButtonElement>(null);\n const itemRefs = useRef<(HTMLButtonElement | null)[]>([]);\n const menuId = useId();\n\n useEffect(() => {\n if (openAt !== null) itemRefs.current[openAt]?.focus();\n }, [openAt]);\n\n useEffect(() => {\n if (!open) return;\n const onDown = (e: MouseEvent) => {\n if (rootRef.current && !rootRef.current.contains(e.target as Node)) setOpenAt(null);\n };\n document.addEventListener(\"mousedown\", onDown);\n return () => document.removeEventListener(\"mousedown\", onDown);\n }, [open]);\n\n const close = () => {\n setOpenAt(null);\n buttonRef.current?.focus();\n };\n\n const onItemKeyDown = (e: KeyboardEvent<HTMLButtonElement>, i: number) => {\n const n = items.length;\n if (e.key === \"ArrowDown\" || e.key === \"ArrowUp\") {\n e.preventDefault();\n itemRefs.current[(i + (e.key === \"ArrowDown\" ? 1 : -1) + n) % n]?.focus();\n } else if (e.key === \"Escape\") {\n e.preventDefault();\n close();\n } else if (e.key === \"Tab\") {\n setOpenAt(null);\n }\n };\n\n return (\n <div className=\"paths-create-menu\" ref={rootRef}>\n <button\n ref={buttonRef}\n type=\"button\"\n className={open ? \"active\" : undefined}\n title={`New folder or document in ${dir}`}\n aria-label=\"New\"\n aria-haspopup=\"menu\"\n aria-expanded={open}\n aria-controls={open ? menuId : undefined}\n onClick={() => setOpenAt(open ? null : 0)}\n onKeyDown={(e) => {\n if (e.key === \"ArrowDown\") {\n e.preventDefault();\n setOpenAt(0);\n } else if (e.key === \"Escape\" && open) {\n e.preventDefault();\n setOpenAt(null);\n }\n }}\n >\n +\n </button>\n {open && (\n <div className=\"paths-create-list\" role=\"menu\" id={menuId} aria-label=\"New\">\n {items.map((item, i) => (\n <button\n key={item.key}\n ref={(el) => {\n itemRefs.current[i] = el;\n }}\n type=\"button\"\n role=\"menuitem\"\n tabIndex={-1}\n title={item.title}\n onClick={() => {\n setOpenAt(null);\n item.run();\n }}\n onKeyDown={(e) => onItemKeyDown(e, i)}\n >\n {item.label}\n </button>\n ))}\n </div>\n )}\n </div>\n );\n}\n","import { useButtonCard, type CardSpec } from \"./AnnotationCard\";\n\n// Breadcrumb is the document header's path (RFC GZ): each folder segment is a\n// button that selects and reveals that folder in the Path tree, and the last\n// segment is the document itself. Every segment carries its annotation card.\n//\n// It is distinct from the followed-links trail (DocTrail), which records the\n// documents a reader came through, not where this one is filed.\nexport interface BreadcrumbProps {\n // path is the document's canonical Path name (\"/kb/docs/architecture\").\n path: string;\n // onFolder selects and reveals a folder (\"/kb\", \"/kb/docs\").\n onFolder: (folder: string) => void;\n // cardFor gives a segment's card: a folder's from the tree, the document's\n // from its summary.\n cardFor?: (segmentPath: string, isDocument: boolean) => CardSpec | undefined;\n}\n\nexport function breadcrumbSegments(path: string): { name: string; path: string }[] {\n const parts = path.split(\"/\").filter(Boolean);\n return parts.map((name, i) => ({ name, path: `/${parts.slice(0, i + 1).join(\"/\")}` }));\n}\n\nexport default function Breadcrumb({ path, onFolder, cardFor }: BreadcrumbProps) {\n const segs = breadcrumbSegments(path);\n return (\n <nav className=\"doc-crumbs\" aria-label=\"Where this document is filed\">\n <ol className=\"doc-crumbs-list\">\n {segs.map((s, i) =>\n i === segs.length - 1 ? (\n <li className=\"doc-crumbs-item\" key={s.path}>\n <Segment name={s.name} card={cardFor?.(s.path, true)} />\n </li>\n ) : (\n <li className=\"doc-crumbs-item\" key={s.path}>\n <Segment name={s.name} card={cardFor?.(s.path, false)} onClick={() => onFolder(s.path)} />\n </li>\n ),\n )}\n </ol>\n </nav>\n );\n}\n\nfunction Segment({ name, card, onClick }: { name: string; card?: CardSpec; onClick?: () => void }) {\n const c = useButtonCard(card);\n if (!onClick) {\n // The document: not a link (it is open), but focusable for its card.\n return (\n <>\n <span className=\"doc-crumbs-current\" aria-current=\"page\" tabIndex={card ? 0 : undefined} {...c.props}>\n {name}\n </span>\n {c.card}\n </>\n );\n }\n return (\n <>\n <button type=\"button\" className=\"doc-crumbs-folder\" onClick={onClick} {...c.props}>\n {name}\n </button>\n {c.card}\n </>\n );\n}\n","import type { DocSummary } from \"./colorScheme\";\nimport type { PathLsFilters } from \"./dataLayer\";\nimport { documentSummaryOf, isAnnotationEntry, type PathNode } from \"../components/PathTree\";\n\n// Search and filter over the Path tree (RFC GZ). Search works on the folders\n// already listed: the tree is lazy, so a folder nobody opened holds nothing\n// to match yet, and the search line says so. The filter is the runtime's\n// (RFC HA): each one-level listing is asked with the filters, so it covers\n// the whole subtree; a runtime that does not filter (no echo of the filters\n// on its answer) gets the filter applied here, to the folders already listed.\n// `findCoverage` is where that is decided.\n\nexport interface TreeFilter {\n name: string;\n type: string; // \"\" = any\n status: string; // \"\" = any\n}\n\nexport const NO_FILTER: TreeFilter = { name: \"\", type: \"\", status: \"\" };\n\nexport function filterActive(f: TreeFilter): boolean {\n return f.name.trim() !== \"\" || f.type.trim() !== \"\" || f.status.trim() !== \"\";\n}\n\n// STATUS_SUGGESTIONS are the statuses the knowledge base works with; a status\n// is free text in the store, so they are offered, not imposed.\nexport const STATUS_SUGGESTIONS = [\"draft\", \"review\", \"confirmed\", \"done\"];\n\n// findCoverage says what a search or a filter reaches, from the root listing\n// it is drawn from: \"subtree\" when the runtime answered it with the filters it\n// applied (RFC HA), else \"opened\" — the folders already listed. A search's\n// listing is never filtered, so a search always reads \"opened\".\nexport type FindCoverage = \"opened\" | \"subtree\";\nexport function findCoverage(rootListing: unknown): FindCoverage {\n const echo = (rootListing as { appliedFilters?: unknown } | undefined)?.appliedFilters;\n return echo !== undefined && echo !== null ? \"subtree\" : \"opened\";\n}\n\nexport function coverageLabel(mode: \"search\" | \"filter\", c: FindCoverage): string {\n const verb = mode === \"search\" ? \"searching\" : \"filtering\";\n return c === \"subtree\" ? `${verb} the whole tree` : `${verb} opened folders`;\n}\n\n// lsFilters is a filter as a one-level ls takes it; undefined when nothing is\n// set. The name is trimmed, as the local filter reads it.\nexport function lsFilters(f: TreeFilter): PathLsFilters | undefined {\n if (!filterActive(f)) return undefined;\n const out: PathLsFilters = {};\n const name = f.name.trim();\n const type = f.type.trim();\n const status = f.status.trim();\n if (name) out.name_contains = name;\n if (type) out.type = type;\n if (status) out.status = status;\n return out;\n}\n\n// AUTO_OPEN_FOLDERS bounds how many folders a filtered tree opens by itself.\n// Every folder a filtered listing keeps leads to a match, so opening it is\n// what the reader would do next; but each opening is one more filtered ls\n// (which can read up to 50,000 documents' metadata), so past the bound the\n// folders wait, closed, for a click.\nexport const AUTO_OPEN_FOLDERS = 8;\n\n// autoOpen picks the folders of a filtered tree to open next, breadth first:\n// drawn (every folder above is open), not open yet, never opened before\n// (`tried` — a folder the reader closes stays closed), and leading to a\n// match: a directory always does, a document with names below it only when\n// its count says something below matches. At most `budget - tried.size`.\nexport function autoOpen(\n tree: PathNode[],\n open: ReadonlySet<string>,\n tried: ReadonlySet<string>,\n budget: number = AUTO_OPEN_FOLDERS,\n): string[] {\n const room = budget - tried.size;\n if (room <= 0) return [];\n const out: string[] = [];\n let level = tree;\n while (level.length > 0 && out.length < room) {\n const next: PathNode[] = [];\n for (const n of level) {\n if (isAnnotationEntry(n)) continue;\n const opens =\n n.kind === \"directory\" || (n.hasChildren === true && (!n.matched || (n.documents ?? 0) > 0));\n if (!opens) continue;\n if (open.has(n.fullPath)) next.push(...n.children);\n else if (!tried.has(n.fullPath) && out.length < room) out.push(n.fullPath);\n }\n level = next;\n }\n return out;\n}\n\nconst fold = (s: string) => s.toLocaleLowerCase();\n\n// searchListed lists, in tree order (depth first, as drawn), the listed\n// entries under `base` (\"\" = the root) whose names contain `query`. A\n// folder's `_annotation` entry is never a match: it has no row.\nexport function searchListed(tree: PathNode[], base: string, query: string): PathNode[] {\n const q = fold(query.trim());\n if (!q) return [];\n const out: PathNode[] = [];\n const walk = (nodes: PathNode[]) => {\n for (const n of nodes) {\n if (isAnnotationEntry(n)) continue;\n const inside = base === \"\" || n.fullPath.startsWith(`${base}/`);\n if (inside && fold(n.name).includes(q)) out.push(n);\n // Only a branch that leads to (or lies under) the base is walked.\n if (inside || n.fullPath === base || base.startsWith(`${n.fullPath}/`)) walk(n.children);\n }\n };\n walk(tree);\n return out;\n}\n\nfunction docMatches(n: PathNode, f: TreeFilter, summaries?: Map<string, DocSummary>): boolean {\n const s = documentSummaryOf(n, summaries);\n const q = fold(f.name.trim());\n if (q && !fold(n.name).includes(q) && !fold(s?.title ?? \"\").includes(q)) return false;\n const type = f.type.trim();\n const status = f.status.trim();\n if (type && fold(s?.type ?? \"\") !== fold(type)) return false;\n if (status && fold(s?.status ?? \"\") !== fold(status)) return false;\n return true;\n}\n\n// filterTree narrows the listed tree to what matches. A document (or any\n// non-folder entry) stays when it matches; a folder stays when something\n// under it does — it is then shown open, as `open` lists — or, with only a\n// name to match, when its own name does (shown as it is, with what it holds).\n// Folders with no match are gone.\nexport function filterTree(\n tree: PathNode[],\n f: TreeFilter,\n summaries?: Map<string, DocSummary>,\n): { tree: PathNode[]; open: Set<string> } {\n const open = new Set<string>();\n const nameOnly = f.type.trim() === \"\" && f.status.trim() === \"\";\n const q = fold(f.name.trim());\n const walk = (nodes: PathNode[]): PathNode[] => {\n const kept: PathNode[] = [];\n for (const n of nodes) {\n if (isAnnotationEntry(n)) {\n kept.push(n); // never drawn; kept so the folder's card keeps its brief\n continue;\n }\n const isFolder = n.kind === \"directory\";\n const under = walk(n.children);\n const hasMatchUnder = under.some((c) => !isAnnotationEntry(c));\n if (hasMatchUnder) {\n open.add(n.fullPath);\n kept.push({ ...n, children: under });\n } else if (isFolder ? nameOnly && q !== \"\" && fold(n.name).includes(q) : docMatches(n, f, summaries)) {\n kept.push(n);\n }\n }\n return kept;\n };\n return { tree: walk(tree), open };\n}\n\n// filterChoices lists the types and statuses among the documents of the given\n// trees (the plain tree and the filtered one), as the filter fields'\n// suggestions; the statuses always include STATUS_SUGGESTIONS. A folder's\n// `_annotation` document is no document of the folder — the runtime's filter\n// never matches it — so neither it nor its `Annotation` type is offered.\nexport function filterChoices(\n trees: PathNode[][],\n summaries?: Map<string, DocSummary>,\n): { types: string[]; statuses: string[] } {\n const types = new Set<string>();\n const statuses = new Set<string>(STATUS_SUGGESTIONS);\n const walk = (nodes: PathNode[]) => {\n for (const n of nodes) {\n if (!isAnnotationEntry(n)) {\n const s = documentSummaryOf(n, summaries);\n if (s?.type && fold(s.type) !== \"annotation\") types.add(s.type);\n if (s?.status) statuses.add(s.status);\n }\n walk(n.children);\n }\n };\n trees.forEach(walk);\n const sort = (a: string, b: string) => a.localeCompare(b);\n return { types: [...types].sort(sort), statuses: [...statuses].sort(sort) };\n}\n","import {\n useCallback,\n useEffect,\n useId,\n useMemo,\n useRef,\n useState,\n useSyncExternalStore,\n type FormEvent,\n type ReactNode,\n} from \"react\";\nimport type {\n AnnotationTarget,\n AssistantContext,\n BrowseScope,\n NavigatorContext,\n NavigatorSelection,\n PathScope,\n Principal,\n} from \"./types\";\nimport { readNavigatorMode, writeNavigatorMode, type NavigatorMode } from \"./lib/navigator\";\nimport { useExplorerData, type ExplorerDataLayer } from \"./lib/dataLayer\";\nimport type { DocSummary } from \"./lib/colorScheme\";\nimport {\n LazyPathTree,\n LS_PAGE_LIMIT,\n ancestorsOf,\n documentIdsOf,\n listSubtree,\n parentPathOf,\n type DirMap,\n} from \"./lib/lazyPathTree\";\nimport {\n ExplorerRoot,\n useResolvedDataLayer,\n type ExplorerDataSource,\n} from \"./components/ExplorerRoot\";\nimport {\n amendCurrent,\n findDocumentPath,\n followReference,\n jumpTo,\n type DocLocation,\n type Trail,\n} from \"./lib/docTrail\";\nimport DocTrail from \"./components/DocTrail\";\nimport TransferModal from \"./components/TransferModal\";\nimport type { TransferRequest } from \"./lib/transfer\";\nimport Splitter from \"./components/Splitter\";\nimport DocumentViewerBody from \"./components/DocumentViewerBody\";\nimport PathTree, {\n buildLazyTree,\n documentSummaryOf,\n isAnnotationEntry,\n nodeCard,\n type PathNode,\n} from \"./components/PathTree\";\nimport CreateMenu from \"./components/CreateMenu\";\nimport Breadcrumb from \"./components/Breadcrumb\";\nimport { CollapseButton, PaneIcon, PaneRail } from \"./components/Pane\";\nimport { CardBody, documentCard, type CardSpec } from \"./components/AnnotationCard\";\nimport { shortcutApplies, usePersistedFlag } from \"./lib/persisted\";\nimport { useNarrow } from \"./lib/useNarrow\";\nimport {\n NO_FILTER,\n autoOpen,\n coverageLabel,\n filterActive,\n filterChoices,\n filterTree,\n findCoverage,\n lsFilters,\n searchListed,\n type TreeFilter,\n} from \"./lib/treeFind\";\n\n// PathExplorer is the embeddable Path VFS console (RFC AL): the unified dirent\n// tree with directory + document CRUD, and an inline DocumentViewer for document\n// dirents. Identity (tenant + subject) is resolved server-side from the\n// authenticated principal — the component sends only `scope` (the subtree\n// SELECTOR) + the optional RFC AS `browse` override, never an authority grant.\n//\n// This is the decoupled port of the loomcycle Web UI's PathTreeView: routing is\n// replaced by internal selection state (with optional controlled\n// `path`/`onPathChange`), the runtime is reached through an injected data layer\n// (connection → client → dataLayer), and browse / principal arrive as props\n// instead of context hooks. Styles ship separately:\n// `import \"@loomcycle/explorer/styles.css\"`.\n\nconst NAME_RE = /^[A-Za-z0-9._-]+$/;\n\nconst SCOPES: PathScope[] = [\"user\", \"agent\", \"tenant\"];\n\n// Where the tree's collapsed state is remembered, beside its splitter width.\nconst TREE_KEY = \"loomcycle.explorer.collapsed.paths\";\n// Below this width the console shows one pane at a time: the tree, or what it\n// opened, with the other folded to its rail.\nconst NARROW_PX = 720;\n// The Path tree's width until the reader drags it. Narrow enough that the\n// document beside it, with its outline open, still reads at close to its\n// measure on a laptop-width window.\nconst TREE_WIDTH_PX = 320;\n// How long typing in the filter pauses before the runtime is asked (RFC HA):\n// each ask is a fresh filtered listing, so not one per keystroke.\nconst FILTER_DEBOUNCE_MS = 250;\n// The filtered tree's store while there is no filter to list.\nconst NO_DIRS: DirMap = new Map();\nconst noDirs = () => NO_DIRS;\nconst noSubscribe = () => () => {};\n\n// joinPath appends a leaf segment to a canonical parent dir (\"\" = root).\nfunction joinPath(dir: string, name: string): string {\n return `${dir}/${name}`;\n}\n\nfunction findNode(tree: PathNode[], fullPath: string): PathNode | undefined {\n for (const n of tree) {\n if (n.fullPath === fullPath) return n;\n const hit = findNode(n.children, fullPath);\n if (hit) return hit;\n }\n return undefined;\n}\n\nexport interface PathExplorerProps extends ExplorerDataSource {\n // ---- Theming. When set, the root carries data-theme; when omitted the\n // component inherits an ancestor's data-theme (dark is the default palette).\n theme?: \"light\" | \"dark\";\n\n // ---- Scope. The initial tree scope; the toolbar select lets the operator\n // switch it at runtime (internal state). Default \"user\".\n defaultScope?: PathScope;\n\n // ---- Selection. `path` + `onPathChange` make the selected path controlled\n // (so a host that routes can bridge URL ↔ selection); omit both for internal\n // state. On a scope switch the selection clears (onPathChange fires with\n // undefined). Mirrors the library's tab/onTabChange controlled pattern.\n path?: string;\n onPathChange?: (path: string | undefined) => void;\n\n // ---- RFC AS browse-by-subject override threaded into every path/document\n // call. Unset → the caller's own subject.\n browse?: BrowseScope;\n\n // ---- Authenticated principal — only `subject` is read (passed to\n // renderAssistant). Optional.\n principal?: Principal;\n\n // ---- Optional Document Assistant slot, forwarded to the embedded\n // DocumentViewer. Provide it to show an \"assistant\" toggle; omit → none.\n renderAssistant?: (ctx: AssistantContext) => ReactNode;\n\n // ---- Optional: have an annotation written again (tenant-scope documents),\n // forwarded to the embedded DocumentViewer. The host owns how (typically by\n // starting the annotating agent's run). Omit → no Regenerate.\n onRegenerateAnnotation?: (target: AnnotationTarget) => void | Promise<void>;\n // Whether the reader may edit annotations by hand (the operator plane; the\n // runtime refuses anyone else). Default false: no Edit is offered.\n canEditAnnotations?: boolean;\n\n // ---- Optional second navigator beside the Path tree (the @loomcycle/universe\n // star map). Provide it to show a `tree | stars` switch in the toolbar; the\n // tree stays the default. Omit → tree only, and nothing else is loaded.\n renderNavigator?: (ctx: NavigatorContext) => ReactNode;\n // Ask for a navigator: when set, and whenever it changes, the explorer\n // switches to it and remembers the choice as the toggle does. A host opening\n // a saved star-map view passes \"stars\". Ignored without renderNavigator.\n navigator?: NavigatorMode;\n\n // ---- Errors. Called on a tree-load failure (in addition to the inline\n // banner). The component NEVER redirects on 401 — the host owns the auth flow.\n onError?: (e: unknown) => void;\n}\n\nexport default function PathExplorer(props: PathExplorerProps) {\n const {\n theme,\n defaultScope,\n path,\n onPathChange,\n browse,\n principal,\n renderAssistant,\n renderNavigator,\n navigator,\n onError,\n onRegenerateAnnotation,\n canEditAnnotations,\n } = props;\n const resolved = useResolvedDataLayer(props);\n return (\n <ExplorerRoot theme={theme} dataLayer={resolved}>\n <PathExplorerBody\n defaultScope={defaultScope}\n path={path}\n onPathChange={onPathChange}\n browse={browse}\n principal={principal}\n renderAssistant={renderAssistant}\n renderNavigator={renderNavigator}\n navigator={navigator}\n onError={onError}\n onRegenerateAnnotation={onRegenerateAnnotation}\n canEditAnnotations={canEditAnnotations}\n />\n </ExplorerRoot>\n );\n}\n\ntype PathExplorerBodyProps = Omit<PathExplorerProps, keyof ExplorerDataSource | \"theme\">;\n\ninterface ModalField {\n key: string;\n label: string;\n placeholder?: string;\n value?: string;\n}\ninterface ModalState {\n title: string;\n message?: string;\n fields: ModalField[];\n submitLabel: string;\n danger?: boolean;\n onSubmit: (vals: Record<string, string>) => Promise<void>;\n}\n\nfunction PathExplorerBody({\n defaultScope,\n path: pathProp,\n onPathChange,\n browse: browseProp,\n principal,\n renderAssistant,\n renderNavigator,\n navigator: navigatorProp,\n onError,\n onRegenerateAnnotation,\n canEditAnnotations,\n}: PathExplorerBodyProps) {\n const data: ExplorerDataLayer = useExplorerData();\n\n const [scope, setScope] = useState<PathScope>(defaultScope ?? \"user\");\n const [internalSelected, setInternalSelected] = useState<string | undefined>(undefined);\n const [err, setErr] = useState<string | null>(null);\n const [modal, setModal] = useState<ModalState | null>(null);\n // The copy / move dialog: one document by id, or a folder's documents.\n const [transfer, setTransfer] = useState<\n { documentId?: string; underPath?: string; fromPath: string } | null\n >(null);\n // Directories the operator has opened. Collapsed by default: opening one is\n // what lists it, so nothing below the root is fetched until it is wanted.\n const [expanded, setExpanded] = useState<ReadonlySet<string>>(() => new Set());\n\n // Effective selection: controlled `path` prop overrides the internal state.\n const selectedPath = pathProp !== undefined ? pathProp : internalSelected;\n\n // onPathChange through a ref so the selection setter + scope-reset effect stay\n // stable (a parent passing an inline callback each render doesn't churn them).\n const onPathChangeRef = useRef(onPathChange);\n useEffect(() => {\n onPathChangeRef.current = onPathChange;\n }, [onPathChange]);\n const onErrorRef = useRef(onError);\n useEffect(() => {\n onErrorRef.current = onError;\n }, [onError]);\n\n // The trail of documents reached by following references (see lib/docTrail).\n // While it has entries, its LAST one is the document on screen — it may have\n // no path at all, so the tree selection cannot be what picks the document.\n const [trail, setTrail] = useState<Trail>([]);\n // navSeq numbers each navigation, so a path lookup that answers after the\n // reader has moved on is dropped instead of yanking the selection back.\n const navSeq = useRef(0);\n // The last path this component reported, to tell a controlled host's echo of\n // it from a path the host chose itself.\n const emittedPath = useRef<string | undefined>(undefined);\n\n // applySelection moves the tree selection without touching the trail — the\n // trail's own navigation uses it so the tree follows the opened document.\n const applySelection = useCallback((p: string | undefined) => {\n emittedPath.current = p;\n onPathChangeRef.current?.(p);\n setInternalSelected(p); // harmless when controlled; drives display when not\n }, []);\n\n // setSelected is a FRESH navigation — a tree click, a create/rename/delete, a\n // scope switch — and starts over: the trail records a chain of followed\n // references, and picking a document some other way is not a link in it.\n const setSelected = useCallback(\n (p: string | undefined) => {\n navSeq.current++;\n setTrail((t) => (t.length > 0 ? [] : t));\n applySelection(p);\n },\n [applySelection],\n );\n\n // A controlled host that moves `path` on its own (not echoing ours) is a fresh\n // navigation too.\n useEffect(() => {\n if (pathProp === undefined || pathProp === emittedPath.current) return;\n navSeq.current++;\n setTrail((t) => (t.length > 0 ? [] : t));\n }, [pathProp]);\n\n // Memoize browse on its primitives so an inline `browse={{...}}` doesn't churn\n // the fetch effect every render.\n const browse = useMemo<BrowseScope | undefined>(\n () =>\n browseProp && (browseProp.scopeId || browseProp.tenant)\n ? { scopeId: browseProp.scopeId, tenant: browseProp.tenant }\n : undefined,\n [browseProp?.scopeId, browseProp?.tenant],\n );\n\n // report hands a listing failure to the host. The tree already shows it\n // inline (root: the banner; a directory: its own row), so this never throws.\n const report = useCallback((e: unknown) => {\n onErrorRef.current?.(e);\n }, []);\n\n // One listing cache per (scope, subject): a new instance on a switch is also\n // what makes a previous subject's in-flight pages land nowhere. Every\n // listing asks for its folders' document counts (RFC HA); a runtime that\n // cannot count leaves them out and the count slots stay empty.\n const lazy = useMemo(\n () => new LazyPathTree(data, scope, browse, LS_PAGE_LIMIT, { withCounts: true }),\n [data, scope, browse],\n );\n const dirs = useSyncExternalStore(lazy.subscribe, lazy.getSnapshot);\n\n // Search and filter (RFC GZ): a second header line, closed until the search\n // icon or \"/\" opens it. The search covers the folders already listed; the\n // filter is the runtime's (RFC HA) and covers the whole tree (findCoverage).\n const [findOpen, setFindOpen] = useState(false);\n const [findMode, setFindMode] = useState<\"search\" | \"filter\">(\"search\");\n const [query, setQuery] = useState(\"\");\n const [filter, setFilter] = useState<TreeFilter>(NO_FILTER);\n const filtering = findOpen && findMode === \"filter\" && filterActive(filter);\n\n // The filter the runtime is asked with: the one typed, once typing pauses;\n // none at once when the filter is cleared or closed.\n const [asked, setAsked] = useState<TreeFilter>(NO_FILTER);\n useEffect(() => {\n const next = filtering ? filter : NO_FILTER;\n const t = setTimeout(() => setAsked(next), filtering ? FILTER_DEBOUNCE_MS : 0);\n return () => clearTimeout(t);\n }, [filtering, filter]);\n\n // A runtime that answers a filtered listing without filtering it (one from\n // before RFC HA: no echo of the filters), or refuses it (a scope whose\n // documents it cannot read), gets the filter applied here instead, to the\n // folders already listed — until the tree is reloaded or switched.\n const [localFilterIn, setLocalFilterIn] = useState<LazyPathTree | null>(null);\n const localOnly = localFilterIn === lazy;\n const askedKey = `${asked.name.trim()}\\u0000${asked.type}\\u0000${asked.status}`;\n // The filtered tree is a listing cache of its own, one per filter: each of\n // its folders is a one-level ls with the filters, opened as the reader (or\n // autoOpen) opens it.\n const flazy = useMemo(() => {\n const f = lsFilters(asked);\n return f && !localOnly\n ? new LazyPathTree(data, scope, browse, LS_PAGE_LIMIT, { withCounts: true, filters: f })\n : null;\n // `asked` is read through its key, so an equal filter keeps its listing.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [data, scope, browse, askedKey, localOnly]);\n const fdirs = useSyncExternalStore(flazy?.subscribe ?? noSubscribe, flazy?.getSnapshot ?? noDirs);\n // The folders open in the filtered tree: its own set, so closing the filter\n // gives back the tree as the reader left it. autoTried is every folder the\n // filtered tree opened by itself, never opened by it again.\n const [filterOpen, setFilterOpen] = useState<ReadonlySet<string>>(() => new Set());\n const autoTried = useRef<Set<string>>(new Set());\n useEffect(() => {\n setFilterOpen(new Set());\n autoTried.current = new Set();\n // A refusal is not reported: it falls back to the local filter (below).\n flazy?.loadDir(\"\").catch(() => {});\n }, [flazy]);\n const froot = fdirs.get(\"\");\n const serverFiltered = !!flazy && !!froot?.loaded && findCoverage(froot) === \"subtree\";\n const fsettled = !!froot && !froot.loading && (froot.loaded || froot.error !== undefined);\n useEffect(() => {\n if (flazy && fsettled && !serverFiltered) setLocalFilterIn(lazy);\n }, [flazy, fsettled, serverFiltered, lazy]);\n useEffect(() => {\n if (!flazy) return;\n for (const d of filterOpen) {\n if (!fdirs.has(d)) flazy.loadDir(d).catch(report);\n }\n }, [flazy, filterOpen, fdirs, report]);\n const ftree = useMemo(() => (serverFiltered ? buildLazyTree(fdirs) : []), [serverFiltered, fdirs]);\n // Open the folders the filter kept, breadth first, up to AUTO_OPEN_FOLDERS:\n // each leads to a match, so the reader sees where the matches are without\n // opening them one by one; past the bound they open on a click.\n useEffect(() => {\n if (!serverFiltered) return;\n const more = autoOpen(ftree, filterOpen, autoTried.current);\n if (more.length === 0) return;\n more.forEach((p) => autoTried.current.add(p));\n setFilterOpen((prev) => new Set([...prev, ...more]));\n }, [serverFiltered, ftree, filterOpen]);\n\n // The navigator slot (renderNavigator): which navigator shows, whether it has\n // the whole explorer, and what it is told. navReload bumps on every change the\n // explorer makes to the tree, so the star map reloads with it.\n const [navMode, setNavModeState] = useState<NavigatorMode>(() =>\n renderNavigator ? readNavigatorMode(globalThis.localStorage) : \"tree\",\n );\n const starsOn = !!renderNavigator && navMode === \"stars\";\n const setNavMode = useCallback((m: NavigatorMode) => {\n setNavModeState(m);\n writeNavigatorMode(globalThis.localStorage, m);\n if (m === \"tree\") setMaximized(false);\n }, []);\n const [maximized, setMaximized] = useState(false);\n const [navReload, setNavReload] = useState(0);\n\n // The tree pane collapses to a rail (RFC GZ), remembered per browser. On a\n // narrow console one pane shows at a time: the tree while the reader picks,\n // then what they picked, with the tree on its rail.\n const consoleRef = useRef<HTMLDivElement>(null);\n const narrow = useNarrow(consoleRef, NARROW_PX);\n const [treeCollapsed, setTreeCollapsed] = usePersistedFlag(TREE_KEY);\n const [narrowTree, setNarrowTree] = useState(() => !pathProp);\n const treeHidden = narrow ? !narrowTree : treeCollapsed && !starsOn;\n const setTreeHidden = useCallback(\n (hide: boolean) => (narrow ? setNarrowTree(!hide) : setTreeCollapsed(hide)),\n [narrow, setTreeCollapsed],\n );\n useEffect(() => {\n if (renderNavigator && navigatorProp) setNavMode(navigatorProp);\n // Only a change of the request switches; a reader's later toggle stands.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [navigatorProp]);\n // The chunk the viewer is on (reported by it), and a pending request to move\n // it (a star picked inside the open document, or the landing chunk of one\n // being opened).\n const [liveChunk, setLiveChunk] = useState<\n { documentId: string; chunkId?: string } | undefined\n >();\n const [focus, setFocus] = useState<\n { documentId: string; chunkId?: string; seq: number } | undefined\n >();\n const invalidate = useCallback(\n (p: string, opts?: { dropSubtree?: boolean }) => {\n setNavReload((n) => n + 1);\n // The filtered tree, if one is shown, changes with it.\n flazy?.invalidate(p, opts).catch(() => {});\n return lazy.invalidate(p, opts);\n },\n [lazy, flazy],\n );\n\n // RFC BN: per-document type/status + color settings, so PathTree can color +\n // badge document rows. Fetched per listed page (≤ one page of ids per call —\n // the bound documents_summary is sized for) and merged, rather than once for a\n // whole tree that is no longer loaded at once. Best-effort — a failure just\n // leaves those rows neutral. `requested` keeps a page from being re-asked on\n // every listing change; summaryGen drops answers from before a reset.\n const [summaries, setSummaries] = useState<Map<string, DocSummary>>(() => new Map());\n const requested = useRef<Set<string>>(new Set());\n const summaryGen = useRef(0);\n const resetSummaries = useCallback(() => {\n summaryGen.current++;\n requested.current = new Set();\n setSummaries(new Map());\n }, []);\n\n // Start over whenever the scope/browse changes (and on mount). Clear the\n // selection on a CHANGE (not on mount) so a stale path from the previous\n // scope/subject doesn't drive the detail pane — but the first run must respect\n // a controlled parent's initial `path` (clearing on mount would fire\n // onPathChange(undefined) and clobber it).\n const firstLoad = useRef(true);\n useEffect(() => {\n if (firstLoad.current) {\n firstLoad.current = false;\n } else {\n setSelected(undefined);\n setErr(null);\n setExpanded(new Set());\n resetSummaries();\n }\n lazy.loadDir(\"\").catch(report);\n }, [lazy, setSelected, resetSummaries, report]);\n\n // An opened directory that has never been listed gets listed. Keyed on the\n // listings too, so a directory whose cache was dropped (moved away and back)\n // while it stayed open re-lists instead of sitting empty. A FAILED listing is\n // left for its retry row, so an outage doesn't turn into a request loop.\n useEffect(() => {\n for (const d of expanded) {\n if (!dirs.has(d)) lazy.loadDir(d).catch(report);\n }\n }, [lazy, expanded, dirs, report]);\n\n // Deep link / post-mutation selection: open the selection's ancestors and list\n // them — paging a directory until the selected entry shows, since it may sit\n // past the first page. Skipped on a scope/subject switch: that render still\n // carries the previous selection, which the effect above is clearing.\n const revealedIn = useRef<LazyPathTree | null>(null);\n useEffect(() => {\n const switched = revealedIn.current !== null && revealedIn.current !== lazy;\n revealedIn.current = lazy;\n if (!selectedPath || switched) return;\n const ancestors = ancestorsOf(selectedPath).filter((d) => d !== \"\");\n setExpanded((prev) => {\n if (ancestors.every((d) => prev.has(d))) return prev;\n const next = new Set(prev);\n ancestors.forEach((d) => next.add(d));\n return next;\n });\n lazy.reveal(selectedPath).catch(report);\n }, [lazy, selectedPath, report]);\n\n useEffect(() => {\n const fresh: string[] = [];\n for (const listing of [...dirs.values(), ...fdirs.values()]) {\n for (const id of documentIdsOf(listing.entries)) {\n if (!requested.current.has(id)) {\n requested.current.add(id);\n fresh.push(id);\n }\n }\n }\n const gen = summaryGen.current;\n for (let i = 0; i < fresh.length; i += LS_PAGE_LIMIT) {\n data\n .documentsSummary({ documentIds: fresh.slice(i, i + LS_PAGE_LIMIT) }, scope, browse)\n .then((resp) => {\n if (summaryGen.current !== gen) return;\n setSummaries((prev) => {\n const m = new Map(prev);\n for (const d of resp.documents ?? []) m.set(d.document_id, d);\n return m;\n });\n })\n .catch(() => {});\n }\n }, [data, dirs, fdirs, scope, browse]);\n\n const tree = useMemo(() => buildLazyTree(dirs), [dirs]);\n\n const [hitAt, setHitAt] = useState(0);\n const findInput = useRef<HTMLInputElement>(null);\n // The runtime's filtered tree is drawn once it has answered with the filters\n // it applied; until then (and on a runtime that does not filter) the filter\n // is applied here to the folders already listed, and the line says so.\n const serverTree = filtering && serverFiltered;\n const coverage = findCoverage(findMode === \"filter\" && serverTree ? froot : dirs.get(\"\"));\n const listId = useId();\n const typeWidened = serverTree && filter.type !== \"\" ? Math.max(0, (froot?.typeExpandedTo?.length ?? 0) - 1) : 0;\n const filtered = useMemo(\n () => (filtering && !serverTree ? filterTree(tree, filter, summaries) : undefined),\n [filtering, serverTree, tree, filter, summaries],\n );\n const choices = useMemo(\n () =>\n findOpen && findMode === \"filter\" ? filterChoices([tree, ftree], summaries) : { types: [], statuses: [] },\n [findOpen, findMode, tree, ftree, summaries],\n );\n\n // refresh re-lists the root and every open directory, then re-reveals the\n // selection (it may have been on a page the reload folded away).\n const refresh = useCallback(async () => {\n setErr(null);\n resetSummaries();\n setNavReload((n) => n + 1);\n // A reload asks the runtime to filter again, even one that did not before.\n setLocalFilterIn(null);\n await Promise.all([\n lazy.refresh(expanded).catch(report),\n flazy?.refresh(filterOpen).catch(() => {}),\n ]);\n if (selectedPath) await lazy.reveal(selectedPath).catch(report);\n }, [lazy, flazy, expanded, filterOpen, selectedPath, resetSummaries, report]);\n\n const toggle = useCallback((dir: string) => {\n setExpanded((prev) => {\n const next = new Set(prev);\n if (next.has(dir)) next.delete(dir);\n else next.add(dir);\n return next;\n });\n }, []);\n\n const toggleFiltered = useCallback((dir: string) => {\n setFilterOpen((prev) => {\n const next = new Set(prev);\n if (next.has(dir)) next.delete(dir);\n else next.add(dir);\n return next;\n });\n }, []);\n\n // Paging and retry act on the tree that is drawn: the filtered one while it is.\n const shownLazy = serverTree && flazy ? flazy : lazy;\n const loadMore = useCallback((dir: string) => shownLazy.loadMore(dir).catch(report), [shownLazy, report]);\n const retry = useCallback(\n (dir: string) => {\n const listing = shownLazy.getSnapshot().get(dir);\n (listing?.loaded ? shownLazy.loadMore(dir) : shownLazy.loadDir(dir)).catch(report);\n },\n [shownLazy, report],\n );\n\n // A pick in the filtered tree is found there until the full tree has\n // revealed it (the selection effect lists its folders).\n const selected = useMemo(\n () =>\n selectedPath ? (findNode(tree, selectedPath) ?? (serverTree ? findNode(ftree, selectedPath) : undefined)) : undefined,\n [tree, ftree, serverTree, selectedPath],\n );\n const rootErr = dirs.get(\"\")?.error;\n const selectedAnnotation =\n selected?.kind === \"directory\" ? selected.children.find(isAnnotationEntry) : undefined;\n\n // Whether the selected directory has its own dirent or exists only through its\n // descendants. A one-level listing reports both as `directory`, so this asks\n // per selection; a data layer without pathIsStored just omits the row.\n const selectedDir = selected?.kind === \"directory\" ? selected.fullPath : undefined;\n const [stored, setStored] = useState<{ path: string; explicit: boolean } | null>(null);\n useEffect(() => {\n if (!selectedDir || !data.pathIsStored) return;\n let cancelled = false;\n data.pathIsStored(selectedDir, scope, browse).then(\n (explicit) => {\n if (!cancelled) setStored({ path: selectedDir, explicit });\n },\n () => {},\n );\n return () => {\n cancelled = true;\n };\n }, [data, selectedDir, scope, browse]);\n // Only a directory can be implicit; every other kind is a stored entry.\n const storedLabel = !selected\n ? undefined\n : selected.kind !== \"directory\"\n ? \"yes\"\n : stored?.path === selected.fullPath\n ? stored.explicit\n ? \"yes\"\n : \"implicit (no entry)\"\n : undefined;\n\n // The directory new items are created under: the selected directory, the\n // parent of a selected leaf, or root.\n const currentDir = useMemo(() => {\n if (!selected) return \"\";\n return selected.kind === \"directory\" ? selected.fullPath : parentPathOf(selected.fullPath);\n }, [selected]);\n const currentDirLabel = currentDir || \"/\";\n\n // Search runs under the selected folder, else the whole tree. The base is\n // taken when the search line opens, so stepping onto a match (which may be\n // selected later) does not move the ground under the search.\n const [searchBase, setSearchBase] = useState(\"\");\n const searching = findOpen && findMode === \"search\" && query.trim() !== \"\";\n const hits = useMemo(\n () => (searching ? searchListed(tree, searchBase, query) : []),\n [searching, tree, searchBase, query],\n );\n const hitSet = useMemo(() => new Set(hits.map((h) => h.fullPath)), [hits]);\n const current = hits.length > 0 ? hits[Math.min(hitAt, hits.length - 1)] : undefined;\n // Every folder above the match the search is on opens, so it is drawn.\n useEffect(() => {\n if (!current) return;\n const above = ancestorsOf(current.fullPath).filter((d) => d !== \"\");\n setExpanded((prev) => {\n if (above.every((d) => prev.has(d))) return prev;\n const next = new Set(prev);\n above.forEach((d) => next.add(d));\n return next;\n });\n }, [current]);\n const treeBox = useRef<HTMLDivElement>(null);\n useEffect(() => {\n if (!current) return;\n const row = treeBox.current?.querySelector<HTMLElement>(\".etree-row.search-current\");\n row?.scrollIntoView?.({ block: \"nearest\" });\n }, [current, expanded]);\n\n const openFind = useCallback(() => {\n setSearchBase(selected?.kind === \"directory\" ? selected.fullPath : \"\");\n setFindOpen(true);\n setHitAt(0);\n // Focus after the line renders.\n setTimeout(() => findInput.current?.focus(), 0);\n }, [selected]);\n const closeFind = useCallback(() => {\n setFindOpen(false);\n setQuery(\"\");\n setFilter(NO_FILTER);\n setHitAt(0);\n }, []);\n const step = (by: number) => {\n if (hits.length === 0) return;\n setHitAt((i) => (((Math.min(i, hits.length - 1) + by) % hits.length) + hits.length) % hits.length);\n };\n\n\n const newFolder = useCallback(() => {\n setModal({\n title: `New folder in ${currentDirLabel}`,\n fields: [{ key: \"name\", label: \"Folder name\", placeholder: \"e.g. launches\" }],\n submitLabel: \"Create\",\n onSubmit: async (v) => {\n const name = v.name.trim();\n if (!NAME_RE.test(name)) throw new Error(\"name may contain only [A-Za-z0-9._-]\");\n const p = joinPath(currentDir, name);\n await data.pathMkdir(p, scope, browse);\n await invalidate(p).catch(report);\n setSelected(p);\n },\n });\n }, [data, invalidate, currentDir, currentDirLabel, scope, browse, report, setSelected]);\n\n const newDocument = useCallback(() => {\n setModal({\n title: `New document in ${currentDirLabel}`,\n fields: [\n { key: \"name\", label: \"Path name\", placeholder: \"e.g. launch-plan\" },\n { key: \"title\", label: \"Title\", placeholder: \"e.g. Launch Plan\" },\n ],\n submitLabel: \"Create\",\n onSubmit: async (v) => {\n const name = v.name.trim();\n if (!NAME_RE.test(name)) throw new Error(\"name may contain only [A-Za-z0-9._-]\");\n const title = v.title.trim() || name;\n const p = joinPath(currentDir, name);\n await data.documentCreate(title, p, scope, browse);\n await invalidate(p).catch(report);\n setSelected(p);\n },\n });\n }, [data, invalidate, currentDir, currentDirLabel, scope, browse, report, setSelected]);\n\n const renameSelected = useCallback(() => {\n if (!selected) return;\n setModal({\n title: `Rename / move ${selected.fullPath}`,\n fields: [{ key: \"to\", label: \"New path\", value: selected.fullPath }],\n submitLabel: \"Move\",\n onSubmit: async (v) => {\n const to = v.to.trim();\n if (!to.startsWith(\"/\")) throw new Error(\"path must start with /\");\n await data.pathMv(selected.fullPath, to, scope, browse);\n await Promise.all([\n invalidate(selected.fullPath, { dropSubtree: true }),\n invalidate(to),\n ]).catch(report);\n setSelected(to);\n },\n });\n }, [data, invalidate, selected, scope, browse, report, setSelected]);\n\n const deleteSelected = useCallback(() => {\n if (!selected) return;\n if (selected.kind === \"document\") {\n const ref = selected.resourceRef as { document_id?: string } | undefined;\n const id = ref?.document_id;\n setModal({\n title: `Delete document ${selected.fullPath}`,\n message:\n \"This deletes the document, all its chunks, and its path entry. This cannot be undone.\",\n fields: [],\n submitLabel: \"Delete\",\n danger: true,\n onSubmit: async () => {\n if (!id) throw new Error(\"this document dirent has no document_id\");\n await data.documentDelete(id, scope, browse);\n await invalidate(selected.fullPath).catch(report);\n setSelected(undefined);\n },\n });\n return;\n }\n // Directory: cascade-delete contained Documents (so no orphaned content),\n // then remove the dirent subtree — in every scope: a tenant-scope branch\n // delete used to drop only the names, leaving its documents unreachable.\n // The tree holds only the directories that were opened, so the branch is\n // listed in full here — the confirmation must count, and the delete must\n // reach, every Document under it, not just the ones on screen.\n const target = selected;\n setErr(null);\n void (async () => {\n let subtree;\n try {\n subtree = await listSubtree(data, target.fullPath, scope, browse);\n } catch (e) {\n setErr(`could not list ${target.fullPath} for delete: ${e instanceof Error ? e.message : String(e)}`);\n return;\n }\n const docIds = documentIdsOf(subtree);\n setModal({\n title: `Delete branch ${target.fullPath}`,\n message:\n subtree.length === 0\n ? \"This removes the (empty) folder.\"\n : `This removes the folder and everything under it` +\n (docIds.length > 0\n ? ` — including ${docIds.length} document(s), whose chunks are deleted.`\n : \".\"),\n fields: [],\n submitLabel: \"Delete\",\n danger: true,\n onSubmit: async () => {\n for (const id of docIds) {\n await data.documentDelete(id, scope, browse);\n }\n await data.pathRm(target.fullPath, scope, true, browse);\n await invalidate(target.fullPath, { dropSubtree: true }).catch(report);\n setSelected(undefined);\n },\n });\n })();\n }, [data, invalidate, selected, scope, browse, report, setSelected]);\n\n const mutable = selected && (selected.kind === \"directory\" || selected.kind === \"document\");\n\n // Copy or move the selected document, or every document under the selected\n // folder, into another scope. Hidden when the data layer cannot do it.\n const canTransfer = !!data.documentsTransfer && !!mutable;\n const transferSelected = useCallback(() => {\n if (!selected) return;\n if (selected.kind === \"document\") {\n const id = (selected.resourceRef as { document_id?: string } | undefined)?.document_id;\n if (!id) {\n setErr(\"this document entry has no document_id\");\n return;\n }\n setTransfer({ documentId: id, fromPath: selected.fullPath });\n return;\n }\n setTransfer({ underPath: selected.fullPath, fromPath: selected.fullPath });\n }, [selected]);\n // After a real copy or move: a move took the selection out of this scope; a\n // copy into this scope added names under the new path.\n const transferDone = useCallback(\n (req: TransferRequest) => {\n if (req.op === \"move\") {\n void invalidate(req.from, { dropSubtree: true }).catch(report);\n setTrail([]);\n setSelected(undefined);\n return;\n }\n if (req.toScope === scope) void invalidate(req.to).catch(report);\n },\n [invalidate, report, scope, setSelected],\n );\n\n // The document on screen: the trail's last entry while references are being\n // followed, else the document the tree selection names.\n const view = useMemo<DocLocation | undefined>(() => {\n if (trail.length > 0) return trail[trail.length - 1];\n if (selected?.kind !== \"document\") return undefined;\n return {\n documentId: (selected.resourceRef as { document_id?: string })?.document_id ?? \"\",\n path: selected.fullPath,\n title: selected.name,\n };\n }, [trail, selected]);\n\n // openDocument follows a reference into another document. The tree follows\n // when that document's path is known: first from the directories already\n // listed, then by asking the data layer. Until (or unless) a path turns up the\n // document is open by id, with the tree selection cleared.\n const openDocument = useCallback(\n (target: DocLocation, from: DocLocation) => {\n const seq = ++navSeq.current;\n const known = findDocumentPath(lazy.getSnapshot(), target.documentId);\n setTrail(followReference(trail, { ...from, path: view?.path }, { ...target, path: known }));\n applySelection(known);\n if (known || !data.documentPath) return;\n data.documentPath(target.documentId, scope, browse).then(\n (p) => {\n if (!p || navSeq.current !== seq) return;\n setTrail((t) => amendCurrent(t, target.documentId, { path: p }));\n applySelection(p);\n },\n () => {}, // best-effort: the document is already open by id\n );\n },\n [data, lazy, trail, view?.path, scope, browse, applySelection],\n );\n\n // jumpToCrumb returns to an earlier document on the trail (Back = the previous\n // one), restoring the chunk that was selected there.\n const jumpToCrumb = useCallback(\n (index: number) => {\n const next = jumpTo(trail, index);\n if (next === trail) return;\n navSeq.current++;\n setTrail(next);\n applySelection(next[next.length - 1].path);\n },\n [trail, applySelection],\n );\n\n const onDocTitle = useCallback(\n (documentId: string, title: string) => setTrail((t) => amendCurrent(t, documentId, { title })),\n [],\n );\n\n // A pick in the navigator. Another chunk of the open document moves the\n // viewer in place; another document opens as a fresh navigation — by its Path\n // name when it has one (so the tree follows), else by id.\n const onNavigatorSelect = useCallback(\n (sel: NavigatorSelection & { documentId: string }) => {\n setFocus((f) => ({\n documentId: sel.documentId,\n chunkId: sel.chunkId,\n seq: (f?.seq ?? 0) + 1,\n }));\n if (view?.documentId === sel.documentId) return;\n if (sel.path) {\n setSelected(sel.path);\n return;\n }\n navSeq.current++;\n setTrail([{ documentId: sel.documentId, chunkId: sel.chunkId }]);\n applySelection(undefined);\n },\n [view?.documentId, setSelected, applySelection],\n );\n\n const navigatorCtx = useMemo<NavigatorContext>(\n () => ({\n scope,\n browse,\n selection: {\n documentId: view?.documentId,\n chunkId:\n liveChunk && liveChunk.documentId === view?.documentId ? liveChunk.chunkId : undefined,\n path: view?.path,\n },\n onSelect: onNavigatorSelect,\n reloadToken: navReload,\n maximized,\n onToggleMaximize: () => setMaximized((m) => !m),\n subject: principal?.subject,\n }),\n [\n scope,\n browse,\n view?.documentId,\n view?.path,\n liveChunk,\n onNavigatorSelect,\n navReload,\n maximized,\n principal?.subject,\n ],\n );\n const focusForView = focus && view && focus.documentId === view.documentId ? focus : undefined;\n\n // rename / delete act on the tree's selected entry, so they are offered only\n // when that entry IS the document on screen (not while its path is unknown, or\n // its directory is still being listed).\n const viewIsSelected =\n !!view?.path && selected?.kind === \"document\" && selected.fullPath === view.path;\n\n // A pick in the tree. On a narrow console a document takes the screen and\n // the tree goes to its rail; a folder keeps the tree, to browse on.\n const pick = useCallback(\n (n: PathNode) => {\n setSelected(n.fullPath);\n if (narrow && n.kind !== \"directory\") setNarrowTree(false);\n },\n [narrow, setSelected],\n );\n\n // A breadcrumb segment selects its folder and shows it in the tree.\n const revealFolder = useCallback(\n (folder: string) => {\n setSelected(folder);\n // Open the folder too, so it is listed and shows what it holds.\n setExpanded((prev) => (prev.has(folder) ? prev : new Set(prev).add(folder)));\n setTreeHidden(false);\n if (navMode === \"stars\") setNavMode(\"tree\");\n },\n [setSelected, setTreeHidden, navMode, setNavMode],\n );\n\n // A breadcrumb segment's card: a folder's from the tree (its _annotation's\n // brief), the document's from the summaries the tree loaded, else read by id.\n const crumbCard = useCallback(\n (segment: string, isDocument: boolean): CardSpec | undefined => {\n const node = findNode(tree, segment);\n if (!isDocument) return node ? nodeCard(node, summaries) : { title: segment.slice(segment.lastIndexOf(\"/\") + 1), type: \"folder\", path: segment };\n if (!view?.documentId) return undefined;\n const s = node ? documentSummaryOf(node, summaries) : undefined;\n return documentCard(\n view.documentId,\n s?.title || view.title || segment.slice(segment.lastIndexOf(\"/\") + 1),\n { data, scope, browse },\n s ? { type: s.type, status: s.status, brief: s.brief ?? \"\" } : undefined,\n );\n },\n [tree, summaries, view?.documentId, view?.title, data, scope, browse],\n );\n\n // Keyboard: \"[\" folds the tree, \"/\" opens the search line.\n const keysRef = useRef<(e: KeyboardEvent) => void>(() => {});\n keysRef.current = (e: KeyboardEvent) => {\n if (!shortcutApplies(e, consoleRef.current)) return;\n if (e.key === \"[\" && !starsOn) setTreeHidden(!treeHidden);\n else if (e.key === \"/\" && !starsOn) {\n setTreeHidden(false);\n openFind();\n } else return;\n e.preventDefault();\n };\n useEffect(() => {\n const onKey = (e: KeyboardEvent) => keysRef.current(e);\n window.addEventListener(\"keydown\", onKey);\n return () => window.removeEventListener(\"keydown\", onKey);\n }, []);\n\n // The folder's annotation: its `_annotation` document's summary is the\n // folder's card, shown as the detail pane's content.\n const folderCard = selected?.kind === \"directory\" ? nodeCard(selected, summaries) : undefined;\n\n return (\n <>\n <div className={`paths-console${narrow ? \" narrow\" : \"\"}`} ref={consoleRef}>\n <Splitter\n className={starsOn ? \"paths-view paths-view--stars\" : \"paths-view\"}\n defaultLeftWidth={starsOn ? 720 : TREE_WIDTH_PX}\n minLeftWidth={280}\n minRightWidth={300}\n storageKey={starsOn ? \"loomcycle.explorer.split.stars\" : \"loomcycle.explorer.split.paths\"}\n hideRight={(starsOn && maximized) || (narrow && !treeHidden)}\n hideLeft={treeHidden}\n onHandleDoubleClick={starsOn ? undefined : () => setTreeHidden(true)}\n leftRail={\n <PaneRail\n side=\"left\"\n label=\"Path tree\"\n icon=\"tree\"\n shortcut=\"[\"\n onExpand={() => setTreeHidden(false)}\n />\n }\n >\n <div className=\"left\">\n <div className=\"paths-toolbar\">\n {/* One line (RFC GZ): scope, tree/stars, search, one \"+\" menu,\n reload, and the edge's collapse control. The subject is the\n topbar's, and the folder a new item goes into is named by the\n create dialog. */}\n <div className=\"paths-scope\" role=\"group\" aria-label=\"Scope\">\n {SCOPES.map((s) => (\n <button\n key={s}\n type=\"button\"\n aria-pressed={scope === s}\n className={scope === s ? \"active\" : undefined}\n onClick={() => setScope(s)}\n title={`Browse the ${s} scope`}\n >\n {s}\n </button>\n ))}\n </div>\n {renderNavigator && (\n <div className=\"paths-nav-switch\" role=\"group\" aria-label=\"Navigator\">\n <button\n type=\"button\"\n aria-pressed={!starsOn}\n className={!starsOn ? \"active\" : undefined}\n onClick={() => setNavMode(\"tree\")}\n title=\"Browse the Path tree\"\n >\n tree\n </button>\n <button\n type=\"button\"\n aria-pressed={starsOn}\n className={starsOn ? \"active\" : undefined}\n onClick={() => setNavMode(\"stars\")}\n title=\"Browse the scope as a 3D star map\"\n >\n stars\n </button>\n </div>\n )}\n <div className=\"paths-toolbar-actions\">\n {!starsOn && (\n <button\n type=\"button\"\n className=\"paths-find-toggle\"\n aria-pressed={findOpen}\n aria-controls=\"paths-find\"\n aria-keyshortcuts=\"/\"\n onClick={() => (findOpen ? closeFind() : openFind())}\n title=\"Search and filter the tree (/)\"\n aria-label=\"Search and filter the tree\"\n >\n <PaneIcon kind=\"search\" />\n </button>\n )}\n {!starsOn && <CreateMenu dir={currentDirLabel} onNewFolder={newFolder} onNewDocument={newDocument} />}\n <button type=\"button\" onClick={() => void refresh()} title=\"Reload the tree\" aria-label=\"Reload the tree\">\n ↻\n </button>\n {!starsOn && (\n <CollapseButton label=\"Path tree\" side=\"left\" shortcut=\"[\" onClick={() => setTreeHidden(true)} />\n )}\n </div>\n </div>\n {findOpen && !starsOn && (\n <div className=\"paths-find\" id=\"paths-find\" role=\"search\">\n <div className=\"paths-find-mode\" role=\"group\" aria-label=\"Search or filter\">\n {([\"search\", \"filter\"] as const).map((m) => (\n <button\n key={m}\n type=\"button\"\n aria-pressed={findMode === m}\n className={findMode === m ? \"active\" : undefined}\n onClick={() => {\n setFindMode(m);\n setHitAt(0);\n }}\n >\n {m}\n </button>\n ))}\n </div>\n <input\n ref={findInput}\n className=\"paths-find-input\"\n type=\"search\"\n value={findMode === \"search\" ? query : filter.name}\n placeholder={findMode === \"search\" ? \"Find a name\" : \"Name\"}\n aria-label={findMode === \"search\" ? \"Find a name in the tree\" : \"Filter by name\"}\n aria-describedby=\"paths-find-note\"\n onChange={(e) => {\n const v = e.target.value;\n if (findMode === \"search\") {\n setQuery(v);\n setHitAt(0);\n } else setFilter((f) => ({ ...f, name: v }));\n }}\n onKeyDown={(e) => {\n if (e.key === \"Escape\") {\n e.preventDefault();\n closeFind();\n } else if (e.key === \"Enter\" && findMode === \"search\") {\n e.preventDefault();\n step(e.shiftKey ? -1 : 1);\n }\n }}\n />\n {findMode === \"filter\" && (\n <>\n {/* Free text with suggestions: any type or status can be\n typed (the runtime filters by it), and what the trees\n have shown is offered. Debounced with the name. */}\n <input\n className=\"paths-find-field\"\n type=\"search\"\n value={filter.type}\n placeholder=\"any type\"\n aria-label=\"Filter by type\"\n list={`${listId}-types`}\n autoComplete=\"off\"\n spellCheck={false}\n onChange={(e) => setFilter((f) => ({ ...f, type: e.target.value }))}\n onKeyDown={(e) => {\n if (e.key === \"Escape\") {\n e.preventDefault();\n closeFind();\n }\n }}\n />\n <datalist id={`${listId}-types`}>\n {choices.types.map((t) => (\n <option key={t} value={t} />\n ))}\n </datalist>\n <input\n className=\"paths-find-field\"\n type=\"search\"\n value={filter.status}\n placeholder=\"any status\"\n aria-label=\"Filter by status\"\n list={`${listId}-statuses`}\n autoComplete=\"off\"\n spellCheck={false}\n onChange={(e) => setFilter((f) => ({ ...f, status: e.target.value }))}\n onKeyDown={(e) => {\n if (e.key === \"Escape\") {\n e.preventDefault();\n closeFind();\n }\n }}\n />\n <datalist id={`${listId}-statuses`}>\n {choices.statuses.map((t) => (\n <option key={t} value={t} />\n ))}\n </datalist>\n </>\n )}\n <span className=\"paths-find-note\" id=\"paths-find-note\" role=\"status\">\n {findMode === \"search\" && query.trim() !== \"\" && (\n <span className=\"paths-find-count\">\n {hits.length === 0 ? \"no match\" : `${Math.min(hitAt, hits.length - 1) + 1} of ${hits.length}`}\n </span>\n )}\n {coverageLabel(findMode, coverage)}\n {findMode === \"search\" && searchBase !== \"\" && ` under ${searchBase}`}\n {typeWidened > 0 && ` · ${filter.type} with ${typeWidened} subtype${typeWidened === 1 ? \"\" : \"s\"}`}\n </span>\n <button type=\"button\" className=\"paths-find-close\" onClick={closeFind} aria-label=\"Close search\">\n <PaneIcon kind=\"close\" />\n </button>\n </div>\n )}\n {(err || rootErr) && <div className=\"paths-err\">{err || rootErr}</div>}\n {starsOn && renderNavigator ? (\n <div className=\"paths-navigator\">{renderNavigator(navigatorCtx)}</div>\n ) : (\n <div className=\"paths-tree-box\" ref={treeBox}>\n <PathTree\n tree={serverTree ? ftree : filtered ? filtered.tree : tree}\n root={serverTree ? froot : dirs.get(\"\")}\n expanded={\n serverTree ? filterOpen : filtered ? new Set([...expanded, ...filtered.open]) : expanded\n }\n onToggle={serverTree ? toggleFiltered : toggle}\n filtered={serverTree}\n onLoadMore={loadMore}\n onRetry={retry}\n selectedPath={selectedPath}\n onSelect={pick}\n summaries={summaries}\n searchHits={searching ? hitSet : undefined}\n searchCurrent={current?.fullPath}\n />\n </div>\n )}\n </div>\n <div className=\"right\">\n {view ? (\n <div className=\"paths-doc\">\n <DocTrail trail={trail} onJump={jumpToCrumb} />\n {/* Keyed on the trail depth: every step along the trail changes it,\n so the viewer remounts and lands on that step's chunk. A plain\n tree selection (depth 0) keeps the viewer mounted, as before. */}\n <DocumentViewerBody\n key={trail.length}\n documentId={view.documentId}\n scope={scope}\n titleHint={view.title}\n browse={browse}\n principal={principal}\n renderAssistant={renderAssistant}\n initialChunkId={view.chunkId ?? focusForView?.chunkId}\n onOpenDocument={openDocument}\n onTitle={onDocTitle}\n onChunkSelect={(chunkId) => setLiveChunk({ documentId: view.documentId, chunkId })}\n focusChunk={focusForView}\n onRegenerateAnnotation={onRegenerateAnnotation}\n canEditAnnotations={canEditAnnotations}\n onAnnotationChanged={() => void refresh()}\n pathLabel={\n view.path ? (\n <Breadcrumb path={view.path} onFolder={revealFolder} cardFor={crumbCard} />\n ) : (\n <span\n className=\"paths-doc-path paths-doc-unfiled\"\n title=\"Opened by id — no entry for this document was found in the Path tree\"\n >\n <em>not in the tree</em>\n </span>\n )\n }\n documentActions={\n viewIsSelected\n ? {\n rename: renameSelected,\n transfer: canTransfer ? transferSelected : undefined,\n delete: deleteSelected,\n }\n : undefined\n }\n />\n </div>\n ) : selected ? (\n <div className=\"paths-detail\">\n <h2>\n <span className=\"paths-detail-kind\">{selected.kind}</span>\n <code>{selected.fullPath}</code>\n </h2>\n {/* A folder's content is its card (RFC GZ): its _annotation's\n brief, read from the tree, never a row of its own. */}\n {folderCard && (\n <div className=\"paths-detail-card\">\n <CardBody info={{ ...folderCard, path: undefined }} />\n </div>\n )}\n <dl className=\"paths-detail-meta\">\n <dt>scope</dt>\n <dd>{scope}</dd>\n {storedLabel && (\n <>\n <dt>stored</dt>\n <dd>{storedLabel}</dd>\n </>\n )}\n </dl>\n {mutable ? (\n <div className=\"paths-detail-actions\">\n <button type=\"button\" onClick={renameSelected}>\n rename / move\n </button>\n {canTransfer && (\n <button type=\"button\" onClick={transferSelected} title=\"Copy or move to another scope\">\n copy / move to…\n </button>\n )}\n {selectedAnnotation && (\n <button\n type=\"button\"\n onClick={() => setSelected(selectedAnnotation.fullPath)}\n title=\"Open the folder's annotation document to edit it\"\n >\n edit folder annotation\n </button>\n )}\n <button type=\"button\" className=\"danger\" onClick={deleteSelected}>\n delete\n </button>\n </div>\n ) : (\n <p className=\"paths-readonly\">\n Read-only — {selected.kind} entries are managed by their own tool.\n </p>\n )}\n </div>\n ) : (\n <div className=\"empty\">\n <p>Select a path on the left, or create a folder / document.</p>\n </div>\n )}\n </div>\n </Splitter>\n </div>\n {modal && <PromptModal state={modal} onClose={() => setModal(null)} />}\n {transfer && (\n <TransferModal\n data={data}\n scope={scope}\n browse={browse}\n documentId={transfer.documentId}\n underPath={transfer.underPath}\n fromPath={transfer.fromPath}\n onClose={() => setTransfer(null)}\n onDone={transferDone}\n />\n )}\n </>\n );\n}\n\n// PromptModal is a minimal create/rename/confirm dialog reusing the shared\n// .modal-* anchors. Zero fields + a message renders a confirm; submit errors\n// (incl. tool refusals surfaced by the data layer) show inline.\nfunction PromptModal({ state, onClose }: { state: ModalState; onClose: () => void }) {\n const [vals, setVals] = useState<Record<string, string>>(() =>\n Object.fromEntries(state.fields.map((f) => [f.key, f.value ?? \"\"])),\n );\n const [busy, setBusy] = useState(false);\n const [err, setErr] = useState<string | null>(null);\n\n const submit = async (e: FormEvent) => {\n e.preventDefault();\n setBusy(true);\n setErr(null);\n try {\n await state.onSubmit(vals);\n onClose();\n } catch (ex) {\n setErr(ex instanceof Error ? ex.message : String(ex));\n setBusy(false);\n }\n };\n\n return (\n <div className=\"modal-overlay\" onClick={onClose}>\n <form className=\"modal\" onClick={(e) => e.stopPropagation()} onSubmit={submit}>\n {/* RFC BN P1: Save/Cancel pinned to the top for consistency with the chunk editor. */}\n <div className=\"modal-header sticky-top\">\n <h3>{state.title}</h3>\n <div className=\"modal-buttons modal-buttons-top\">\n <button type=\"button\" onClick={onClose} disabled={busy}>\n cancel\n </button>\n <button type=\"submit\" className={state.danger ? \"danger\" : \"primary\"} disabled={busy}>\n {busy ? \"working…\" : state.submitLabel}\n </button>\n </div>\n </div>\n {state.message && <p className=\"modal-context\">{state.message}</p>}\n {state.fields.map((f, i) => (\n <label key={f.key} className=\"path-field\">\n <span>{f.label}</span>\n <input\n className=\"path-modal-input\"\n value={vals[f.key]}\n placeholder={f.placeholder}\n autoFocus={i === 0}\n onChange={(e) => setVals((v) => ({ ...v, [f.key]: e.target.value }))}\n />\n </label>\n ))}\n {err && <div className=\"modal-err\">{err}</div>}\n </form>\n </div>\n );\n}\n","import { useCallback, useEffect, useRef, useState, type ReactNode } from \"react\";\nimport type { AnnotationTarget, AssistantContext, BrowseScope, DocScope, Principal } from \"./types\";\nimport {\n ExplorerRoot,\n useResolvedDataLayer,\n type ExplorerDataSource,\n} from \"./components/ExplorerRoot\";\nimport { amendCurrent, followReference, jumpTo, type DocLocation, type Trail } from \"./lib/docTrail\";\nimport DocTrail from \"./components/DocTrail\";\nimport DocumentViewerBody from \"./components/DocumentViewerBody\";\n\n// DocumentViewer is the standalone, self-styling root for one chunked-graph\n// document (RFC AK) — the chunk tree + Markdown view + chunk editor. Mount it\n// on its own (a deep-link page) or let <PathExplorer> embed the shared body for\n// a document dirent. It resolves its own data layer + wraps in the themeable\n// `.loomcycle-explorer` root; styles ship separately:\n// `import \"@loomcycle/explorer/styles.css\"`.\n//\n// `documentId` is the document the host opened. A reference into ANOTHER\n// document is followed in place — the viewer shows that document and a\n// breadcrumb back — unless the host takes navigation over with onOpenDocument.\nexport interface DocumentViewerProps extends ExplorerDataSource {\n documentId: string;\n /** The chunk to open on, in place of the document's root: a section a link\n * or a search hit named. An id that is not one of the document's chunks\n * (another document's, a deleted one) lands on the root. Changing it while\n * documentId stays the same moves the selection without reloading. */\n chunkId?: string;\n scope: DocScope;\n /** Shown until the root chunk's title loads. */\n titleHint?: string;\n /** RFC AS browse-by-subject override threaded into every document call. */\n browse?: BrowseScope;\n /** Theming. Set → the root carries data-theme; omit → inherit an ancestor's\n * data-theme (dark is the default palette). */\n theme?: \"light\" | \"dark\";\n /** Authenticated principal — only `subject` is read (passed to renderAssistant). */\n principal?: Principal;\n /** Optional Document Assistant slot. Provide it to show an \"assistant\" toggle\n * that renders the returned node into the panel; omit → no assistant. */\n renderAssistant?: (ctx: AssistantContext) => ReactNode;\n /** Take over \"open another document\" (a followed cross-document reference),\n * e.g. to route to it. `target` is the document + chunk to open; `from` is\n * the document being left, with the chunk selected in it. Omit → the viewer\n * swaps the document itself and keeps a breadcrumb trail back. */\n onOpenDocument?: (target: DocLocation, from: DocLocation) => void;\n /** Have an annotation written again (tenant-scope documents). The host owns\n * how — typically by starting the annotating agent's run; the viewer reloads\n * the annotation when the returned promise settles. Omit → no Regenerate. */\n onRegenerateAnnotation?: (target: AnnotationTarget) => void | Promise<void>;\n /** Whether the reader may edit annotations by hand (the operator plane; the\n * runtime refuses anyone else). Default false: no Edit is offered. */\n canEditAnnotations?: boolean;\n}\n\nexport default function DocumentViewer(props: DocumentViewerProps) {\n const { documentId, scope, browse, theme } = props;\n const resolved = useResolvedDataLayer(props);\n return (\n <ExplorerRoot theme={theme} dataLayer={resolved}>\n {/* Keyed on what the host opened: a new document / scope / subject from the\n host is a fresh navigation, and drops the trail. */}\n <DocumentViewerHost\n key={`${scope}:${documentId}:${browse?.scopeId ?? \"\"}:${browse?.tenant ?? \"\"}`}\n {...props}\n />\n </ExplorerRoot>\n );\n}\n\n// DocumentViewerHost owns the trail for the standalone viewer: the document on\n// screen is the trail's last entry, or the host's `documentId` until a reference\n// has been followed.\nfunction DocumentViewerHost({\n documentId,\n chunkId,\n scope,\n titleHint,\n browse,\n principal,\n renderAssistant,\n onOpenDocument,\n onRegenerateAnnotation,\n canEditAnnotations,\n}: DocumentViewerProps) {\n const [trail, setTrail] = useState<Trail>([]);\n const current = trail[trail.length - 1];\n\n // The host's chunk: the landing chunk on mount, and later changes of it\n // move the selection in the mounted document (focusChunk), or — when the\n // reader has followed a reference elsewhere — bring them back to the host's\n // document at that chunk.\n const [focus, setFocus] = useState<{ chunkId?: string; seq: number }>();\n const hostChunk = useRef(chunkId);\n useEffect(() => {\n if (chunkId === hostChunk.current) return;\n hostChunk.current = chunkId;\n if (trail.length > 0) {\n // Back to the host's document: the body remounts and lands on chunkId,\n // so no earlier focus request may be replayed into it.\n setFocus(undefined);\n setTrail([]);\n } else setFocus((f) => ({ chunkId, seq: (f?.seq ?? 0) + 1 }));\n // trail is read, not watched: only a change of the host's chunk moves here.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [chunkId]);\n\n const open = useCallback(\n (target: DocLocation, from: DocLocation) => {\n if (onOpenDocument) onOpenDocument(target, from);\n else setTrail((t) => followReference(t, from, target));\n },\n [onOpenDocument],\n );\n const jump = useCallback((index: number) => setTrail((t) => jumpTo(t, index)), []);\n const onTitle = useCallback(\n (id: string, title: string) => setTrail((t) => amendCurrent(t, id, { title })),\n [],\n );\n\n return (\n <>\n <DocTrail trail={trail} onJump={jump} />\n {/* Keyed on the trail depth so each step remounts the viewer and lands on\n that step's chunk. */}\n <DocumentViewerBody\n key={trail.length}\n documentId={current?.documentId ?? documentId}\n scope={scope}\n titleHint={current ? current.title : titleHint}\n browse={browse}\n principal={principal}\n renderAssistant={renderAssistant}\n initialChunkId={current ? current.chunkId : chunkId}\n focusChunk={current ? undefined : focus}\n onOpenDocument={open}\n onTitle={onTitle}\n onRegenerateAnnotation={onRegenerateAnnotation}\n canEditAnnotations={canEditAnnotations}\n />\n </>\n );\n}\n"],"mappings":"A,8xBAMA,IAAa8G,EAAgB,+BAE7B,SAAgBC,EAAkB,EAA8D,CAC9F,GAAI,CACF,OAAOC,GAAS,QAAA,8BAAqB,IAAM,QAAU,QAAU,MACjE,MAAQ,CACN,MAAO,MACT,CACF,CAEA,SAAgBC,EACd,EACA,EACM,CACN,GAAI,CACFD,GAAS,QAAQF,EAAeI,CAAI,CACtC,MAAQ,CAER,CACF,CCpBA,SAAgBC,EAAc,EAAgD,CAC5E,MAAO,CAAC,CAACC,GAAS,CAACA,EAAM,WAAa,CAAC,CAACA,EAAM,QAAQ,WACxD,CAKA,SAAgBC,EAAgB,EAA8B,CAC5D,IAAMC,EAAWC,GAA4C,QAC7D,GAAI,CAAC,MAAM,QAAQD,CAAO,EAAG,MAAO,CAAC,EACrC,IAAME,EAAQ,IAAI,IAClB,IAAK,IAAMC,KAAKH,EAAS,CACvB,GAAM,CAAE,OAAM,QAAUG,GAAK,CAAC,EAC1B,OAAOC,GAAS,UAAYA,IAAS,IAAMC,IAAS,YAAYH,EAAM,IAAIE,CAAI,CACpF,CACA,MAAO,CAAC,GAAGF,CAAK,CAAC,CAAC,MAAM,EAAG,IAAMI,EAAE,cAAcC,CAAC,CAAC,CACrD,CAKA,SAAgBC,EAAmB,EAAmB,EAAuC,CAC3F,IAAMC,EAAMC,GAAW,GAEvB,OADID,IAAQ,IAAME,EAAQ,KAAM,GAAMC,EAAE,YAAY,IAAMH,EAAI,YAAY,CAAC,EAAUE,EAC9E,CAACF,EAAK,GA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