// karasu reversed into itself (reverse-architecture skill, 2026-11-14). // Skeleton: system / service / domain scaffold, physical spine, facet vocabulary. facet trust_boundary { label "Trust boundary input" description "Receives a value from outside the process (HTTP request, CLI argument, VS Code message, pasted or imported file, fetched URL) and must validate or canonicalize it before building a path, URL or markup from it" link "https://github.com/kompiro/karasu/blob/main/docs/test-perspectives/TPL-168-trust-boundary-input-validation.md" "TPL-168" } facet secret { label "Secret" description "Holds or carries a credential that must never be logged, exported, shared or committed (API key, OAuth client secret, session token, OAuth state)" link "https://github.com/kompiro/karasu/blob/main/docs/policy/nest-data-handling.md" "karasu-nest data handling" } facet nest_personal_data { label "Personal data (karasu-nest)" description "Holds or carries data that identifies a person (GitHub numeric id, login, session) under the karasu-nest privacy policy" link "https://github.com/kompiro/karasu/blob/main/docs/policy/nest-privacy.md" "karasu-nest privacy policy" } facet agent_surface { label "Agent-facing contract" description "A CLI command or flag recorded in agent-surface.json: removing or renaming it requires a deprecation entry, because agents and skills call it" link "https://github.com/kompiro/karasu/blob/main/docs/adr/2901-karasu-authoring-skill.md" "ADR-2901" } system Karasu { label "karasu" description "Text-based architecture modeling tool: .krs models compiled into logical, physical and organizational SVG views" user Author [human] { label "Model author" role "Writes and previews .krs models" } user CodingAgent [ai] { label "Coding agent" role "Authors or reverse-engineers .krs through the CLI and the agent skills" } user Reader [human] { label "Reader" role "Views a shared model or a gallery entry without editing it" } client WebApp [web] { label "karasu app (preview SPA)" resource opfs ProjectIndex "/meta/projects.json" resource opfs ProjectFiles "/projects// (project files)" resource opfs Snapshots "/projects//.snapshots//" resource opfs PasteCompare "/projects//.karasu-paste-compare.krs" resource sessionStorage ApiKeySession "karasu.ai.anthropic.apiKey" resource localStorage ApiKeyPersisted "karasu.ai.anthropic.apiKey (opt-in persist)" resource localStorage ApiKeyPersistChoice "karasu.ai.settings.persist" resource localStorage LocalePref "karasu-locale" resource localStorage ThemePref "karasu-theme" resource localStorage LastProject "karasu-last-project-id" resource localStorage TourProgressKey "karasu-first-run-tour" resource localStorage TourProjectKey "karasu-first-run-tour-project" resource localStorage WelcomeDismissed "karasu-welcome-dismissed" resource localStorage SidebarWidth "karasu:sidebar:width" resource localStorage EditorWidth "karasu:editor:width" } client CliTool [cli] { label "karasu CLI" resource file KrsSources ".krs / .krs.style" resource file RenderOutput "SVG / draw.io / report output" } client VsCodeExtension [extension] { label "karasu VS Code extension" resource file WorkspaceKrs ".krs / .krs.style (workspace)" } client AgentSkills [extension] { label "karasu agent skills" description "Claude Code plugin shipping karasu-author and reverse-architecture" } client DocsSite [web] { label "Documentation site" } service CoreLib { label "@karasu-tools/core" description "Pure TypeScript library: parser, resolver, style, renderer, translate" boundary CompilePipeline { label "compile() pipeline" description "The domains compile.ts chains for every render: parse, resolve, style, draw" contains Language contains Modeling contains Styling contains Rendering } domain Language { label "Language" description "The .krs and .krs.style surface: lexing, parsing to AST, imports and multi-file projects, formatting, structural patching (applyKrsPatch), language version, annotations, the builtin reference and vocabulary" -> Styling "parses the @import'ed .krs.style sheets of a project; the reference embeds the builtin style source" -> Modeling "reads the CRUD verb vocabulary and infra index (core/src/spec) and the Warning type while parsing" // ─── Usecases ──────────────────────────────────────────────────────────── usecase TokenizeSource { label "Tokenize source" description "Lexer.tokenize / tokenizeWithComments: .krs text into tokens with exact ranges, optionally keeping comments and blank lines as trivia for the formatter" } usecase ParseDocument { label "Parse a .krs document" description "Parser.parse: one source string (and its absolute path, when known) into a KrsFile AST plus diagnostics; every range is stamped with the file path" } usecase BuildDeclarationIndexes { label "Build declaration indexes" description "The finalize pass shared by a single-file parse and the merged project: owner, boundary, facet and node-path indexes, sync-cycle marks, duplicate-id and reference (owns / contains / realizes / physical ref / facet) checks" } usecase FindCyclicDependencies { label "Find sync dependency cycles" description "Marks edges on a sync cycle ([cyclic]) and reports the cycle as a warning" } usecase ResolveNodePathReference { label "Resolve a node path reference" description "Matches a dotted reference (Sys.Svc.Domain) against declared node paths by suffix, and reports ambiguous candidates" } usecase ResolveProjectImports { label "Resolve a multi-file project" description "ImportResolver.resolve: from an entry file, load every wildcard / named / directory import through a FileSystemProvider, detect cycles and missing files, merge reopened system / deploy / organization / infra blocks (closest file wins label / description), re-derive merged-model indexes and verdicts, then parse the style imports" facets trust_boundary } usecase ValidateRelativePath { label "Validate an untrusted relative path" description "isSafeRelativePath: rejects empty, absolute, backslash and '..' paths before a caller joins them under a root (used by zip import and project manager)" facets trust_boundary } usecase ValidateLinkUrl { label "Validate a link URL" description "Allows only http: / https: / mailto: link URLs (link-url-scheme-not-allowed otherwise) so a preview never renders a javascript: href" facets trust_boundary } usecase FormatDocument { label "Format a .krs document" description "format(): canonical indentation, property order and comment placement; idempotent; refuses on parse errors or a value it cannot preserve" } usecase SerializeMergedProject { label "Serialize a merged project" description "serializeKrsFile: print a resolved multi-file AST back to one self-contained .krs (no comments), used to flatten a project for sharing" } usecase ReportLanguageVersion { label "Report the language version" description "KRS_LANGUAGE_VERSION: the single source of truth for the .krs language axis, independent of npm semver" } usecase GetReference { label "Get the language reference" description "getReference(locale): node kinds, deploy / org kinds, grouping constructs, tags, annotations, style properties, shapes, syntax sections and samples, in en or ja" } usecase CheckToolVocabulary { label "Check against the tool vocabulary" description "The closed set of builtin tags and annotations: suggests the nearest builtin annotation for a typo and tells whether a style selector names only tool vocabulary" } usecase ListBuiltinExamples { label "List builtin example projects" description "Example projects generated from examples/ (pnpm gen:examples) for first launch and the reference Samples tab" } usecase FindOpenableExample { label "Find an openable example" description "Resolves a (slug, lang) request from ?example= or the docs gallery to its manifest entry; a malformed or unknown slug means do not fetch" facets trust_boundary } usecase InterpretDraftConfidence { label "Interpret @draft confidence" description "Reads @draft(confidence: ...) into a machine level (low / medium / high) or an opaque value" } usecase InterpretMigrationIntent { label "Interpret migration intent" description "Reads until on @deprecated / @experimental and from on @migration_target into a migration intent; until becomes a date / month / quarter deadline or an opaque value" } usecase DescribeNodeDetailFields { label "Describe node detail fields" description "Shared row and icon data for the node detail panel, mirrored by the app and the VS Code webview" } // ─── Entities ──────────────────────────────────────────────────────────── entity SourceFile { label "Source file (KrsFile)" description "One parsed .krs document: its top-level declarations, imports and the indexes built over them" SourceFile -> ImportDeclaration "imports" SourceFile -> StyleImport "imports style" SourceFile -> Declaration "declares" SourceFile -> DeployBlock "declares" SourceFile -> OrganizationBlock "declares" SourceFile -> BoundaryBlock "declares" SourceFile -> FacetDeclaration "declares" SourceFile -> LegendBlock "declares" } entity Token { label "Token" Token -> Trivia "leading trivia" } entity Trivia { label "Trivia (comment / blank line)" } entity ImportDeclaration { label "Import" description "import \"file.krs\" (wildcard), import { A, B.C } from \"file.krs\" (named) or a directory import" ImportDeclaration -> SourceFile "names" ImportDeclaration -> NodePath "named entries" } entity StyleImport { label "@import of a style sheet" StyleImport -> Styling.StyleSheet "names" } entity Declaration { label "Declaration (KrsNode)" description "A system / service / domain / usecase / entity / resource / user / client node or an infra block and its leaves" Declaration -> Declaration "child" Declaration -> Edge "declares" Declaration -> Tag "tagged" Declaration -> Annotation "annotated" Declaration -> LinkEntry "links" Declaration -> ResourceOperation "operations" Declaration -> FacetDeclaration "member of" } entity Edge { label "Edge" description "A sync (->) or async (-->) dependency or entity relation, with an optional #id and property block" Edge -> NodePath "from / to" Edge -> Tag "tagged" Edge -> FacetDeclaration "member of" } entity NodePath { label "Node path reference" description "A dotted id path (Sys.Svc.Domain) resolved by suffix against declared nodes" NodePath -> Declaration "resolves to" NodePath -> Modeling.ModelNode "identifies" } entity Tag { label "Tag" } entity Annotation { label "Annotation" description "@name(key: value, ...) on a declaration" } entity LinkEntry { label "Link" } entity ResourceOperation { label "Resource operation" description "A CRUD verb, or a custom verb decorated with its CRUD intent" } entity DeployBlock { label "Deploy block" DeployBlock -> NodePath "realizes" } entity OrganizationBlock { label "Organization block (teams / members)" OrganizationBlock -> NodePath "owns" } entity BoundaryBlock { label "Boundary" BoundaryBlock -> NodePath "contains" } entity FacetDeclaration { label "Facet declaration" } entity LegendBlock { label "Legend" LegendBlock -> Tag "explains" LegendBlock -> Annotation "explains" } entity Diagnostic { label "Diagnostic" description "Code + params + severity + range; rendered to text by Localization" Diagnostic -> SourceFile "anchored in" Diagnostic -> Modeling.DiagnosticId "aliased by" } entity ResolvedProject { label "Resolved project" description "The merged KrsFile of an entry file and everything it imports, its style sheets in cascade order and its diagnostics" ResolvedProject -> SourceFile "merges" ResolvedProject -> Styling.StyleSheet "cascade" ResolvedProject -> Diagnostic "reports" } entity DraftState { label "Draft state" DraftState -> Annotation "interprets" } entity MigrationIntent { label "Migration intent" MigrationIntent -> Annotation "interprets" MigrationIntent -> NodePath "migrates from" } entity ReferenceCatalog { label "Language reference (REFERENCE_DATA)" ReferenceCatalog -> ExampleProject "samples" ReferenceCatalog -> Styling.StyleSheet "builtin style source" } entity ToolVocabulary { label "Tool vocabulary" ToolVocabulary -> Tag "builtin tags" ToolVocabulary -> Annotation "builtin annotations" } entity ExampleProject { label "Builtin example project" } entity OpenableExample { label "Openable example manifest entry" OpenableExample -> ExampleProject "opens" } // moved from ModelEditing (seam verdict) usecase ApplyKrsPatch { label "Apply a structural patch to .krs text" description "Core entry point (@karasu-tools/core applyKrsPatch): append / replace / remove / insert-child on a source string by node id, searching logical, deploy and org trees; returns the new source or an error (not found, ambiguous across diagram types, missing content). Also called by the in-app assistant chat as its edit tool" link "https://github.com/kompiro/karasu/blob/main/packages/core/src/patch/krs-patch.ts" "krs-patch.ts" } entity KrsPatch { label "Patch" description "One operation (append / replace / remove / insert-child) with its target id and content" KrsPatch -> PatchTarget "addresses" KrsPatch -> PatchContent "carries" } entity PatchTarget { label "Patch target" description "The node located by id and its source range (start offset to the closing brace, inclusive)" PatchTarget -> Declaration "located in" PatchTarget -> DeployBlock "located in" PatchTarget -> OrganizationBlock "located in" } entity PatchContent { label "Patch content" description "Piped .krs text spliced into the file as given (only re-indented for insert-child)" } entity PatchResult { label "Patch result" description "The rewritten source text, or the error message" PatchResult -> KrsPatch "outcome of" PatchResult -> SourceFile "rewrites" } } domain Modeling { label "Modeling" description "Semantic resolution of the AST into a model: canonical ids, edge endpoints, inheritance, diagnostics, compile, extraction of the system / drill-down / deploy / org views, and the before / after view diff" // ─── Compile facade (core/src/compile/compile.ts) ─────────────────────── usecase CompileModel { label "Compile a .krs source" description "compile(): parse one source, validate edge ids, collect model warnings, extract the requested system / deploy / org view, resolve styles and render it; returns SVG, warnings, diagnostics and node metadata" } usecase CompileProject { label "Compile a multi-file project" description "compileProject(): resolve the entry file's imports through a FileSystemProvider into one merged model, then run the same compile pipeline" } usecase BuildViewBundle { label "Build a bundled multi-view SVG" description "buildAllViewsSvg / buildAllViewsSvgProject / buildAllLayersSvg / buildDrillDownSvg (+ Org variants): every view level of a model in one bundle, parse diagnostics merged with the renderer's" } usecase RenderEntityView { label "Render a domain's entity view" description "renderEntityView(): parse and render the per-domain entity-relation view at a view path" } usecase DeriveTeamDependenciesLazily { label "Attach team dependencies to an org compile" description "Org compile result exposes teamDependencies as a memoized getter computed on first read" } // ─── Resolution (core/src/resolver, not style-resolver) ───────────────── usecase AssignEdgeCanonicalIds { label "Assign edge canonical ids" description "authorId or `` base per edge; ambiguous bases warn and clear the id; project-wide author-id uniqueness check (ADR-1096)" } usecase ResolveEdgeEndpoints { label "Resolve edge endpoints" description "Bare endpoint binds to the declaring block's peers; qualified endpoint must be root-anchored at a system; builds the ghost-endpoint resolver for cross-system edges" } usecase ResolveResourceEntity { label "Resolve a usecase resource to its store" description "Physical dot-notation or bare id → unique entity → table → infra block (usecase → entity → table → database)" } usecase InheritAnnotations { label "Propagate service annotations" description "Descendants of an annotated service inherit the nearest annotated ancestor's annotations (replace, never merge)" } usecase AnalyzeModel { label "Analyze model (emit warnings)" description "analyze(): domain dispersal, shared-infra fan-in, cross-domain store access, unassigned nodes / resources, unresolved realizes / owns / handles / endpoints, cross-system refs, cycles, tag / annotation / facet / selector vocabulary, style conflicts, legend refs" } usecase CollectModelWarnings { label "Collect model warnings" description "One builder shared by compile, diff, bundle and draw.io: analyze() plus value-level validation of every user style sheet" } usecase IdentifyDiagnostic { label "Map a diagnostic code to its KRS id" description "diagnosticIdOf(): stable KRSnnn alias for every Diagnostic / Warning code, retired ids never reused" } usecase ClassifyWarningSeverity { label "Classify warning severity" description "warningSeverity(): warning vs info per WarningKind" } // ─── View extraction (core/src/view) ──────────────────────────────────── usecase ExtractSystemView { label "Extract system / drill-down view" description "extractView / createViewExtractor: root system view (optionally with services expanded in place) or the drill-down slice of a container at a view path, with derived edges, promoted resources and ghosts" } usecase ExtractEntityView { label "Extract entity view" description "Per-domain entity relations, cross-domain targets as ghost entities, store-scoped ER projection onto a database canvas" } usecase ExtractDeployView { label "Extract deploy view" description "Deploy containers per realized service, units, store realization and derived ghost edges for the selected deploy block" } usecase ExtractOrgView { label "Extract org view" description "Teams at an org view path: focused team and ancestor chain" } usecase DeriveImplicitEdges { label "Derive implicit edges" description "Implicit service edges aggregated from cross-service domain edges (\"N domain edges\"), service → infra edges with [read]/[write] tags, delivers edges, canvas edges; explicit edges suppress derived ones" } usecase SynthesizeGhosts { label "Synthesize ghost nodes" description "Caller / callee ghost systems and domains for cross-system edges reaching the focused container" } usecase PromoteUsecaseResources { label "Promote usecase resources" description "Promote dot-notation sub-resources to siblings in the usecase diagram and infer read / write tags from operations" } usecase SynthesizeUnassignedSystem { label "Wrap top-level orphans" description "Synthesize the `__unassigned__` pseudo-system around top-level services / domains / infra blocks" } usecase ResolveViewPath { label "Resolve a view path" description "resolveContainerChain(): the one reader of a ViewPath, shared by extractors and the app's breadcrumbs" } // ─── Spec helpers (core/src/spec) ─────────────────────────────────────── usecase ClassifyResourceOperations { label "Classify resource operations" description "Recognized CRUD verbs, decorated verbs, write / read classification of a usecase's operations" } usecase IndexDeclaredInfra { label "Index declared infra" description "One walk of every database / queue / storage block and its leaves, shared by reference validation, coverage and CRUD matrix" } // ─── Entities ─────────────────────────────────────────────────────────── entity Model { label "Resolved model" description "The import-merged KrsFile seen as a semantic model: systems (plus the synthesized unassigned system), deploy blocks, organizations" Model -> Language.SourceFile "resolved from" Model -> ModelNode "contains" Model -> ModelEdge "contains" } entity ModelNode { label "Model node" description "A system / service / domain / usecase / resource / infra / client / user node with its path identity and effective (inherited) annotations" ModelNode -> ModelNode "child of" } entity ModelEdge { label "Model edge" ModelEdge -> ModelNode "connects" ModelEdge -> CanonicalId "identified by" } entity CanonicalId { label "Edge canonical id" description "authorId or `` base, quoted when an endpoint is not one identifier" } entity EntityResolution { label "Resource → entity → store resolution" EntityResolution -> ModelNode "resolves resource" EntityResolution -> InfraLeaf "targets" } entity InfraLeaf { label "Declared infra leaf" description "table / queue-item / bucket inside a database / queue / storage; owned by the domains whose entity maps it" } entity ViewPath { label "View path" ViewPath -> ModelNode "drills to container" } entity ViewSlice { label "View slice" description "What one view draws: nodes, child edges, frame edges, ghosts, promoted resources" ViewSlice -> ViewPath "extracted at" ViewSlice -> ModelNode "shows" ViewSlice -> DerivedEdge "shows" ViewSlice -> Ghost "shows" } entity DerivedEdge { label "Derived edge" description "Implicit service edge, infra edge, delivers edge or canvas edge computed from the model, never authored" DerivedEdge -> ModelEdge "aggregates" DerivedEdge -> DomainEdgeDetail "carries" } entity DomainEdgeDetail { label "Constituent domain edge" DomainEdgeDetail -> ModelEdge "detail of" } entity Ghost { label "Ghost node" description "Muted stand-in for a node outside the current view: ghost system / domain for cross-system edges, ghost entity for cross-domain relations" Ghost -> ModelNode "stands for" } entity UnassignedSystem { label "Unassigned pseudo-system" UnassignedSystem -> ModelNode "wraps orphans" } entity DeploySlice { label "Deploy view slice" DeploySlice -> DeployContainer "contains" } entity DeployContainer { label "Deploy container" DeployContainer -> ModelNode "realizes" } entity OrgSlice { label "Org view slice" OrgSlice -> ModelNode "focuses team" } entity Warning { label "Model warning" description "Finding raised by analyze() or style value validation; severity warning or info" Warning -> DiagnosticId "aliased by" Warning -> ModelNode "points at" } entity DiagnosticId { label "Diagnostic id (KRSnnn)" } entity NodeMetadata { label "Node metadata" description "Per-node detail (kind, label, description summary, links, owning team, runtime, draft / migration state) handed to detail panels" NodeMetadata -> ModelNode "describes" } entity CompileResult { label "Compile result" description "System / deploy / org result: SVG plus warnings, diagnostics, metadata, facets, deploy tree or org index" CompileResult -> Model "compiled from" CompileResult -> ViewSlice "renders" CompileResult -> Warning "reports" CompileResult -> Language.Diagnostic "reports" CompileResult -> NodeMetadata "carries" CompileResult -> Styling.ResolvedStyles "carries (org)" CompileResult -> ModelAnalysis.TeamDependencyReport "carries lazily (org)" } // ─── Domain edges ─────────────────────────────────────────────────────── -> Language "parses source, resolves imports, node paths, reference validation, cycle detection, builtin vocabulary" -> Styling "resolves styles, builtin and display-mode sheets, style value validation, selector serialization, edge endpoint literal" -> Rendering "renders the extracted slice (system / deploy / org / drill-down / bundle), legend usage, facet overlay and overview" -> ModelAnalysis "lazy team dependencies on the org compile result" // moved from ModelAnalysis (seam verdict) usecase DiffSystemView { label "Diff two models on the system view" description "compileSystemDiff(): resolve before / after entries with one ImportResolver each, extract the same view path on both sides, union the slices, resolve styles against builtin + before + after sheets (cyclic tag off), render with data-diff-state and inject the diff stylesheet" } usecase DiffDeployView { label "Diff two models on the deploy view" description "compileDeployDiff(): pick the deploy block by id (or the first) on each side, union containers by serviceId, units by id and ghost edges by edge key" } usecase DiffOrgView { label "Diff two models on the org view" description "compileOrgDiff(): union teams / members / owns relations; owns compared by written notation, not resolution" } usecase DiffAllViews { label "Diff every applicable view into one bundle" description "buildAllViewsSvgDiffProject(): system / deploy / org diffs, each skipped when neither side has that layer, bundled with CSS-only tab navigation" } usecase UnionViewSlices { label "Union two view slices with diff state" description "diffSystemViewSlices / diffDeployViewSlices / diffOrgViewSlices: one union slice, after-side elements first, per-node / per-card-path / per-edge diff meta, per-frame merge on the multi-system root, set diff of the domain edges inside each aggregated implicit edge" } usecase CollectDiffWarnings { label "Collect the warnings a diff reports" description "The after model's warnings, once per diff, validated against the after side's own sheets (#2879)" } usecase InjectDiffStyle { label "Embed diff-state CSS in the SVG" description "Self-contained diff stylesheet inserted after the tag, idempotent, so a CLI diff reads as a diff when opened standalone" } usecase KeyOwnsRelation { label "Key an owns relation" description "ownsEdgeKey(team, ref): injective team → owned-node key shared by the org diff and the org renderers" } entity ViewDiff { label "Diffed system view" description "Union slice of two system view slices plus per-element diff meta" ViewDiff -> ViewSlice "unions before and after" ViewDiff -> ElementDiff "annotates elements with" } entity DeployViewDiff { label "Diffed deploy view" DeployViewDiff -> DeploySlice "unions before and after" DeployViewDiff -> ElementDiff "annotates elements with" } entity OrgViewDiff { label "Diffed org view" OrgViewDiff -> OrgSlice "unions before and after" OrgViewDiff -> ElementDiff "annotates elements with" } entity ElementDiff { label "Element diff state" description "unchanged / added / removed / changed with the changed fields (label, tags, annotations, aggregated domain edges); keyed by node id, card path, edge key or owns key" ElementDiff -> ModelNode "describes a node" ElementDiff -> ModelEdge "describes an edge" ElementDiff -> DomainEdgeDetail "set-diffs constituents of" } entity DiffCompileResult { label "Diff compile result" description "Per-view diff SVG, merged before / after diagnostics, the after model's warnings, and the diff meta maps" DiffCompileResult -> ViewDiff "renders (system)" DiffCompileResult -> DeployViewDiff "renders (deploy)" DiffCompileResult -> OrgViewDiff "renders (org)" DiffCompileResult -> Warning "reports the after side's" DiffCompileResult -> Language.Diagnostic "carries" DiffCompileResult -> Rendering.SvgBundle "bundles all views into" } } domain Styling { label "Styling" description "Style sheets and themes: selector matching, resolved style, builtin default style and display-mode sheets" -> Language "style lexer reuses the .krs token types and identifier character classes; cascade filters selectors by the tool vocabulary; builtin sheet takes badge colours / icons / en labels from REFERENCE_DATA; resolver walks AST node paths and quotes edge endpoint ids" -> Modeling "keys resolved edge styles with the view edge-key and skips the unassigned-system placeholder" -> Rendering "checks url(\"\") icons against the shape registry; theme and display-mode vocabularies are declared beside the palette and layout types" usecase ParseStyleSheet { label "Parse a .krs.style sheet" description "StyleParser.parse: lex and parse a sheet into rules with selectors, specificity, declaration ranges, value ASTs and comment trivia; reports selector / token diagnostics" facets trust_boundary } usecase ValidateStyleValues { label "Validate style values (lint)" description "Check every declaration against the property schema: unknown property, bad enum, hex colour, length unit, out-of-range number, unregistered url() icon. The core operation behind `karasu lint-style`" } usecase TidyStyleSheet { label "Tidy a style sheet" description "Merge duplicate-selector rules (cascade tail wins), reorder declarations by axis (visual, typography, layout, karasu), re-serialize with comments kept; idempotent and leaves a sheet with parse errors untouched. The core operation behind `karasu tidy-style`" } usecase SerializeStyleSheet { label "Serialize a style sheet" description "Print a StyleSheet back to canonical text, regrouping rules that came from one selector list" } usecase ResolveStyles { label "Resolve effective styles" description "Flatten the builtin, author and display-mode sheets into one cascade (specificity, then declaration order across sheets), drop declarations that fail their schema, and compute the resolved style of every logical node (with annotation inheritance and inferred infra tags), edge, deploy unit, org node, boundary frame and team frame, plus layout hints and painted-colour flags" } usecase StyleDerivedEdges { label "Style a view slice's derived edges" description "After resolution, give edges that exist only on an extracted view (implicit service edges, projected store relations) their own style entry without overwriting an authored edge's" } usecase GetBuiltinStyleSheet { label "Get the builtin style sheet for a theme" description "Build the default sheet for the dark or light theme, inserting annotation badge rules with caller-injected translated labels; parsed once per (theme, label set) and cached" } usecase ApplyDisplayMode { label "Apply a display mode" description "Append the display mode's sheet (the icon theme for icon mode, none for shape mode) after the author sheets so the mode wins every specificity tie" } usecase LookupNodeIcon { label "Look up a node's icon" description "Map (kind, tags) to an Icon Mode pictogram name, first variant tag wins; the same table generates the icon-theme sheet" } entity StyleSheet { label "Style sheet" description "A parsed .krs.style file or a builtin sheet (, ), identified by its sheet id" } entity StyleRule { label "Style rule" description "One selector with its declarations, specificity and global source index" StyleRule -> StyleSheet "declared in" StyleRule -> StyleSelector "selects with" StyleRule -> StyleDeclaration "declares" } entity StyleSelector { label "Selector" description "kind / #id / [tag] / [@annotation] / [facets=] / edge# / edge[from=] / edge[to=] / boundary#" StyleSelector -> Language.Declaration "matches by kind, id, tag, annotation" StyleSelector -> Language.Edge "matches by canonical id or endpoints" StyleSelector -> Language.BoundaryBlock "boundary#" StyleSelector -> Language.FacetDeclaration "[facets=]" } entity StyleDeclaration { label "Declaration" description "A property: value pair inside a rule, with its range and trivia" StyleDeclaration -> PropertySchema "validated against" } entity PropertySchema { label "Property schema" description "The single table of known properties and their value bounds (enum, hex, number, length, url, list, sequence) and their tidy axis" } entity ResolvedStyles { label "Resolved styles" description "Output of style resolution for one compile: per-node, per-path, per-edge styles, frames, layout hints, painted colours, defaults and warnings" ResolvedStyles -> ResolvedNodeStyle "per node key" ResolvedStyles -> ResolvedEdgeStyle "per edge key" ResolvedStyles -> FrameStyle "boundary and team frames" ResolvedStyles -> LayoutHints "per node" ResolvedStyles -> StyleWarning "collects" } entity ResolvedNodeStyle { label "Resolved node style" description "Effective fill, text, border, font, opacity, shape and badge of one node" ResolvedNodeStyle -> Language.Declaration "styles" } entity ResolvedEdgeStyle { label "Resolved edge style" description "Effective colour, stroke, direction and label placement / disclosure of one edge" ResolvedEdgeStyle -> Language.Edge "styles" } entity FrameStyle { label "Frame style" description "Author-only frame colours for a boundary or team frame (builtin rules do not follow a selector onto the frame)" } entity LayoutHints { label "Layout hints" description "column / grid-columns escape hatches read from the cascade for the layout engine" } entity StyleWarning { label "Style warning" description "A resolution-time warning such as a column hint ignored outside the system view" } entity Theme { label "Theme" description "dark or light; selects the builtin sheet template and its annotation badge colours" } entity BuiltinStyleSheet { label "Builtin style sheet" description "karasu's default sheet: kind colours, tag variants, annotation badges; trusted, not schema-checked" BuiltinStyleSheet -> Theme "templated per" BuiltinStyleSheet -> StyleSheet "parsed as" BuiltinStyleSheet -> Language.Annotation "badge colour, icon and default label per annotation" } entity DisplayMode { label "Display mode" description "shape or icon; each mode may lay one sheet over the model's sheets" DisplayMode -> IconTheme "icon mode lays" } entity IconTheme { label "Icon theme" description "The Icon Mode sheet generated from the icon rules" IconTheme -> IconRule "generated from" IconTheme -> StyleSheet "parsed as" } entity IconRule { label "Icon rule" description "(kind, tag?) to icon name, scoped logical / infra / resource-variant / client-variant / org / deploy" IconRule -> Rendering.Shape "names a registered icon" } } domain Rendering { label "Rendering" description "Layout and SVG drawing of every view: placement, edge routing, frames, badges, legend, shapes, draw.io export" -> Modeling "extract view slices (system / drill-down / deploy / org / entity), model warnings, edge keys, inherited annotations" -> Styling "resolve node and edge styles, parse style sources, builtin and display-mode sheets, cascade order for legend swatches" -> Language "AST types, node-path ids, import resolution for a multi-file draw.io export" -> ModelAnalysis "draw the CRUD matrix and the team dependency graph, key diff state onto nodes and edges" // ─── View renderers (public entry points) ─────────────────────────────── usecase RenderSystemView { label "Render a logical view" description "render / renderFromLayout: lay out one logical view slice (system root or a drilled service / domain) and draw it as SVG with frames, edges, controls and legend" } usecase RenderDrillDownBundle { label "Render a drill-down bundle" description "buildDrillDownSvg / buildDrillDownSvgOrg: one static SVG holding every drill level, navigated by CSS :target with no JavaScript" } usecase RenderEntityView { label "Render an entity view" description "renderEntityView: the live single-level entity-relation view of one domain, with foreign entities as ghosts" } usecase RenderDeployView { label "Render a deploy view" description "renderDeploy + layoutDeploy: deploy units grouped by the service they realize, system edges shown as ghost edges" } usecase RenderOrgView { label "Render an org view" description "renderOrgView: teams, members and the services they own, with drill-down into sub-teams" } usecase RenderOrgTreeView { label "Render the org tree view" description "renderOrgTreeView: left-right team tree with Bezier connectors and expandable member grids" } usecase RenderAllLayers { label "Render all layers" description "buildAllLayersSvg / buildAllLayersSvgOrg: every drill level stacked vertically in one SVG" } usecase RenderAllViewsBundle { label "Render the all-views bundle" description "buildAllViewsSvg / bundleSingleLevelViews: system, deploy and org views in one SVG with CSS-only tabs" } usecase RenderCrudMatrix { label "Render the CRUD matrix" description "renderMatrixAsSvg: usecase x resource table as SVG" } usecase RenderTeamDependencyGraph { label "Render the team dependency graph" description "renderTeamDependencyGraph: team-to-team dependency report drawn as a graph" } usecase WrapOgpFrame { label "Wrap an SVG in an OGP frame" description "wrapSvgForOgpFrame: letterbox a diagram into a fixed 1200x630 canvas for social cards (rasterized by /render and karasu-nest)" } // ─── Layout and routing pipeline ──────────────────────────────────────── usecase LayOutCanvas { label "Lay out a canvas" description "layout: layer assignment (kind tiers or Group by bands), barycenter placement, external side columns, ghost placement, multi-system frames, and a deterministic width-budget search for the least-empty canvas" } usecase CollapseCanvasNodes { label "Collapse categories and groups" description "Fold the infra / external categories or a Group by group into a stub and re-target the edges that crossed it" } usecase RouteEdges { label "Route edges" description "runRoutingChain: skip-layer channel routing, gutter routing around group frames, port distribution, parallel bundles, channel lanes, mutual pairs drawn as one line" } usecase PlaceEdgeLabels { label "Place edge labels" description "Nudge colliding labels off cards, labels and foreign lines; truncate or withhold what cannot be seated and open label room on a second placement" } usecase ComputeCrossingMarks { label "Compute crossing marks" description "Hops where unrelated edges cross, junction chips where trunk stubs merge, trunk bands" } usecase ResolveFacetOverlay { label "Resolve the facet overlay" description "Viewer-selected facets to colored rings and dimming; emits nothing when no facet is selected" } usecase BuildFacetOverview { label "Build the facet overview" description "Derive the membership list of every facet from the facets properties on the model" } usecase RenderLegend { label "Render the legend footer" description "collectLegendUsage + buildLegendFooter: scoped legend entries with swatches from the style sheets, plus the facet color key" } usecase ResolvePalette { label "Resolve the chrome palette" description "Dark / light diagram chrome colors and the WCAG contrast check the builtin themes are held to" } // ─── Shapes and icons ─────────────────────────────────────────────────── usecase RegisterShape { label "Register a shape" description "registerShape / registerBuiltinShapes: named render functions with content insets and port frames, referenced by .krs.style shape" } usecase RegisterSvgIcon { label "Register an SVG icon" description "parseSvgIcon / loadAndRegisterIcons / resolveIconManifest: turn icon SVG text (builtin or from an icons.json manifest) into a registered icon with label / description slots" facets trust_boundary } // ─── draw.io export ───────────────────────────────────────────────────── usecase ExportDrawio { label "Export draw.io" description "exportDrawio: turn system / deploy / org layouts into an mxGraph (.drawio) document, one page per view" } usecase BuildDrawioProject { label "Build a draw.io project" description "buildDrawio / buildDrawioProject: resolve a multi-file project through a FileSystemProvider, lay out each selected view and export it" } // ─── Entities ─────────────────────────────────────────────────────────── entity Canvas { label "Canvas (rendered SVG)" description "The SVG of one view level" Canvas -> Layout "drawn from" Canvas -> Modeling.ViewSlice "renders" Canvas -> Styling.ResolvedStyles "painted with" Canvas -> Palette "chrome colors" Canvas -> LegendFooter "footer" Canvas -> FacetOverlay "highlight layer" } entity SvgBundle { label "SVG bundle" description "Several canvases in one SVG: drill-down levels, stacked layers or view tabs" SvgBundle -> DrillLevel "contains" } entity DrillLevel { label "Drill level" description "One level of a bundle, addressed by a krs-- anchor" DrillLevel -> Canvas "shows" } entity Layout { label "Layout result" description "Positions of nodes, edges and frames for one view, before drawing" Layout -> PlacedNode "places" Layout -> EdgeRoute "routes" Layout -> Frame "frames" Layout -> CrossingMark "marks" } entity PlacedNode { label "Placed node (card)" PlacedNode -> Language.Declaration "positions" PlacedNode -> Shape "drawn as" PlacedNode -> Badge "carries" PlacedNode -> CornerLane "chip lane" } entity CollapseStub { label "Collapse stub" description "Synthetic card that stands for a folded category or group" CollapseStub -> GroupBand "folds" } entity GroupBand { label "Group band" description "Row range of one Group by group (team or boundary)" GroupBand -> Frame "enclosed by" } entity Frame { label "Frame" description "Container rectangle: system frame, drill-down frame, group or boundary frame" Frame -> PlacedNode "encloses" } entity EdgeRoute { label "Edge route" description "A routed edge polyline with waypoints, ports and bundle index" EdgeRoute -> PlacedNode "connects" EdgeRoute -> Lane "runs in" EdgeRoute -> EdgeLabel "labelled by" EdgeRoute -> Modeling.ModelEdge "draws" } entity EdgeLabel { label "Edge label" description "Seated, truncated or withheld label text of an edge" } entity Channel { label "Channel" description "Clear horizontal band between two rows of obstacles" Channel -> Frame "bounded by" } entity Lane { label "Lane" description "A fixed-pitch track inside a channel or a side gutter" Lane -> Channel "inside" } entity CrossingMark { label "Crossing mark" description "Hop, junction chip or trunk band" CrossingMark -> EdgeRoute "disambiguates" } entity ObstacleIndex { label "Obstacle index" description "Spatial grid over cards and frame pieces queried by every routing pass" ObstacleIndex -> PlacedNode "indexes" ObstacleIndex -> Frame "indexes" } entity CornerLane { label "Corner lane" description "Inset row of chips on a card: annotation pill, info and drill buttons" } entity Badge { label "Badge" description "Annotation badge (icon, label, color) from the resolved node style" Badge -> Styling.ResolvedStyles "styled by" } entity Shape { label "Shape" description "Registered render function with content insets and port frame" Shape -> IconDef "icon-backed" } entity IconDef { label "Icon definition" description "Parsed SVG icon: viewBox, body, label and description slots" } entity Palette { label "Diagram palette" description "Chrome colors for the dark or light theme" } entity LegendFooter { label "Legend footer" LegendFooter -> Language.LegendBlock "declared by" LegendFooter -> Styling.StyleSheet "swatch colors from" } entity FacetOverlay { label "Facet overlay" description "Viewer-side selection of facets to highlight" FacetOverlay -> Language.FacetDeclaration "highlights" } entity FacetOverview { label "Facet overview" FacetOverview -> Language.FacetDeclaration "lists members of" } entity DrawioDocument { label "draw.io document" DrawioDocument -> DrawioPage "pages" } entity DrawioPage { label "draw.io page" DrawioPage -> Layout "exported from" } } domain Translation { label "Translation" description "Adapters that turn compose / k8s / OpenAPI / DB schema / wrangler manifests into .krs" -> Language "escape emitted string values (formatter quoteString / emitDescription)" usecase TranslateInfraConfig { label "Translate an infra config into .krs" description "Host-agnostic entry point shared by `karasu translate` and the App: picks the adapter for the format, runs it, optionally wraps the output in a system block, and returns warnings as data" facets trust_boundary link "https://github.com/kompiro/karasu/blob/main/packages/core/src/translate/translate.ts" "translate.ts" } usecase WrapInSystem { label "Wrap output in a system block" description "Wraps openapi / db output in `system { ... }`; rejects a name that is not a .krs identifier (SYSTEM_NAME_PATTERN)" facets trust_boundary } usecase TranslateCompose { label "Translate docker-compose" description "docker-compose YAML -> a deploy block with one oci unit per service (image + realizes)" facets trust_boundary } usecase TranslateK8s { label "Translate Kubernetes manifests" description "Multi-document k8s YAML -> a deploy block named by namespace; Deployment / StatefulSet / DaemonSet become oci, Job / CronJob become job (with schedule)" facets trust_boundary } usecase TranslateOpenApi { label "Translate an OpenAPI spec" description "OpenAPI YAML/JSON -> a service with one provisional domain; operations grouped per resource path segment (resource granularity) or one usecase per operation (operation granularity)" facets trust_boundary } usecase TranslateDbSchema { label "Translate a SQL schema" description "SQL DDL or a migration history (CREATE / DROP / RENAME replayed) -> a database block of tables with recorded table -> table FK edges" facets trust_boundary } usecase TranslateWrangler { label "Translate wrangler.toml" description "Cloudflare Worker config -> a self-contained system (Worker service, D1 / R2 / KV / Vectorize / Queue infra, Workers AI / Durable Object externals, service-binding edges) plus a deploy block with typed stores (ADR-1935)" facets trust_boundary } usecase ResolveRealizes { label "Resolve realizes for a deploy unit" description "Three stages for compose / k8s units: the karasu/realizes label, then karasu.map.yaml, then the kebab-case -> PascalCase naming heuristic; an unresolved unit gets a TODO comment and a warning" facets trust_boundary } usecase InferSoftForeignKeys { label "Infer soft foreign keys" description "db: a `_id` / `_code` column naming a known table (s / es plural fallback) becomes a soft FK when no explicit REFERENCES covers it" } usecase FoldAggregates { label "Fold tables into aggregates" description "db aggregate granularity: a composite-PK child with an FK to its parent, or a `_items` / `_lines` / `_history` ... child with an FK to the stem table, folds into its root; transitive parents flatten to the root" } usecase ScaffoldEntityDomain { label "Scaffold entities from aggregate roots" description "db aggregate granularity: a provisional per-database domain with one entity per root (table mapping) and root -> root relations, soft-only ones tagged [inferred]" } usecase EmitUsecaseBindings { label "Emit usecase -> resource bindings" description "openapi (resource granularity) / db (aggregate granularity) with --emit-bindings: a resource with an operations line per usecase; --emit-crud-decoration adds `:` (list:read, post:create, select:read, insert:create)" } entity SourceManifest { label "Source manifest" description "The untrusted input text: compose / k8s YAML, OpenAPI spec, SQL script, wrangler.toml" facets trust_boundary } entity MapFile { label "karasu.map.yaml" description "Deploy unit name -> service id(s), read by the host and passed in as text" facets trust_boundary } entity TranslateOptions { label "Translate options (TranslatorContext)" description "format, input name, map file, service / database / system name, granularity, emit-bindings, emit-crud-decoration, warning sink" TranslateOptions -> MapFile "carries" } entity ComposeService { label "Compose service" ComposeService -> SourceManifest "declared in" } entity K8sWorkload { label "Kubernetes workload" K8sWorkload -> SourceManifest "declared in" } entity DeployUnit { label "Emitted deploy unit" description "An oci / job unit emitted from a compose service or k8s workload" DeployUnit -> ComposeService "from (compose)" DeployUnit -> K8sWorkload "from (k8s)" DeployUnit -> RealizesResolution "realizes" } entity RealizesResolution { label "Realizes resolution" description "Resolved service id list or unresolved" RealizesResolution -> MapFile "looked up in" } entity OpenApiOperation { label "OpenAPI operation" OpenApiOperation -> SourceManifest "declared in" } entity OpenApiResourceGroup { label "OpenAPI resource group" description "Operations sharing the first non-prefix, non-version, non-parameter path segment; becomes one Manage usecase" OpenApiResourceGroup -> OpenApiOperation "groups" } entity DbTable { label "DB table" DbTable -> SourceManifest "surviving the replayed script" DbTable -> ForeignKey "declares" DbTable -> Aggregate "folded into" } entity ForeignKey { label "Foreign key (explicit)" ForeignKey -> DbTable "references" } entity SoftForeignKey { label "Soft foreign key" description "A ForeignKey of kind soft, inferred from the column name" SoftForeignKey -> DbTable "references by naming convention" } entity Aggregate { label "Aggregate" Aggregate -> DbTable "rooted at" } entity RootRelation { label "Root relation" description "A child's FKs rolled up to its root and deduplicated by target; one set feeds both the table -> table edges and the entity relations" RootRelation -> Aggregate "between roots" RootRelation -> ForeignKey "confirmed by" RootRelation -> SoftForeignKey "inferred from" } entity WranglerBinding { label "Wrangler binding" WranglerBinding -> SourceManifest "declared in" } entity TranslationResult { label "Translation result" description "The generated .krs scaffold text plus non-fatal warnings" TranslationResult -> TranslationWarning "collects" TranslationResult -> Language.SourceFile "emits .krs text for" } entity TranslationWarning { label "Translation warning" description "Plain English message (unresolved realizes, duplicate binding renamed, unsupported binding, --system ignored)" } } domain ModelAnalysis { label "Model analysis" description "Reports over a compiled model for people and harnesses: coverage, CRUD matrix, team dependencies. Seam resolved (was @draft): kept as its own context, view diff moved to Modeling, subtree to CommandLine" // ─── View diff (core/src/diff, core/src/compile/compile-diff.ts) ───────── // ─── Coverage (core/src/view/coverage-extract.ts, cli/src/coverage.ts) ── usecase MeasureDomainCoverage { label "Measure per-domain density" description "extractCoverage(): usecases / entities / resource refs / edges attributed to the nearest enclosing domain, normalized score, thin flag below half the median (or an explicit threshold); every domain reported" } usecase MeasurePhysicalCoverage { label "Measure physical-layer recovery" description "Per declared infra block, counted from the declaration side: leaves, mapped by an entity, referenced by a resource (through the entity resolver), unmapped-but-referenced, unreferenced; plus tableless entities as a fact" } usecase DiffStoreRelations { label "Compare recorded and projected table relations" description "Per database: relations recorded on the leaves vs those the entity layer projects onto them (recorded-without-projection, projection-without-recorded, direction and kind mismatch)" } usecase FormatCoverageReport { label "Format a coverage report" description "Markdown tables (domains, infra, database relations, tableless entities) or JSON; the physical tables are omitted when the model declares no infra" } // ─── CRUD matrix (core/src/view/crud-matrix-*.ts, cli/src/matrix.ts) ──── usecase ExtractCrudMatrix { label "Extract the CRUD matrix" description "extractCrudMatrix(): usecase rows × declared infra leaf columns (plus referenced non-infra resources), cells from operations incl. decorated verbs and unknown verbs, row / column CRUD tallies; filters by service, infra kind, external, writes only, omit empty" } usecase FormatCrudCell { label "Format a matrix cell" description "formatCell(): CRUD initials in order, ? for unknown verbs or an undeclared relation; the one short form shared by md, svg and the app panel" } usecase FormatCrudMatrix { label "Format the CRUD matrix as text" description "formatMatrixAsMarkdown / formatMatrixAsCsv with optional totals and footnotes for unrecognized verbs and omitted rows / columns" } // ─── Team dependencies (core/src/view/team-dependency-*.ts) ───────────── usecase ExtractTeamDependencies { label "Derive team dependencies" description "extractTeamDependencies(): logical edges × 1:N ownership, endpoints resolved by the shared edge-endpoint resolver, one dependency per team pair and edge kind, cross-team vs nested by the org tree; observes, never ranks" } usecase ResolveInheritedOwnership { label "Resolve a node's owning teams" description "Nearest owned ancestor wins outright (owns is written per service, edges per domain); a node of a kind that can never be owned is not reported as unowned" } usecase DetectStructuralOverlaps { label "Detect ownership crossing containment" description "A node owned by a team other than the owner of the node it sits inside, invisible to the edge join" } usecase FormatTeamDependencies { label "Format team dependencies as text" description "Markdown team × team matrix plus provenance table and the unowned remainder, or tidy CSV discriminated by a relation column" } // ─── Subtree slicing (cli/src/subtree.ts) ─────────────────────────────── // ─── Entities ─────────────────────────────────────────────────────────── entity CoverageReport { label "Coverage report" CoverageReport -> DomainCoverage "per domain" CoverageReport -> PhysicalCoverage "physical layer" } entity DomainCoverage { label "Domain coverage" description "Counts, normalized score and the relative thin flag of one domain" DomainCoverage -> Modeling.ModelNode "measures domain" } entity PhysicalCoverage { label "Physical coverage" PhysicalCoverage -> InfraCoverage "per infra block" PhysicalCoverage -> TablelessEntity "lists" } entity InfraCoverage { label "Infra coverage" InfraCoverage -> Modeling.InfraLeaf "counts leaves of" InfraCoverage -> StoreRelationGap "per database" } entity StoreRelationGap { label "Recorded vs projected table relation" description "An ordered leaf pair present on one side only, or with mismatched direction / kind" StoreRelationGap -> Modeling.InfraLeaf "between" } entity TablelessEntity { label "Tableless entity" description "An entity with no table mapping, reported as a fact, never a defect" TablelessEntity -> Modeling.ModelNode "is" } entity CrudMatrix { label "CRUD matrix" CrudMatrix -> CrudRow "rows" CrudMatrix -> CrudColumn "columns" CrudMatrix -> CrudCell "cells" CrudMatrix -> CrudTally "row and column totals" } entity CrudRow { label "Matrix row (usecase)" CrudRow -> Modeling.ModelNode "usecase" } entity CrudColumn { label "Matrix column (infra leaf)" CrudColumn -> Modeling.InfraLeaf "declared leaf" } entity CrudCell { label "Matrix cell" description "Recognized CRUD verbs, unknown verbs, declared flag, write flag" CrudCell -> CrudRow "row" CrudCell -> CrudColumn "column" CrudCell -> Language.ResourceOperation "classifies" } entity CrudTally { label "CRUD tally" } entity TeamDependencyReport { label "Team dependency report" TeamDependencyReport -> TeamDependency "dependencies" TeamDependencyReport -> StructuralOverlap "overlaps" TeamDependencyReport -> UnownedEndpoint "unowned remainder" } entity TeamDependency { label "Team dependency" description "One team pair for one edge kind, cross-team or nested, with its edge count" TeamDependency -> TeamDependencyEdge "induced by" TeamDependency -> TeamOwnership "joins" } entity TeamDependencyEdge { label "Inducing edge" TeamDependencyEdge -> Modeling.ModelEdge "is" } entity TeamOwnership { label "Resolved team ownership" description "Owning teams of a node, direct or inherited from the nearest owned ancestor, read 1:N" TeamOwnership -> Modeling.ModelNode "owned node" TeamOwnership -> Language.OrganizationBlock "teams and owns declared in" } entity StructuralOverlap { label "Structural overlap" StructuralOverlap -> Modeling.ModelNode "inner and enclosing node" StructuralOverlap -> TeamOwnership "disagreeing owners" } entity UnownedEndpoint { label "Unowned endpoint" UnownedEndpoint -> Modeling.ModelNode "is" } // ─── Domain edges ─────────────────────────────────────────────────────── -> Modeling "extracts system / deploy / org slices to diff; edge keys; model warnings; entity resolver, declared-infra index, store relation projection, canvas edges and edge-endpoint resolver for the measurements; resolved systems for matrix, coverage and subtree" -> Language "AST types, node-path ids, team ownership index from reference validation" } } service KarasuCli { label "karasu CLI" delivers CliTool, WebApp domain CommandLine { label "Command line" description "Command surface (render, check, coverage, translate, serve, skill, capabilities, append / insert / remove / apply, subtree …), deprecations and diagnostic output. Absorbed the folded ModelEditing commands" -> Modeling "compile a project from disk (compileProject / buildAllViewsSvgProject) and the single-file compile behind serve's /render" -> Rendering "draw.io export (buildDrawioProject) and the CRUD matrix SVG (renderMatrixAsSvg)" -> Language "fmt (format), import resolution (ImportResolver), subtree re-serialization (serializeKrsFile), safe relative paths (isSafeRelativePath), language version" -> Styling "lint-style (StyleParser, validateStyleValues) and tidy-style (tidyStyleSheet)" -> Translation "translate (translateInfraConfig, SYSTEM_NAME_PATTERN)" -> ModelAnalysis "coverage, CRUD matrix, team dependencies and view diff extraction" -> Localization "render diagnostics and warnings in the locale read from LC_ALL / LC_MESSAGES / LANG" // ─── Commands (one per entry in agent-surface.json) ───────────────────── usecase RenderCommand { label "karasu render" description "Compile a .krs project (imports resolved) and write every view bundled, one --view, or draw.io XML to stdout or --output; --include-matrix also writes .matrix.svg. Exits 1 on any error diagnostic before writing" facets agent_surface link "https://github.com/kompiro/karasu/blob/main/packages/cli/src/render.ts" "render.ts" resource CliTool.RenderOutput { operations write:create } resource CliTool.KrsSources { operations read:read } } usecase CheckCommand { label "karasu check" description "Run the same all-views compile as render and write nothing; text lines on stderr or one JSON document on stdout (--format json). Exit 1 iff an error-severity diagnostic exists" facets agent_surface link "https://github.com/kompiro/karasu/blob/main/packages/cli/src/check.ts" "check.ts" resource CliTool.KrsSources { operations read:read } } usecase ServeCommand { label "karasu serve" description """ Start a local HTTP server (default 127.0.0.1:3000) over a directory: the bundled preview app (SPA fallback to index.html), the /api/* project routes, the /api/watch change stream and the /render image endpoint. /api/* answers only when the Host header is localhost, an IP literal or an --allowed-host name (DNS-rebinding guard, not access control); any request carrying x-karasu-render is refused so /render cannot loop back. Warns when bound to a non-loopback address or when [::1]:port is shadowed. """ facets agent_surface, trust_boundary link "https://github.com/kompiro/karasu/blob/main/packages/cli/src/serve.ts" "serve.ts" link "https://github.com/kompiro/karasu/blob/main/packages/cli/src/serve-host.ts" "serve-host.ts" } usecase TranslateCommand { label "karasu translate" description "Read a compose / k8s / openapi / db / wrangler file (and karasu.map.yaml beside it or --map), translate it to a .krs scaffold and write it to stdout or --output. Option combinations and the --system name are validated before anything is read" facets agent_surface, trust_boundary link "https://github.com/kompiro/karasu/blob/main/packages/cli/src/translate/cli-options.ts" "cli-options.ts" resource CliTool.KrsSources { operations write:create } } usecase FmtCommand { label "karasu fmt" description "Format .krs files in place (all under cwd by default, skipping node_modules / .git / dist / .claude / .worktrees), --check for CI, or --stdin to stdout" facets agent_surface resource CliTool.KrsSources { operations read:read, rewrite:update } } usecase LintStyleCommand { label "karasu lint-style" description "Parse .krs.style files and check property values against the schema; exit 1 on an error-severity finding only" facets agent_surface resource CliTool.KrsSources { operations read:read } } usecase TidyStyleCommand { label "karasu tidy-style" description "Merge duplicate rules and group properties by axis in .krs.style files, in place, --check or --stdin; --no-merge only reorders" facets agent_surface resource CliTool.KrsSources { operations read:read, rewrite:update } } usecase CoverageCommand { label "karasu coverage" description "Per-domain density report (md / json) with an optional thin-score --threshold, for a reverse / repair loop" facets agent_surface resource CliTool.KrsSources { operations read:read } } usecase MatrixCommand { label "karasu matrix" description "Usecase x resource CRUD matrix as md / csv / svg, filtered by --service / --infra / --external / --writes-only / --omit-empty" facets agent_surface resource CliTool.RenderOutput { operations write:create } resource CliTool.KrsSources { operations read:read } } usecase SubtreeCommand { label "karasu subtree" description "Emit one node's sub-tree as standalone .krs, wrapped to its nearest top-level-capable ancestor (or the full chain with --with-ancestors). The slicing itself lives in cli/src/subtree.ts" facets agent_surface resource CliTool.KrsSources { operations read:read } } usecase DiffCommand { label "karasu diff" description "Render a diff SVG (bundled or one --view) between two .krs entries; either side may be `-`, which is written to a hidden temp file beside the other side so its relative imports resolve, and removed before exit" facets agent_surface resource CliTool.RenderOutput { operations write:create } resource CliTool.KrsSources { operations read:read } } usecase TeamDependenciesCommand { label "karasu team-dependencies" description "Team x team dependency matrix plus provenance (md / csv), derived from owns x logical edges; unowned endpoints are listed, not dropped" facets agent_surface resource CliTool.KrsSources { operations read:read } } usecase SkillInstallCommand { label "karasu skill install" description "Copy one or every agent skill from the karasu-skills package into --dir (default .claude/skills). The name is checked against the shipped skill list before a path is built; existing skills need --force; each copy is staged and swapped in so a failure leaves the old one" facets agent_surface, trust_boundary link "https://github.com/kompiro/karasu/blob/main/packages/cli/src/skill.ts" "skill.ts" } usecase SkillPathCommand { label "karasu skill path" description "Print the absolute path of a shipped skill (or of the skills directory) so an agent can read it without copying" facets agent_surface } usecase CapabilitiesCommand { label "karasu capabilities" description "List commands, arguments, flags, the .krs language version and the deprecation table, as text or --json (schemaVersion 1), generated from the live commander tree" facets agent_surface link "https://github.com/kompiro/karasu/blob/main/packages/cli/src/capabilities.ts" "capabilities.ts" } // ─── serve's HTTP routes ──────────────────────────────────────────────── usecase ServeProjectFiles { label "Serve project files (/api/files, /api/project, /api/file/:name, /api/default)" description "List .krs names, return every .krs / .krs.style with its relative path, return one file, or name the default entry. Paths come from a walk that never follows a symlink out of the served directory; a requested name must be a safe relative path, its realpath must stay inside, and the read uses O_NOFOLLOW" facets trust_boundary resource CliTool.KrsSources { operations list:read, read:read } } usecase StreamFileChanges { label "Stream file changes (/api/watch)" description "Server-sent events for .krs / .krs.style add / change / unlink under the served directory (chokidar), so the preview reloads" resource CliTool.KrsSources { operations watch:read } } usecase RenderFromRequest { label "Render from a request (/render?code= | ?src=)" description "Compile one source (base64 `code` or a fetched `src` URL, no import resolution) and answer image/svg+xml with CORS *, 400 on bad parameters, 422 with localized error lines on compile errors, 503 when both src fetch slots are busy" facets trust_boundary link "https://github.com/kompiro/karasu/blob/main/packages/cli/src/render-endpoint.ts" "render-endpoint.ts" } usecase FetchRemoteSource { label "Fetch a remote .krs (SSRF guard)" description "GET a public http(s) URL with redirects followed by hand (max 5), every hop's resolved address checked inside the socket lookup against loopback / private / link-local / CGNAT / multicast ranges and this machine's own addresses, a 256 KiB decompressed body limit and a 10 s timeout; tagged with x-karasu-render" facets trust_boundary link "https://github.com/kompiro/karasu/blob/main/packages/cli/src/render-fetch.ts" "render-fetch.ts" } // ─── Cross-cutting steps ──────────────────────────────────────────────── usecase ResolvePathArgument { label "Resolve a path argument" description "Turn a typed path into an entry: a directory means its index.krs, missing vs unreadable (EACCES, ELOOP) are told apart, a directory where one file is expected is refused, and a file list expands directories by suffix" facets trust_boundary link "https://github.com/kompiro/karasu/blob/main/packages/cli/src/path-arg.ts" "path-arg.ts" } usecase ReportDiagnostics { label "Report diagnostics" description "Print errors, warnings and infos as `Severity[KRSnnn]: file:line:col: message` lines in the CLI locale, or as the check --format json document (schemaVersion, errorCount, locale-independent code and params); return the error count for the exit status" link "https://github.com/kompiro/karasu/blob/main/packages/cli/src/report-diagnostics.ts" "report-diagnostics.ts" } usecase ApplyDeprecations { label "Emit deprecation notices" description "Before commander parses argv, rewrite deprecated command / flag aliases to their replacement and print the fixed-format `karasu: deprecated: ...` line, or exit 1 with `karasu: removed: ...` for a tombstone" link "https://github.com/kompiro/karasu/blob/main/packages/cli/src/deprecations.ts" "deprecations.ts" } usecase ResolveCliLocale { label "Resolve the CLI locale" description "Pick en / ja from LC_ALL, LC_MESSAGES, LANG (strongest first) for diagnostic text" } usecase PrintVersion { label "karasu --version" description "Print the CLI package version and the .krs language version" } // ─── Entities ─────────────────────────────────────────────────────────── entity Command { label "CLI command" description "A commander command with its positional arguments and options" Command -> Command "subcommand" } entity CommandFlag { label "Command flag" CommandFlag -> Command "belongs to" } entity AgentSurfaceEntry { label "Agent surface entry" description "A command and its flags pinned in agent-surface.json: dropping or renaming one needs a Deprecation" AgentSurfaceEntry -> Command "pins" AgentSurfaceEntry -> CommandFlag "pins" } entity Deprecation { label "Deprecation" description "A retired command or flag, its replacement, since / removal versions; stays as a tombstone once removed" Deprecation -> Command "replaced by" } entity DeprecationNotice { label "Deprecation notice" description "The fixed-format stderr line agents parse; never translated" DeprecationNotice -> Deprecation "announces" } entity CapabilitiesReport { label "Capabilities report" CapabilitiesReport -> Command "lists" CapabilitiesReport -> Deprecation "lists" } entity EntryPath { label "Resolved entry path" description "Absolute path plus the display path of the entry .krs (a directory's index.krs) and the Node fs provider" EntryPath -> Language.SourceFile "names the entry of" } entity DiagnosticReport { label "Diagnostic report" description "The text lines or the JSON document for one run" DiagnosticReport -> Language.Diagnostic "formats" DiagnosticReport -> Modeling.Warning "formats" DiagnosticReport -> CliLocale "rendered in" DiagnosticReport -> EntryPath "locates against" } entity CliLocale { label "CLI locale" } entity ServedDirectory { label "Served directory" description "The directory serve exposes; nothing outside its realpath is listed or read" } entity ServedFile { label "Project file" description "A .krs or .krs.style under the served directory, by relative path" ServedFile -> ServedDirectory "lives under" ServedFile -> Language.SourceFile "is read as" } entity ServeWatchEvent { label "Watch event" description "SSE payload: path, file (for .krs) and add / change / unlink" ServeWatchEvent -> ServedFile "announces" } entity AllowedHost { label "Allowed host" description "An --allowed-host name (or .suffix) /api/* also answers to" AllowedHost -> ServedDirectory "opens /api/* over" } entity ServeRenderRequest { label "Render request" description "/render query: src URL or base64 code, optional view" ServeRenderRequest -> RemoteSource "fetches" ServeRenderRequest -> Rendering.SvgBundle "answered with" } entity RemoteSource { label "Remote source" description "The fetched text of a src URL, or the failure reason (blocked, too large, too many redirects, timeout)" RemoteSource -> BlockedAddressRange "checked against" } entity BlockedAddressRange { label "Blocked address range" description "Loopback, private, link-local, CGNAT, multicast, reserved ranges plus this machine's own interface addresses" } entity SkillPackage { label "Shipped skill" description "A directory with SKILL.md in the karasu-skills package, a runtime dependency of the CLI" } entity InstalledSkill { label "Installed skill" InstalledSkill -> SkillPackage "copied from" } // moved from ModelEditing (seam verdict) usecase AppendCommand { label "karasu append" description "Append piped .krs as a new top-level block at the end of a file, creating the file when missing. The piped text is spliced verbatim: nothing parses it before the write" facets agent_surface, trust_boundary link "https://github.com/kompiro/karasu/blob/main/packages/cli/src/append.ts" "append.ts" resource CliTool.KrsSources { operations append:create,update } } usecase InsertCommand { label "karasu insert" description "Insert piped .krs as the last child of , re-indented to the parent's closing brace. Refuses a missing file or an unknown / ambiguous id; the piped text itself is not parsed" facets agent_surface, trust_boundary link "https://github.com/kompiro/karasu/blob/main/packages/cli/src/insert.ts" "insert.ts" resource CliTool.KrsSources { operations read:read, splice:update } } usecase RemoveCommand { label "karasu remove" description "Remove the node (logical, deploy or org) and its source range from a file in place; refuses an unknown or ambiguous id" facets agent_surface link "https://github.com/kompiro/karasu/blob/main/packages/cli/src/remove.ts" "remove.ts" resource CliTool.KrsSources { operations read:read, splice:update } } usecase ApplyCommand { label "karasu apply" description """ Upsert piped .krs (typically `karasu translate` output) into a file: each incoming top-level system / service / domain / deploy replaces the node with the same id (a system whose children all exist is replaced child by child, keeping hand-added siblings) or is appended; input carrying a top-level database / queue / storage is appended whole so a translate --from db pair stays together. A failed replace is a warning, not an exit. """ facets agent_surface, trust_boundary link "https://github.com/kompiro/karasu/blob/main/packages/cli/src/apply.ts" "apply.ts" resource CliTool.KrsSources { operations read:read, upsert:update } } usecase MergeIncomingBlocks { label "Merge incoming blocks (upsert by id)" description "apply's planner: parse incoming and existing text, collect existing ids (system descendants included), then issue one append or replace patch per incoming top-level block" } usecase ReadStdin { label "Read piped input" description "Read all of stdin as UTF-8; empty input is refused by every editing command. Shared with fmt / lint-style / tidy-style --stdin" } entity IncomingBlock { label "Incoming block" description "A top-level block of the piped text, sliced out by its parsed range" IncomingBlock -> Language.KrsPatch "becomes" IncomingBlock -> Language.Declaration "parsed as" } // moved from ModelAnalysis (seam verdict) usecase SliceSubtree { label "Slice a node's subtree out of a model" description "Find the node by bare id (ambiguous ids are refused with every match's path), keep the chain up to the nearest system / service / domain (or the system root with --with-ancestors), prune siblings and wrapper edges, serialize as a standalone .krs" } entity Subtree { label "Subtree slice" description "A target node with its full interior and a pruned ancestor chain, standalone as a .krs file" Subtree -> Modeling.ModelNode "target and ancestors" Subtree -> Language.SourceFile "serialized as" } } } service KarasuApp { label "karasu app" description "Vite + React SPA on Cloudflare Pages, plus the Pages Functions deployed with it" delivers WebApp domain Workspace { label "Workspace" description "Projects, files and storage modes (OPFS / memory / serve), snapshots, the editor document and file tree" -> Language "FileSystemProvider port + InMemory provider, isSafeRelativePath / normalizePath / resolvePath, Parser (example import walk), builtin example projects, getReference sample, findOpenableExample" -> Localization "useTranslation / setLocale for the UI, resolveLocale to pick the ja or en seed projects, tour text catalogs" -> Preview "mounts AppShell with the entry path, dispatches SELECT_FILE / SET_COMPARE_SOURCE / SET_CURRENT_PROJECT into the app state, registers keyboard commands, sets the theme through ThemeProvider" -> CommandLine "serve mode: GET /api/files (mode probe), /api/default, /api/project and the /api/watch SSE stream of `karasu serve`" -> Sharing "boot reads an inline share payload (#s=) and a ?krs= anchor, and seeds the shared style at SHARE_STYLE_IMPORT_PATH" -> AssistantChat "Settings tab stores the Anthropic API key" // ─── Mode and boot ─────────────────────────────────────────────────────── usecase DetectAppMode { label "Choose the storage mode" description "detectAppMode: serve when GET /api/files answers JSON within 200 ms, else memory when ?mode=memory or OPFS is missing, else opfs. A build can fix the mode (serve-main.tsx fixes serve so Monaco is left out)" link "https://github.com/kompiro/karasu/blob/main/packages/app/src/fs/detect-storage-mode.ts" "detect-storage-mode.ts" } usecase BootProjectWorkspace { label "Boot the project workspace" description "OPFS mode: list projects from the metadata file; on an empty list seed the default projects (Getting Started, ec-platform, client-mcp, multi-file-system, feature-samples, facet-styling) in the browser locale; otherwise sweep stale paste-compare temp files. Restores the project from /projects/, the last project id or the first project, and opens the file the URL hash names or index.krs" link "https://github.com/kompiro/karasu/blob/main/packages/app/src/hooks/useProjectInitialization.ts" "useProjectInitialization.ts" resource WebApp.LocalePref { operations get:read } resource WebApp.PasteCompare { operations sweep:delete } resource WebApp.LastProject { operations get:read, set:update } resource WebApp.ProjectIndex { operations read:read, seed:create } } usecase OpenMemoryWorkspace { label "Open a single-file memory workspace" description "Memory mode (no OPFS, ?mode=memory, or an inline share link): seeds /memory/index.krs with the shared .krs or the locale's sample, plus a shared style sheet, in an in-memory fs that never touches the visitor's projects" facets trust_boundary } usecase PreviewServedDirectory { label "Preview a served directory" description "Serve mode: mirrors every .krs / .krs.style from GET /api/project into the in-memory fs under /serve, compiles the entry named by the URL path or /api/default, and refetches on every change / add / unlink SSE event or reconnect. Read-only: the editor is hidden" facets trust_boundary } // ─── Projects ──────────────────────────────────────────────────────────── usecase CreateProject { label "Create a project" description "New /projects/ directory with a default index.krs (system, deploy and organization sample), appended to the metadata file under a serial queue; a failed metadata commit removes the directory" resource WebApp.ProjectFiles { operations write:create } resource WebApp.ProjectIndex { operations write:update } } usecase RenameProject { label "Rename a project" resource WebApp.ProjectIndex { operations write:update } } usecase DeleteProject { label "Delete a project" description "After a confirm dialog: removes the project directory (files, snapshots, temp files) and its metadata entry, then switches to the first remaining project" resource WebApp.ProjectFiles { operations remove:delete } resource WebApp.ProjectIndex { operations write:update } } usecase SwitchProject { label "Switch project" description "From the project selector, the Switch Project… command palette picker or browser back / forward: pushes /projects/#system, remembers the id as the last project and opens its index.krs" resource WebApp.LastProject { operations set:update } resource WebApp.ProjectIndex { operations get:read } } usecase ImportProjectZip { label "Import a project from a ZIP" description "Keeps only .krs / .krs.style entries with a safe relative path, rejects archives over 10 000 entries, 50 MB per file or 200 MB total before inflating, strips a single top-level directory as the project name, and disambiguates the name with (2), (3)…" facets trust_boundary link "https://github.com/kompiro/karasu/blob/main/packages/app/src/utils/import-project-zip.ts" "import-project-zip.ts" resource WebApp.ProjectFiles { operations write:create } resource WebApp.ProjectIndex { operations write:update } } usecase ExportProjectZip { label "Export a project as a ZIP" description "Collects every file under the project root (snapshots and dot files included) into /… and downloads .zip" resource WebApp.ProjectFiles { operations read:read } } usecase OpenGalleryExample { label "Open a gallery example" description "?example=&lang= deep link: checks the slug against the openable-example manifest, fetches the entry and its relative imports from the fixed raw.githubusercontent.com origin (no redirects, 50 files / 1 MB per file / 5 MB total), and opens them as a new project" facets trust_boundary link "https://github.com/kompiro/karasu/blob/main/packages/app/src/utils/fetch-example.ts" "fetch-example.ts" resource WebApp.ProjectFiles { operations write:create } resource WebApp.ProjectIndex { operations write:update } } usecase AddBundledExample { label "Add a bundled example project" description "Copies an example shipped in core into a new, uniquely named project without opening it (used by the first-run guides)" resource WebApp.ProjectFiles { operations write:create } resource WebApp.ProjectIndex { operations write:update } } // ─── Files ─────────────────────────────────────────────────────────────── usecase OpenFile { label "Open a file" description "Reads the file into the editor; a missing file opens as an empty buffer, an existing file whose read fails keeps the current selection (so auto-save cannot clobber it), and a later click supersedes an earlier slow read" resource WebApp.ProjectFiles { operations read:read } } usecase CreateFile { label "Create a file or folder" description "File tree inline input under a folder; a bare name gets .krs, .krs.style is kept" resource WebApp.ProjectFiles { operations write:create } } usecase RenameFileOrFolder { label "Rename a file or folder" description "Copy to the new name then delete the old one (folders recursively); the editor follows a renamed open file" resource WebApp.ProjectFiles { operations rename:update } } usecase DeleteFileOrFolder { label "Delete a file or folder" description "After a confirm dialog; clears the editor when the open file is deleted" resource WebApp.ProjectFiles { operations remove:delete } } // ─── Editor document ───────────────────────────────────────────────────── // ─── Snapshots and compare ─────────────────────────────────────────────── usecase CaptureSnapshot { label "Capture a snapshot" description "Manual (file tree Snapshot now, optional label) or automatic (5 min after the last edit and on beforeunload). Stored per file under .snapshots//; an auto capture identical to the latest one (FNV-1a hash) is skipped; only the newest 20 auto snapshots are kept, manual ones are never pruned" resource WebApp.Snapshots { operations write:create, gc:delete } } usecase CompareWithSnapshot { label "Compare with a snapshot" description "Picker of the file's snapshots, newest first; the chosen one is mounted read-only at /.snapshot-view// over the live fs, so its imports resolve against the current workspace" resource WebApp.Snapshots { operations read:read } } usecase CompareWithFile { label "Compare with another file" resource WebApp.ProjectFiles { operations read:read } } usecase CompareWithPaste { label "Compare with pasted text" description "Pasted .krs is written to the hidden temp file .karasu-paste-compare.krs in the project and used as the diff base; the file is deleted when diff mode leaves the pasted source, and swept at boot after a crash" facets trust_boundary resource WebApp.PasteCompare { operations write:create, remove:delete } } usecase ViewPastedSource { label "View the pasted source" resource WebApp.PasteCompare { operations read:read } } // ─── Settings and layout ───────────────────────────────────────────────── usecase ChangeLocale { label "Change the UI language" resource WebApp.LocalePref { operations set:update } } usecase ChangeTheme { label "Change the theme" description "system / light / dark preference" resource WebApp.ThemePref { operations set:update } } usecase ChangeDisplayMode { label "Change the node display mode" description "shape or icon, kept in the app state (not persisted)" } usecase StoreApiKey { label "Store or clear the Anthropic API key" description "Settings tab: keeps the key in sessionStorage by default, or in localStorage when the user opts in; Clear removes it from both" facets secret resource WebApp.ApiKeyPersistChoice { operations get:read, set:update } resource WebApp.ApiKeyPersisted { operations set:create, remove:delete } resource WebApp.ApiKeySession { operations set:create, remove:delete } } usecase ResizePanels { label "Resize the sidebar and the editor" description "Drag to resize, double-click to reset; the widths are remembered per browser" resource WebApp.EditorWidth { operations get:read, set:update } resource WebApp.SidebarWidth { operations get:read, set:update } } // ─── First run ─────────────────────────────────────────────────────────── usecase ShowWelcome { label "Show the first-run Welcome" description "Only on the boot that seeded the default projects, unless dismissed before or the URL asked for a place (example, share, permalink); choices: design, understand, evolve or straight to the editor" resource WebApp.ProjectFiles { operations read:read } resource WebApp.WelcomeDismissed { operations get:read, dismiss:update } } usecase RunGuidedTour { label "Run a guided tour" description "Opens a fresh copy of the tour's sample project (or the recorded copy while it still matches the sample), drives each step's scene (file, view, drill) and advances on the step's completion signal; progress is recorded per step" resource WebApp.TourProjectKey { operations set:update } resource WebApp.TourProgressKey { operations set:create, step:update, end:delete } } usecase ResumeGuidedTour { label "Resume a guided tour after reload" description "At boot, resumes the recorded step only on the tour project's own URL (or a bare URL that opens it); a link from outside keeps the record, a record whose project is gone is discarded" resource WebApp.LastProject { operations get:read } resource WebApp.TourProgressKey { operations get:read } } usecase RestartGuidedTour { label "Restart the guided tour" description "Restart Guided Tour… redoes the last started guide in the project that guide used" resource WebApp.TourProjectKey { operations get:read } } // ─── Entities ──────────────────────────────────────────────────────────── entity Project { label "Project" description "id, name, rootPath /projects/; listed in the OPFS metadata file /meta/projects.json" Project -> Language.ExampleProject "seeded from" } entity ProjectFile { label "Project file" description "A .krs or .krs.style under the project root; dot-prefixed entries (.snapshots, the paste temp file) are hidden from the tree" ProjectFile -> Project "belongs to" } entity StorageMode { label "Storage mode" description "opfs / memory / serve: which FileSystemProvider backs the workspace" } entity FsEvent { label "File system event" description "create / change / delete emitted by the observable fs after a mutation" FsEvent -> ProjectFile "about" } entity Snapshot { label "Snapshot" description "id, trigger (auto / manual), optional label, size and content hash; the content is a sibling .krs" Snapshot -> ProjectFile "captures" } entity SnapshotIndex { label "Snapshot index" description "index.json per file under .snapshots/, version 1" SnapshotIndex -> Snapshot "lists" } entity CompareSource { label "Compare source" description "The diff base: another file, pasted text or a snapshot" CompareSource -> ProjectFile "file" CompareSource -> PastedSource "pasted" CompareSource -> Snapshot "snapshot" } entity PastedSource { label "Pasted source" description "Untrusted text held in the hidden temp file .karasu-paste-compare.krs" facets trust_boundary PastedSource -> Project "held in" } entity ProjectArchive { label "Project ZIP archive" description "An imported or exported .zip of a project" facets trust_boundary ProjectArchive -> ProjectFile "contains" } entity MirroredServeFile { label "Mirrored served file" description "A .krs / .krs.style that `karasu serve` sends, mirrored at /serve/ in the in-memory fs" facets trust_boundary MirroredServeFile -> CommandLine.ServedFile "mirrors" } entity Settings { label "User settings" description "UI language, theme preference, node display mode and the API key persistence choice" Settings -> Localization.Locale "language" Settings -> Styling.DisplayMode "display mode" Settings -> Styling.Theme "theme" } entity PanelLayout { label "Panel layout" description "Sidebar and editor widths remembered per browser" } entity Tour { label "Guided tour" description "service-split, understand, evolve, service-split-payroll: ordered steps with a scene and a completion condition" Tour -> Language.ExampleProject "teaches with" } entity TourProgress { label "Tour progress" description "Tour id, project id and step index, versioned (v 1)" TourProgress -> Tour "of" TourProgress -> Project "in" } entity TourProject { label "Last tour project" description "Which guide was started last and in which project, for Restart Guided Tour…" TourProject -> Tour "guide" TourProject -> Project "copy" } entity WelcomeState { label "Welcome dismissed flag" } // moved from AssistantChat (seam verdict) usecase TranslateManifest { label "Translate a pasted manifest" description "Command palette / sidebar opens the dialog: paste or load a compose / k8s / OpenAPI / SQL / wrangler file, pick options (map file, service, database, system, granularity, bindings), translate client-side, then copy or download the .krs; the result is never written into the project" facets trust_boundary } -> Styling "2 entity relations" } domain Editing { label "Editing (karasu editor)" description "The in-app Monaco editor: editing .krs source, syntax highlighting, IME composition, format / tidy, reacting to external writes, jump-to-source. Absent in serve mode and the VS Code viewer (hideEditor). Seam resolved: split out of Workspace, which it depends on" -> Workspace "auto-save goes through the per-file SerialQueue (fs/serial-queue.ts) onto the workspace fs, external refresh watches the ObservableFileSystemProvider, a cross-file jump reads the definition file; the edit pane hosts the Settings tab (SettingsPane)" -> Preview "dispatches UPDATE_FILE_CONTENT / SELECT_FILE into the app state (state/app-reducer), picks karasu-dark / karasu-light from useTheme, registers keyboard commands (useCommand)" -> Language "format / FormatError, Parser + KrsFile walked by findNodeLine, normalizePath, the FileSystemProvider port; the Monarch keyword list hand-copies the lexer's keywords" -> Styling "tidyStyleSheet for the Tidy action on an open .krs.style" -> AssistantChat "the edit pane hosts the Chat tab (ChatPane) and reads the stored API key (getStoredApiKey) for it" // ─── New usecases (missed in Phase 1) ──────────────────────────────────── usecase HighlightKrsSyntax { label "Highlight .krs syntax" description "Registers the `krs` language in Monaco once (beforeMount) with a hand-written Monarch tokenizer (keywords, @annotations, -> / -->, strings, comments) and the karasu-dark / karasu-light editor themes, switched with the app's effective theme. .krs.style files are tokenized as krs too" link "https://github.com/kompiro/karasu/blob/main/packages/app/src/components/EditorPane.tsx" "EditorPane.tsx" } usecase ComposeWithIme { label "Type through an IME composition" description "While an IME composition is in flight the editor holds the latest value back and flushes it once on compositionEnd, so pushing intermediate values into the controlled value cannot drop or duplicate characters (Google JP IME on Blink)" } usecase SwitchEditPaneTab { label "Switch the edit pane tab" description "Editor / Chat / Settings tabs (EditTabBar, arrow keys between triggers); mod+shift+1 shows the Editor and mod+shift+2 the Chat even while a text input has focus; Settings has no shortcut. Format / Tidy toolbar only on the Editor tab" } // ─── New entities ──────────────────────────────────────────────────────── entity EditPaneTab { label "Edit pane tab" description "editor / chat / settings: which panel the edit pane shows (component state, not persisted)" EditPaneTab -> AssistantChat.ChatSession "chat tab shows" } entity KrsEditorGrammar { label "Editor grammar for krs" description "Monaco language id `krs`: Monarch keyword list and token rules, plus the two editor colour themes" KrsEditorGrammar -> Language.Token "approximates" } entity SourceJump { label "Pending source jump" description "Target line of a jump from the preview to a node's definition, held until the cross-file SELECT_FILE has put the definition file into the editor" SourceJump -> Workspace.ProjectFile "in file" SourceJump -> Language.Declaration "to the line of" } // moved from Workspace (seam verdict) usecase EditDocument { label "Edit and auto-save the document" description "Every Monaco change updates the state, is written to disk through a per-file serial queue (so writes land in order), and triggers a recompile; the written values are remembered to recognise their watch echoes" resource WebApp.ProjectFiles { operations autosave:update } } usecase RefreshFromExternalWrite { label "Refresh the editor from an external write" description "Watches the open file on the observable fs; a write that is not the editor's own echo (GUI edge-direction append, AI translate, style bootstrap) replaces the buffer, later write wins (ADR-1076)" resource WebApp.ProjectFiles { operations reload:read } } usecase FormatOpenDocument { label "Format the open .krs" description "Shift+Alt+F / Format button: runs the core formatter, no-op on a parse error or no change, saved like an edit" resource WebApp.ProjectFiles { operations write:update } } usecase TidyOpenStyleSheet { label "Tidy the open .krs.style" resource WebApp.ProjectFiles { operations write:update } } entity EditorDocument { label "Editor document" description "The open file's path and buffer in the app state, with the set of values the editor wrote itself" EditorDocument -> Workspace.ProjectFile "buffers" } // moved from Preview (seam verdict) usecase JumpToEditorSource { label "Jump to a node's source" description "Parse the defining file (nodeFileIndex) to find the node's line and move the Monaco cursor there, switching files first for a cross-file jump" } } domain Preview { label "Preview" description "Viewing a compiled model: view switching, drill-down, breadcrumbs, focus canvas, detail panels, compare / diff mode, facet and group-by controls, deep links" // ─── View selection (state/app-reducer.ts, DiagramTabBar, useAutoSwitchView, useOrgDisplayMode) ─── usecase SwitchView { label "Switch the active view" description "Pick the System / Deploy / Org / Matrix tab (DiagramTabBar or mod+1..4); SET_ACTIVE_VIEW resets the drill path and carries an optional highlight" } usecase AutoSwitchView { label "Auto-switch to the file's only view" description "Once per opened entry: a deploy-only file opens on Deploy, an org-only file on Org (priority system > deploy > org, ADR-766)" } usecase SwitchOrgDisplayMode { label "Switch the org tab's mode" description "grid (drill-down) / tree (#krs-org-tree) / team dependencies, held as one value so at most one mode is on" } usecase ToggleEntityView { label "Toggle a domain's entity view" description "While drilled into a domain, show its entity-relation view instead (#krs-entity-)" } usecase SelectDeployBlock { label "Select the deploy block to draw" } // ─── Compiling what is on screen (useDebouncedCompile, useSystemView / useDeployView / useOrgView, result-fingerprint) ─── usecase CompileActiveView { label "Compile the visible view" description "Debounced (300 ms) compileProject of the entry for the system / deploy / org view with display mode, theme, group-by, facets and collapse state; keeps the last valid SVG on error and publishes only when the result fingerprint changed" } usecase LoadStyleSource { label "Load the imported style sheets" description "useStyleSource: parse the entry's @import list and read the combined .krs.style text through the file system (re-read on a host revision bump)" } usecase ShowWarnings { label "Show warnings and diagnostics" description "WarningPanel / PreviewPane error strip: localized warnings with severity and file:line location; ErrorBanner for transient action failures" } // ─── Navigation (Breadcrumb, useBreadcrumbs, useCrossNavigation, useHistoryNavigation, history-hash) ─── usecase DrillDown { label "Drill into a node" description "Click a service / domain card (or a team card in org) to push its view path" } usecase NavigateBreadcrumb { label "Navigate the breadcrumbs" description "Each crumb navigates to the prefix of the drill path it came from; the longest resolvable prefix is shown (resolveContainerChain)" } usecase CrossNavigate { label "Jump between views" description "Deploy badge on a service -> Deploy with the realizing container marked; team badge -> Org; owned-service link in Org -> System; deploy container -> System with the realized node highlighted" } usecase NavigateHistory { label "Navigate with browser history" description "Every view change pushes #krs--[:][?file=] (buildHash); back / forward re-applies it (parseHash) including the open file" } usecase RestoreDeepLink { label "Restore a deep link" description "Decode a #krs--[:][?file=] hash (or a share target turned into one) on load and apply it once the path index for the open entry is current: re-open the named file only if it is inside the project root, rebuild the drill path from the leaf id, re-apply the highlight. Replaces history entries until done; any visitor action ends it (endDeepLinkRestore)" facets trust_boundary link "https://github.com/kompiro/karasu/blob/main/docs/spec/permalink.md" "Deep permalink anchors" } usecase HighlightNode { label "Highlight a node" description "Mark one element (data-node-id, or data-realized-node-id on a deploy container) and clear it on demand" } usecase RevealNode { label "Keep a node in view" description "requestReveal(nodeId): pan the preview so a requested node sits inside the pane (used by the first-run tour); withdrawn by any press or wheel" } usecase PanZoomDiagram { label "Pan and zoom the diagram" } // ─── Inspecting (NodeDetailPanel, EdgeDetailPanel, EdgeContextMenu, useEdgeDirectionWriter) ─── usecase InspectNodeDetails { label "Inspect a node's details" description "Open the node detail panel from a card's info button: kind, label, Markdown description (marked + DOMPurify), links filtered by isSafeLinkUrl, team, runtime, annotation diff in compare mode" facets trust_boundary } usecase InspectEdgeDetails { label "Inspect an edge's details" description "Read an authored edge (or an aggregated N-domain-edges stub) back from the SVG's data-edge-* attributes; sanitized Markdown description and safe links only" facets trust_boundary } usecase PickEdgeDirection { label "Write an edge direction back to the source" description "Edge context menu: upsert an `edge# { direction: … }` rule into the entry's last imported .krs.style; with no @import yet, derive .krs.style, inject the @import into the .krs and create the sheet; then recompile" resource WebApp.ProjectFiles { operations write:update } } // ─── Diagram controls (PreviewViewControls, preview-group-by, useCollapsibleSet, FacetOverviewPanel) ─── usecase ChangeGroupBy { label "Group the system view" description "none / team / boundary, offered only for axes the model carries (GROUP_BY_AXES)" } usecase ToggleFacetOverlay { label "Highlight a facet" description "Select facets for the overlay ring; orthogonal to group-by; exports show the same selection" } usecase ShowFacetOverview { label "Show a facet's members" description "Draggable panel listing the derived members of each facet, in the renderer's colour order" } usecase CollapseGroups { label "Collapse / expand categories, team frames and services" description "Toggle one external / infra category or team frame, collapse-all / expand-all, or expand one service in place (at most one)" } usecase ShowAllLayers { label "Show all layers" description "Swap the diagram for the stacked all-layers SVG, built eagerly only while the panel is open" } // ─── Compare mode (DiffModeBanner, useAppViews + compile*Diff) ─── usecase ShowDiffView { label "Show the diff against a compare source" description "With a compare source set (file, pasted text or snapshot, chosen in Workspace), compile the view diff in parallel with the base compile; the diff supplies SVG + diagnostics, the base the metadata" } usecase SwapDiffDirection { label "Swap the diff direction" } usecase ExitCompareMode { label "Leave compare mode" } // ─── Other surfaces ─── usecase ShowCrudMatrix { label "Show the CRUD matrix" description "Matrix tab: usecase x resource table with service / infra filters" } usecase BrowseOutline { label "Browse the outline" description "Outline tree of the active view's AST (system / deploy / org); click highlights, double-click drills to the node or switches the deploy block" } usecase OpenFocusCanvas { label "Open the focus canvas" description "One edge, or one node with its neighbours, redrawn over the preview with every label in full from the SVG on screen; Back trail, keyboard and touch operable; hovering a card dims the other edges and offers a Relations pill" } usecase ExportDiagram { label "Export the diagram" description "Download the drill-down SVG, the all-views bundle or a draw.io project, built on demand from the settled source" } usecase OpenReferenceWindow { label "Open the reference window" description "Pop out the language reference (?reference&view=) in its own window so it stays open beside the editor" } usecase RunCommandPalette { label "Run a command from the palette" description "mod+shift+p lists every registered keyboard command; opens even while the editor is focused" } usecase DispatchShortcut { label "Dispatch a keyboard shortcut" description "Serialize a keydown into a chord (mod = Cmd / Ctrl) and run the matching command, skipping text inputs unless the command allows it" } usecase TogglePreviewFocus { label "Toggle preview focus" description "mod+shift+f collapses the editor so the preview fills the width" } usecase SetThemePreference { label "Set the theme" description "light / dark / system persisted under localStorage karasu-theme; the effective theme drives data-theme and the diagram theme" resource WebApp.ThemePref { operations get:read, set:update } } usecase PublishAppSignal { label "Publish an app signal" description "Record what the preview shows (team dependencies) or did (share opened, SVG exported) for a reader outside it such as the first-run tour" } usecase CustomizePreviewToolbar { label "Customize the toolbar for a host" description "PreviewToolbarSlot: a host (gallery viewer, karasu serve, VS Code webview) appends controls, omits share / export / allLayers / docs, or sets the share origin" } usecase ClassifyTopLevelPath { label "Classify a top-level URL segment" description "routes.ts: the reserved first segments (SPA projects, Functions s / render / r / api, static assets / fonts) the bare // guard must decline" } // ─── Entities ─── entity ActiveView { label "Active view" description "The diagram tab: system, deploy, org or matrix" } entity ViewSelection { label "View selection" description "What the preview shows: active tab, drill path, entity / org sub-mode and selected deploy block (reset on file or project switch)" ViewSelection -> ActiveView "tab" ViewSelection -> Modeling.ViewPath "drill path" ViewSelection -> OrgDisplayMode "org mode" ViewSelection -> Language.DeployBlock "selected deploy block" ViewSelection -> NodeHighlight "highlight" } entity OrgDisplayMode { label "Org display mode" description "grid, tree or team dependencies" OrgDisplayMode -> ModelAnalysis.TeamDependencyReport "dependencies mode shows" } entity NodeHighlight { label "Node highlight" description "Highlighted element id plus the SVG attribute it is matched against" NodeHighlight -> Modeling.ModelNode "marks" } entity ViewState { label "Compiled view state" description "Per-view publish of one compile: SVG, warnings, diagnostics, node metadata and path indexes; the last valid SVG is kept on error" ViewState -> Modeling.CompileResult "published from" ViewState -> Rendering.Canvas "shows" ViewState -> ResultFingerprint "deduplicated by" ViewState -> PathIndex "indexes" ViewState -> ViewSelection "compiled for" } entity ResultFingerprint { label "Result fingerprint" description "String over SVG + warnings + diagnostics (+ node metadata) deciding whether to re-publish" } entity ActiveViewData { label "Active view data" description "The active view normalized to one shape for the preview column (svg, warnings, breadcrumbs, callbacks, group-by, facets, diff maps)" ActiveViewData -> ViewState "normalizes" ActiveViewData -> Breadcrumb "crumbs" ActiveViewData -> GroupByAxis "grouping" ActiveViewData -> FacetSelection "overlay" ActiveViewData -> CollapseState "collapse" } entity PathIndex { label "Path index" description "Node id -> view path for system, team and org nodes; current / compiling / failed relative to the open entry" PathIndex -> Modeling.ViewPath "resolves to" } entity Breadcrumb { label "Breadcrumb" description "One crumb of the drill path; navigates to its prefix" Breadcrumb -> Modeling.ViewPath "prefix of" } entity DeepLink { label "Deep link (history hash)" description "#krs--[:][?file=]; same anchor grammar as the static drill-down SVG" DeepLink -> ViewSelection "addresses" DeepLink -> NodeHighlight "highlight suffix" DeepLink -> Rendering.DrillLevel "same anchor as" DeepLink -> Workspace.ProjectFile "open file" DeepLink -> Sharing.ShareTarget "built from" } entity DeepLinkRestoration { label "Deep link restoration" description "Pending view, node and highlight from the arrival hash, applied once the path index is current; ended by any visitor action" DeepLinkRestoration -> DeepLink "restores" DeepLinkRestoration -> PathIndex "waits for" } entity RevealRequest { label "Reveal request" description "Node to keep in view plus a sequence number" RevealRequest -> Modeling.ModelNode "keeps in view" } entity GroupByAxis { label "Group-by axis" description "none, team or boundary" GroupByAxis -> Language.BoundaryBlock "boundary axis" } entity FacetSelection { label "Facet selection" description "Facets highlighted on the overlay" FacetSelection -> Language.FacetDeclaration "selects" FacetSelection -> Rendering.FacetOverlay "drawn as" } entity CollapseState { label "Collapse state" description "Collapsed categories, collapsed team groups and the one service expanded in place" CollapseState -> Rendering.CollapseStub "drawn as" } entity CompareMode { label "Compare mode" description "Compare source plus the swapped flag; swap resets when the source or project changes" CompareMode -> Workspace.CompareSource "compares against" CompareMode -> Modeling.ViewDiff "system diff" CompareMode -> Modeling.DeployViewDiff "deploy diff" CompareMode -> Modeling.OrgViewDiff "org diff" } entity DetailSelection { label "Detail selection" description "The node or edge whose detail panel is open" DetailSelection -> Modeling.NodeMetadata "node detail" DetailSelection -> EdgeDetail "edge detail" } entity EdgeDetail { label "Edge detail" description "One authored edge read back from data-edge-* attributes, or the constituents of an aggregated stub" EdgeDetail -> Modeling.DomainEdgeDetail "aggregated constituents" EdgeDetail -> Modeling.CanonicalId "identified by" } entity EdgeDirectionPick { label "Edge direction pick" description "Context-menu choice of a direction for one canonical edge id and the style file it is written to" EdgeDirectionPick -> Modeling.CanonicalId "for edge" EdgeDirectionPick -> Styling.StyleRule "written as" } entity FocusTarget { label "Focus target" description "An edge (from, to) or a node whose neighbourhood the focus canvas shows" FocusTarget -> Modeling.ModelNode "centred on" } entity FocusTrail { label "Focus trail" description "What the focus canvas has shown, oldest first; Back pops it" FocusTrail -> FocusTarget "visited" } entity FocusDrawing { label "Focus drawing" description "Cards copied from the on-screen SVG plus full-label lanes, laid out with estimateTextWidth" FocusDrawing -> FocusTarget "draws" FocusDrawing -> Rendering.Canvas "copies cards from" } entity CrudMatrixFilter { label "CRUD matrix filter" description "Service and infra kind / store selected in the matrix tab" CrudMatrixFilter -> ModelAnalysis.CrudMatrix "filters" } entity OutlineItem { label "Outline item" description "View-agnostic tree node mapped from the system, deploy or org AST" OutlineItem -> OutlineItem "child of" OutlineItem -> Language.Declaration "mirrors" } entity KeyboardCommand { label "Keyboard command" description "Dot-namespaced id, title, optional chord and text-input policy; a keybinding target and a palette entry (ADR-1411)" } entity ThemePreference { label "Theme preference" description "light, dark or system; resolves to an effective theme" ThemePreference -> Styling.Theme "diagram theme" } entity AppSignal { label "App signal" description "A showing flag or a sequenced event the preview records for outside readers" } entity PreviewToolbarSlot { label "Preview toolbar slot" description "Host-supplied extra controls, omitted actions and share origin" } entity RouteSegment { label "Reserved route segment" description "A first URL segment owned by the SPA, a Pages Function or static assets" } // ─── Domain edges ─── -> Modeling "compile the project, resolve drill paths and container chains, warning severity" -> Rendering "drill-down / all-layers / entity bundles, org tree and team dependency graph, pictograms, facet colours, anchor ids, draw.io export" -> ModelAnalysis "view diff in compare mode, CRUD matrix" -> Language "parse imports and node lines, node-path refs, link URL safety, reference catalog, node detail fields" -> Styling "icon theme for outline icons; edge direction written as a style rule" -> Workspace "read and write project files, compare source and snapshots, select file" -> Editing "AppShell mounts the edit pane and runs the editor hooks; jump to source; @import inject through handleEditorChange" -> Sharing "share dialog, synthesized share payload, share target to hash" -> Localization "UI strings, localized warnings and diagnostics" // moved from Sharing (seam verdict) usecase MountGalleryViewer { label "Mount the gallery viewer" description "viewer.html build served by karasu-nest under a sandbox CSP: read the submission from the embedded JSON