# Workspace Knowledge Base

> Canonical path: `specs/kb/workspace-knowledge-base.md`
> Status: living product spec
> Scope: Knowledge Base product model, source lifecycle, repository-backed source surfaces, and user-facing information architecture.

## 1. Purpose

Knowledge Base is the workspace product for collecting, browsing, maintaining, and retrieving durable knowledge. A KB is a MeshX product object, not an AGS repository and not a Project wrapper.

MeshX owns:

- KB metadata, source membership, retrieval policy, permissions, freshness, and audit state;
- the relationship between KB resources and repositories;
- source creation and source-specific product semantics;
- retrieval and read authorization.

AGS owns repository primitives:

- repositories, owners, branches, commits, trees, blobs, wiki, issues, pull requests, labels, milestones, releases, and repository-level permissions.

Product UI routes and labels may differ from AGS API paths. Browser paths describe user intent; backend calls may use AGS repository endpoints when that is the correct primitive.

## 2. Core Model

A workspace can contain many KBs. A KB can contain many sources. Sources are the durable units that connect the KB product model to versioned content.

Workspace collection organization uses two distinct concepts:

- every KB belongs to exactly one primary **Group**; collection pages render
  Groups as vertically expanded sections so the workspace library remains
  scannable without entering a section first;
- a KB may have multiple **Tags** from the workspace vocabulary; selecting
  multiple Tags applies an AND filter across Groups.

Groups and Tags are durable workspace-scoped metadata, not browser-only saved
view state. Existing and otherwise unassigned KBs belong to the workspace's
default Group. Deleting a non-default Group moves its KBs to that default
Group; deleting a Tag removes its assignments without deleting any KB. KB
managers may move a KB and change its Tags through keyboard- and touch-accessible
controls. Collection covers, Groups, and Tags use theme-neutral styling and do
not expose taxonomy color controls. Existing taxonomy color fields remain in
the API and storage model for compatibility but do not affect collection
presentation. Collection search matches KB names, descriptions, and Tag names.
The Tag filter keeps its selected-Tag and result summary outside the horizontal
Tag scroller on compact screens and always exposes a one-action reset. Taxonomy
management uses directly editable names: a save action appears only after the
name changes, and Enter saves the valid change. Collection cards use the whole
card as their primary open target while pin, organization, and overflow actions
remain independent controls.

Supported source types:

| API value            | Product label                   | Meaning                                                                                                  |
| -------------------- | ------------------------------- | -------------------------------------------------------------------------------------------------------- |
| `file_repository`    | File repository / 文件库        | A repository-backed source for uploaded files, authored documents, and maintained knowledge files.       |
| `codebase`           | Codebase / 代码仓库             | A repository-backed source for source code and repository-native work state.                             |
| `database_schema`    | Database schema / 数据库 Schema | A configured source whose extracted schema knowledge can be materialized into repository-backed content. |
| `external_connector` | External connector / 外部连接器 | A configured source whose synced external content can be materialized into repository-backed content.    |

Creating a KB creates MeshX KB metadata and creator ownership only. It does not create a repository by default.
New interactive creation uses the recoverable Draft workflow defined in
[`setup-publication-governance.md`](./setup-publication-governance.md). Legacy
or system creation may create an Official KB directly only when its caller owns
the corresponding publication decision.
Every KB is workspace-public. The all-workspace-members role defaults to `view`
and may be raised to `edit` or `manage`, but it cannot be set to `none`. Legacy
empty or `none` defaults are interpreted and migrated as `view`. Explicit KB
grants are still required for elevated per-user roles, explicit per-user denies
remain supported, and agent access remains opt-in through agent KB grants.

KB list, card, sidebar, and detail surfaces do not show public/private labels or
badges because KB visibility is no longer a configurable KB property.

Creating a source ensures the repositories required by that source before the source becomes usable.

## 3. Repository Ownership

KB source repository ownership follows the KB storage scope. The repository
owner segment is always the owning user or workspace identity itself:

```text
personal storage:  <user_id>/<source_slug>     # canonical or mirror
personal storage:  <user_id>/<source_slug>.kb  # insights
workspace storage: <workspace_id>/<source_slug>
workspace storage: <workspace_id>/<source_slug>.kb
```

The `.kb` suffix belongs only to the repository name. It must not be appended
to the AGS owner segment.

A Source display name and its repository slug are different identities.
`knowledge_base_sources.name` is mutable and may be repeated within or across
KBs. The repository slug is the stable bare name stem used by the primary
repository and its paired insights repository; ordinary Source updates never
rename either AGS repository. Repository identity remains authoritative in
`resource_repositories`, not on the Source row.

Rules:

- MeshX ensures the owner before ensuring repositories in that owner.
- A source creates exactly one user-visible repository (`canonical` or `mirror`, never both) plus one `insights` repository.
- Default mode creates `canonical` + `insights`. Mirror mode creates `mirror` + `insights`.
- The user-visible repository (`canonical` or `mirror`) is owned by the
  resolved storage owner, is created private, is browsable by authorized users,
  and participates in slug-conflict detection for that owner. Slug uniqueness
  is scoped to the resolved storage-owner namespace, which may span multiple
  KBs. For a normal derived repository name, MeshX chooses the first available
  stem that leaves both `<stem>` and `<stem>.kb` free in MeshX mappings and AGS;
  a repeated Source display name therefore does not make source creation fail.
  A strict caller-provided
  repository-name override is never silently changed and returns a conflict
  with a suggested available stem instead. Source creation
  does not accept a client-selected public/private repository visibility. When
  the creator needs repository access, MeshX records durable repository access
  intent and reconciles the AGS collaborator materialization from that intent.
- The `insights` repository is system-managed backend storage for generated wiki pages, graph artifacts, and indexed content. It is not user-visible.
- The `wiki` repository role is retired. Generated wiki content lives in the `insights` repository's AGS wiki pages.
- Repository identity is stored in `resource_repositories`; source metadata is stored in `knowledge_base_sources`.
- Repository names are human-readable conventions. MeshX database mappings are the authority.

## 4. Source Lifecycle

Adding a source follows one product shape:

1. The user selects a source type.
2. MeshX validates KB edit permission.
3. MeshX ensures the required AGS owner and repositories.
4. MeshX records source metadata.
5. MeshX records repository mappings.
6. MeshX grants repository access needed for the initiating user to open the source detail surface.
7. Web opens the source detail.

Every repository-backed source has exactly one user-visible repository plus one system-managed `insights` repository. Default-mode sources use the `canonical` repository as the user-visible surface; mirror-mode sources use the `mirror` repository instead — the two modes are mutually exclusive. The `insights` repository holds generated wiki pages, graph artifacts, and indexed content. Mirror-mode credential lookup is scoped to the `mirror` repository because no `canonical` repository exists in that mode. Configured data sources may materialize fetched or generated content into the `insights` repository when the product needs versioned browsing, citations, or publishing.

Repository lifecycle rules:

- MeshX mutates AGS repositories only through AGS APIs. It must not read or write AGS database tables directly for KB source repository lifecycle.
- Source metadata updates do not rename, move, or infer repository identity. Repository identity remains the `resource_repositories` row until an explicit repository lifecycle operation changes it.
- Removing a source first deletes the source's managed AGS repositories (`canonical` or `mirror`, plus `insights`) through the AGS repository API, treating missing repositories as already deleted. Only after those API deletes succeed may MeshX remove source metadata, source mirror metadata, and `resource_repositories` / repository-access mapping rows.
- If any AGS deletion fails, MeshX keeps the source metadata and repository mappings so the delete can be retried.
- If AGS was changed but MeshX cannot persist the follow-up metadata or mapping cleanup, MeshX records the failure in `resource_repository_lifecycle_events` for compensation and operator repair.
- If one or more source repositories were created but source metadata or repository mapping persistence fails, MeshX records a `create_bind` lifecycle failure for the created repository identities.

Mirror source credentials are source settings, not AGS repository access
tokens. Importing an external Git repository may use no credential for public
remotes, a one-time pasted token stored as a source-scoped internal secret for
compatibility, or a saved personal external access token owned by the current
workspace principal. Saved personal tokens are managed from the repository
access token settings entry under a distinct external-import token tab; they
are personal, not workspace-shared or organization-shared.

The import and source settings surfaces must let an editor choose an existing
personal token, paste a temporary token, or paste and save a token for future
mirror imports. Source detail and settings may show a sanitized credential
summary such as token name, owner principal, provider base URL, status, expiry,
last-used time, and linked source count. They must not show token plaintext or
raw sensitive credential refs. A personal token that is linked by one or more
sources cannot be deleted or revoked until those sources are changed to use
another credential or no credential.

MeshX may accelerate credential-free public source mirrors with an
operator-managed shared bare-repository cache. A cache miss never creates a
shared cache implicitly, and credentialed sources always clone from their
configured upstream. Published cache contents are immutable generations: a
refresh completes a new generation in isolation, publishes it under its final
version path, and only then switches the active generation through a uniquely
fenced build attempt and a monotonic registry revision. The previous generation
remains available to source-sync readers while refresh is running or fails, and
retired generations are retained beyond the maximum source-sync execution window
before cleanup. A bounded
generation sweep runs at MeshX startup and periodically thereafter, so retired
and unpublished generations do not depend on a later successful refresh for
reclamation. Refreshing the shared cache does not itself push content into
existing source mirror repositories; each source receives the new generation on
its next manual or scheduled mirror sync.

## 5. Source Detail Surface

Source detail is a repository-backed product surface scoped by a selected KB
source. The KB detail route may expose source-scoped Browse, Documents, and
Dashboard as top-level KB tabs, but the content remains source-backed and must
keep a source selector visible when more than one source is available. In KB
detail, the source selector and source-scoped revision controls belong in the
left source context column of split Browse, Documents, Dashboard, and
Automation surfaces rather than as a separate content toolbar above the
right-hand detail pane.
For source-backed Browse, the left file-tree/source context column may be
collapsed so the selected file preview can use the available width; the surface
must keep an obvious control to restore the column.

The common source tabs are:

- **Browse / 浏览**: browse the source fact layer. For code and files this is the source primary repository tree (`canonical` in default mode, `mirror` in mirror mode). For materialized data sources this is the materialized output.
- **Knowledge / 知识**: browse repository wiki or generated/authored knowledge surfaces.
- **Activity / 活动**: issue-style work for source maintenance.
- **Convergence / 收敛**: pull-request style work when the source supports review and merge workflows.
- **Labels / 标签** and **Milestones / 里程碑**: repository work organization when supported.
- **Published Versions / 发布版本**: releases or published outputs when supported.
- **Settings / 设置**: source and repository settings inside a source detail
  route. The KB detail Settings tab is KB-level and aggregates source settings
  rather than becoming another source selector surface.

The available source-scoped surfaces are selected by source type and repository
capability. Source detail must not invent a separate style or layout for
KB-specific tabs when the same repository primitive already exists.

Generated insights are not a mandatory top-level tab. The source-scoped
Dashboard is the explicit exception: it renders an imported Understand Anything
publication from the selected source's insights repository under the contract in
[`uploaded-ua-dashboard.md`](./uploaded-ua-dashboard.md). Other generated
insights can appear inside Browse, Knowledge, status surfaces, or source health
modules according to product need.

## 6. KB Detail Surface

`/kb/:kbId` opens the KB overview. The KB overview summarizes the KB as a
product object and does not become an aggregate repository tab surface.

The overview should show:

- source list and source management actions;
- direct Browse and Documents shortcuts for each source;
- recently updated documents;
- recent activity and audit-like events;
- recent automation tasks for source repositories.

The Overview tab uses a two-column layout on wide screens. The left column is
wider and contains source management and recently updated documents.
The right rail is narrower and shows recent automation tasks for this KB's source
repositories above the operation records.

Source-backed Browse, Documents, and Automation are reachable from the KB detail
tab row and require a selected source. The source-backed Automation tab reuses
the Automation workspace repository authoring surface for the selected source
repository and also exposes the selected source repository's run history and run
detail view in place; it is not the legacy repository Actions tab. The selected
source, Browse/Documents layer selector, branch selector, commit-history entry,
Automation task/run selector, and source sync action are presented in the left
context column when those controls apply. The KB detail Settings tab is a
KB-level manager page. It is visible only to users with `owner`, `manage`, or
`canManage=true`; `view` and `edit` users must not see Settings tabs or disabled
settings controls, and direct Settings URLs must be replaced by the default
readable KB surface. Settings uses the same single-column settings section
layout as other MeshX resources, includes KB metadata, a source settings section
where multiple sources are listed together and a single source can be expanded
for compact inline editing, and a danger-zone section for destructive lifecycle
actions. Ask and permissions are product actions, not repository tabs.

The KB-level Settings surface includes a manager-only switch for allowing
workspace members with KB access to use server-hosted Knowledge Q&A without
source-repository access. The switch is disabled by default and must explain
that it neither grants direct repository/source access nor overrides an
explicit `none` KB grant.

## 7. Navigation

The Knowledge first-level workspace entry owns KB navigation. In the workspace
rail it appears directly below Explorer and directly above Apps.

Root state:

```text
/kb
/kb?mode=ask
/kb?mode=permissions
/kb?view=all
```

The `view=all` and `view=pinned` collection surfaces retain search, saved views,
pinning, and pagination while presenting each returned page as lightweight book
cover cards on vertically stacked Group shelves. Search text, selected Tags, and
the current page are URL state so that refresh, sharing, and browser history
restore the collection. Saved views appear beside the built-in views in the
same selector; saving switches to the new view, and that view can be reopened or
deleted after a reload.

The unfiltered All collection shows every configured Group, including empty
Groups, and an empty shelf can open creation with that Group preselected. A
shelf count distinguishes items on the current page from the total in
that Group for the active server-side filter, so global pagination must not make
a partial shelf appear complete. Shelves can be collapsed individually or all
at once, and the collapsed state is retained locally per workspace. Cards expose
the KB name, description, source count, activity state, pin state,
and Tags. On compact screens, per-card actions use a labelled overflow menu
rather than unexplained icon-only controls.

KB state:

```text
/kb/:kbId
/kb/:kbId?view=browse&source=:sourceId
/kb/:kbId?view=documents&source=:sourceId
/kb/:kbId?view=dashboard&source=:sourceId
/kb/:kbId?view=automation&source=:sourceId
/kb/:kbId?view=automation&source=:sourceId&automationView=runs
/kb/:kbId?view=automation&source=:sourceId&automationView=run&run=:runId
/kb/:kbId?view=settings
/kb/:kbId?view=settings&source=:sourceId
/kb/:kbId/sources/:sourceId
/kb/:kbId/sources/:sourceId/:tab
```

The KB sidebar keeps workspace-level Ask and Permissions visible. After a KB is
selected, the KB context shows the KB detail tabs in this order for managers:
Overview, Browse, Documents, Dashboard, Automation, and Settings.
Non-managers see only readable tabs; Settings is omitted. Browse, Documents,
Dashboard, and Automation use the selected source and keep source selection in
the left-side source context column inside the tab content. Settings is a
KB-level page; when a `source` query is present it opens that source's inline
settings row instead of showing a source select. Direct Settings URLs for
non-managers replace to the Overview or Browse surface instead of rendering a
read-only Settings page.
Operation records live in the Overview right rail rather than as a top-level KB
detail tab; recent automation run entries in that rail deep-link to the
selected source's Automation run detail view. Existing source-scoped paths
remain addressable deep links for repository browser internals and map back to
the matching KB detail tab.

## 8. Retrieval And Reads

KB retrieval and file reads go through MeshX product APIs.

MeshX must:

- authenticate the principal;
- validate KB grants and source policy;
- resolve eligible sources and repository mappings;
- bind reads and citations to repository revisions where reproducibility matters;
- re-check authorization on every read.

Clients and agents must not infer KB access by directly enumerating AGS repositories. AGS repository readability is necessary for repository content access, but KB grant and source policy remain MeshX product decisions.

The Knowledge Q&A ask surface is composer-first. It summarizes the active
search scope in a readable sentence and reveals a full scope workspace only on
request. The default is the requester's live set of authorized KBs. A user may
narrow one question to one or more Groups, to one or more Tags, or to explicit
KBs. Multiple Groups form a union because each KB has one primary Group;
multiple Tags use AND matching, consistent with the collection filter.

Group and Tag choices are client-side selection rules over the currently
authorized KB list. At submission, the client resolves a narrowed rule to
explicit KB ids, and the server re-authorizes those ids for the request. The
scope workspace shows the live matched KB count and must explain that these
filters never grant access or expand permissions. An empty narrowed result
cannot be applied or submitted. Scope changes remain a draft until the user
applies them; cancelling or dismissing the workspace preserves the previously
applied scope, and browsing between scope types preserves each type's current
selection. A zero-match draft uses warning feedback, explains how to recover,
and the composer provides a direct action to reopen scope adjustment. Tag mode
states its AND behavior, distinguishes the selected Tag count from the final KB
match count, and warns before adding a Tag would reduce the match to zero. The
all-accessible mode continues to use the server's live
authorized-root contract so permission changes apply without stale client
enumeration.

## 9. Durable Boundaries

The KB product must not depend on:

- Project ids, Project repo refs, or Project membership;
- KB-level repository submodules;
- repository names as the only source of truth;
- legacy `/refs` source selection;
- compatibility redirects from old Project routes;
- repository identity on source rows.

The clean model is: KB metadata in KB tables, repository mappings in `resource_repositories`, repository content in AGS, and product permission/retrieval decisions in MeshX.
