# Knowledge Q&A Hosted Sessions（知识问答托管会话）

> Status: product-and-runtime-spec
> Canonical path: `specs/kb/knowledge-qa-runtime-sessions.md`
> Related specs: [Workspace Knowledge Base](./workspace-knowledge-base.md), [KB Permissions](./kb-permissions.md), [KB / KB Source AGS Permission Matrix](./kb-ags-permission-matrix.md), [MaaS Runtime Session Authority](../maas/runtime-session-authority.md), [Scope Message Model](../message/scope-model.md).

## 1. Summary

Knowledge Q&A lets a Human ask questions across the knowledge bases they can
currently read without creating or selecting an Agent or Machine. AgentTeam executes
each turn in its server-hosted runtime, uses the organization's hosted-model
credits, and writes the grounded answer back to a canonical reply thread.

The product has one organization control: enabled or disabled. There is no
platform allow switch, inherited policy, organization model default, or custom
organization model policy. The hosted catalog is the platform capability and
is allowed by default; organization administrators decide whether their funded
organization exposes Knowledge Q&A to members.

## 2. Product Experience

### 2.1 Organization Settings

The organization settings navigation contains one entry named “Knowledge Q&A”.
The page contains:

- one switch that enables or disables new submissions for the organization;
- available hosted credits in the human-facing AgentTeam credit unit, never raw
  credit atoms;
- content-free usage and operational aggregates such as requests, success rate,
  terminal latency, queue state, token usage, and failure categories.

Entering this settings page automatically refreshes the usage overview. A
manual refresh remains available while the administrator stays on the page.

A missing organization policy row means disabled. Reading settings or checking
availability must not materialize a row. Switching the setting persists one
organization-scoped row and an audit record. Disabling prevents new turns and
retries but does not delete or hide existing threads.

There is no platform Knowledge Q&A settings page. Platform operators manage the
general hosted-model inventory and billing system through their owning product
surfaces, not through a second Knowledge Q&A policy hierarchy.

### 2.2 Start A Session

The Knowledge Q&A composer directly exposes:

- every AgentTeam-hosted model returned by current organization availability;
- the reasoning levels that preserve their meaning under each model's
  MaaS-owned Chat Completions compatibility profile;
- the current Human-authorized knowledge scope;
- the question and one primary send action.

Models that are present in the hosted inventory but are not currently executable
remain visible and disabled. A model is executable for Knowledge Q&A only when
the MaaS availability response marks it enabled, inventory-active,
entitlement-eligible, balance-positive, runtime-supported, and capable of
`chat_completions`, `chat_completions.reasoning_effort`, and
`chat_completions.tools`. It must also project a complete, exact supported
`chatCompletionsCompatibilityProfile`. Missing, unknown, conflicting, or
ambiguous profiles fail closed. Every profile-driven parameter that Knowledge
Q&A sends must also have its independent MaaS feature capability; the current
OpenAI profile therefore requires `chat_completions.tool_choice` and
`chat_completions.parallel_tool_calls`, while the DeepSeek V4 thinking profile
requires neither because it omits both parameters. There is no text-action
fallback, so a model without native function tool calling must be disabled
before queue admission.

On first use in a workspace, the first executable model is the initial model
choice and that model's server-projected default is the initial reasoning
level. OpenAI's current profile exposes `low` / `medium` / `high` with
`medium` as default. DeepSeek V4 thinking exposes only `high`, because its
MaaS mapping would otherwise collapse `low` and `medium` to the same upstream
effort and misrepresent those choices. The browser then restores its most
recent model, reasoning level, and narrowed knowledge scope for later visits
to the same workspace. A restored model that is no longer executable falls
back visibly to the first executable model; a restored reasoning level that is
not supported by that model falls back to the model's projected default.
restored knowledge scope remains subject to current authorization and readiness
checks. AgentTeam validates the model/reason pair again on create/retry and does not
treat browser filtering as an authority boundary. It must not accept an
arbitrary model reference that is absent or unavailable in the
organization-scoped hosted inventory.

### 2.3 Follow-ups And Retry

Creating a session freezes the selected model and reasoning level into the
session. Every normal follow-up in that thread uses that same selection. Retrying
a failed, canceled, no-answer, or completed turn with grounding warnings uses
the original selection. A user starts a new Knowledge Q&A session to choose
another model or reasoning level.

Every turn receives the same-session conversation context without requiring
the question to contain a reference keyword. The context contains each prior
terminal question and, for completed turns, its final assistant answer.
No-answer, failed, and canceled turns contribute the question plus the explicit
terminal status; partial output, tool traces, error detail, and prior evidence
are excluded. Before this context becomes model-visible, AgentTeam removes every
server-owned `agentteam-kqa-citation://` destination from the derived summary and
completed-answer tail while preserving its visible evidence marker. Durable
citation routes are presentation state, not dialogue context, and therefore
cannot be copied into a later model answer. The current question is sent
exactly once.

Only the latest terminal turn in a session may be retried. Retry does not create
a conversation branch. Older terminal turns remain canonical history but are
not retryable after a later terminal turn exists.

The thread reuses canonical reply-thread messages, subscription, Inbox, unread,
and citation behavior. One session has one owner and one thread. Turns are
serialized and admitted through the bounded per-user queue plus per-user and
per-organization submission-rate controls. The durable organization backlog
has no arbitrary count ceiling; per-organization running capacity and fair
claiming still bound active work.

### 2.4 Ref-Specific Questions And Source Changes

When the current question explicitly names a branch or Git tag, Knowledge Q&A
may resolve that explicitly typed ref inside an already-authorized primary
Source repository and explore the resolved immutable commit. Annotated and
lightweight tags are both peeled to a commit. Resolution is read-only,
attempt-local, and cannot select revision expressions, remote refs, another
repository, or an ungranted Source.

When the current question also explicitly asks to switch a mirrored Source's
default branch, the answer may carry a non-mutating source-change proposal. The
thread renders the proposed current and target refs and requires a separate
Human confirmation. Confirmation rechecks current KB editor authority and an
optimistic expected-current-ref fence on the server before changing the mirror
configuration, then enqueues the existing mirror sync/index flow. A stale
proposal is blocked and must be regenerated or refreshed; simply reading the
answer never changes Source configuration or an upstream Git repository.

### 2.5 Authenticated Answer Sharing

The owner of a completed Knowledge Q&A turn can create an external share link
for that single answer. The share action is attached to the completed assistant
answer; queued, running, failed, canceled, and no-answer turns cannot be shared.

The link is an invitation to an authenticated AgentTeam account, never a public
answer page. An unauthenticated recipient remains on the normal login surface.
After authentication and workspace selection, AgentTeam redeems the invitation and
opens the shared answer directly. Successful redemption attaches the answer to
that Human account, so later visits use a stable share ID and the answer appears
under the left-sidebar section named “Shared with me” (`来自分享`). The recipient
does not need membership in the source workspace or organization. Direct share
reading and this sidebar projection remain available even when Knowledge Q&A
submission is disabled in the recipient's current organization.

The reader artifact contains only the owner display-name snapshot, question,
formal terminal answer, and share/open timestamps. It excludes the conversation
thread, other turns, activities, debug output, model/reasoning selection, KB and
Source identifiers, repository metadata, evidence bodies, citation records,
credentials, and source-change actions. Before persistence, AgentTeam replaces each
verified repository-linked `[E<positive integer>]` marker with a presentation-
only destination containing that marker number, removes every owner-scoped
`agentteam-kqa-citation://` destination (including code spans and fences), and stores
the marker-to-citation metadata mapping in a share-owned server table. The
browser never receives the owner citation ID.

Clicking a shared marker uses an account-bound endpoint that rechecks the
recipient's current source authorization in MeshX. Direct source authority
returns the exact historical code excerpt in a right sidebar plus a server-
selected repository code route. Without direct source authority, the redeemed
share authorizes only the original bounded evidence excerpt in the existing
restricted-evidence sidebar; it never authorizes repository navigation.

Creating a link returns a new high-entropy invitation token and invalidates the
previous invitation token for that answer. Recipients who already redeemed an
earlier token retain their account-bound share. V1 has no anonymous view,
workspace-local share card, recipient enumeration, per-recipient revocation, or
recipient access to the owner's citation API.

## 3. Authorization And Availability

1. The acting Human is the only session owner and runtime principal.
2. Requested KB and source IDs can only narrow the current Human-authorized
   scope; they cannot widen it.
3. MeshX rechecks current access before reading evidence and before opening a
   citation. A KB manager may enable that KB's narrow
   `allow_knowledge_qa_without_source_access` policy so workspace members with
   a non-`none` KB role can use server-owned Q&A retrieval without receiving
   direct source-repository access. Explicit `none` KB grants still deny.
4. Knowledge Q&A creates no Agent, Machine binding, Agent grant, per-session
   Member, DM, repository credential, or user-visible KB checkout. Server-owned
   exploration reads only the exact authorized commit from AGS's local Git
   object store and never exposes repository storage paths or Git metadata to
   the model. The per-KB policy does not create or change AGS collaborators,
   credentials, repository tokens, or direct repository/source API
   authorization.
5. A submission requires the organization switch, hosted entitlement, positive
   balance, an executable selected model, an available worker, and at least one
   ready authorized root.
6. The worker rechecks the organization switch before execution. MaaS remains
   authoritative for model availability and settlement at execution time.
7. Non-empty data-policy requirement references fail closed until a durable
   data-policy contract is defined.
8. Share creation reauthorizes the exact source workspace, session owner,
   completed turn, and canonical assistant message from server-owned facts. A
   browser cannot supply or replace snapshot content.
9. Invitation redemption, received-share detail, and received-share listing all
   require an authenticated Human and the deployment's ordinary identity-
   verification gate. Redemption grants the scrubbed snapshot and bounded
   share-evidence access to that exact user; it does not create workspace/KB/
   Source membership, repository authorization, owner-citation authority, or
   an Agent grant.

Stable failure categories distinguish organization-disabled, entitlement,
credits, model availability, runtime availability, queue admission, scope, and
terminal execution failures. The UI explains the closest actionable remedy and
does not silently choose another model.

## 4. Durable Model

The server owns these durable facts:

- `organization_knowledge_qa_policy`: sparse organization switch and version;
- `knowledge_qa_policy_audit`: organization switch before/after state and actor;
- `knowledge_qa_sessions`: owner, thread, narrowed knowledge scope, requested
  model, requested reasoning level, state, and timestamps;
- `knowledge_qa_turns`: immutable question identity, copied requested selection,
  effective execution snapshot, current attempt, and terminal state;
- `knowledge_qa_turn_attempts`: retry identity, aggregate usage, the ordered
  distinct provider settlement or synthetic recovery-correlation references
  recorded across hosted-model calls, and failure, plus content-free
  accounting-recovery state for ambiguous runtime transport outcomes;
- `knowledge_qa_runtime_contexts`: one optional per-session derived summary,
  its canonical compacted-through turn, summary format version, and monotonic
  generation;
- `knowledge_qa_shares`: one scrubbed answer snapshot per source turn, the
  SHA-256 hash of the current invitation token, source ownership references,
  and creation/update timestamps. The raw token is never persisted;
- `knowledge_qa_share_citations`: the server-only evidence-number mapping and
  copied immutable citation metadata needed for one bounded live authorization
  check; it contains no evidence body or credential;
- `knowledge_qa_share_recipients`: account-bound successful redemptions with
  first/last-open timestamps and an index for the bounded “Shared with me”
  projection;
- the authorized-root snapshot stored once on its turn, plus citation and
  bounded activity projections.

Deleting the source turn or owner cascades the share; deleting a share cascades
its recipient rows. Token rotation updates only the current token hash and the
snapshot derived from the same immutable completed answer. It does not remove
existing recipient rows.

MeshX separately retains one content-free, requester-bound accounting
checkpoint per active attempt. The checkpoint contains only a monotonically
increasing model-call generation, aggregate usage, ordered settlement
references, running/terminal state, authority IDs, and expiry timestamps. It
must never contain the question, conversation history, model output, tool
arguments/results, evidence, citations, repository identity, or credentials.
Checkpoint reads do not delete or extend it; bounded TTL cleanup is the only
ordinary deletion path.

Generation has no independent count ceiling: it includes exploration,
failed/repair, context-overflow retry, and context-summary calls, including
calls that do not consume the 512-action budget. Every inference producer must
first project returned accounting onto the runtime's closed contract. Usage
contains only the fixed supported token-counter names with non-negative,
integer-valued JSON numbers no greater than the safe-integer boundary
9,007,199,254,740,991 (`2^53 - 1`); MaaS wire values must use an integer JSON
number token. Unknown provider fields are omitted because MaaS remains the
canonical usage-event source. The exact scalar vocabulary is `input_tokens`,
`output_tokens`, `total_tokens`, `prompt_tokens`, `completion_tokens`,
`cached_tokens`, `audio_tokens`, `reasoning_tokens`,
`cache_creation_input_tokens`, `cache_read_input_tokens`,
`prompt_cache_hit_tokens`, and `prompt_cache_miss_tokens`. The only detail
objects are `input_tokens_details`, `output_tokens_details`,
`prompt_tokens_details`, and `completion_tokens_details`; their exact scalar
vocabulary is `cached_tokens`, `audio_tokens`, `reasoning_tokens`,
`accepted_prediction_tokens`, `rejected_prediction_tokens`,
`cache_creation_tokens`, and `cache_read_tokens`. The producer checks numeric
type and range before any floating-point conversion, and additionally checks
the encoded projection against the 65,535-byte usage envelope before it can
leave the boundary. Aggregate merge performs the same safe-integer addition and
encoded-size checks. If a call would overflow an aggregate counter, MeshX keeps
the previous exact aggregate, checkpoints that call's provider reference, and
returns stable MaaS accounting recovery; MaaS retains the canonical usage event.

An invalid recognized counter or a provider settlement reference longer than
255 bytes becomes stable MaaS accounting recovery. Before returning that error,
the producer preserves the valid usage projection and replaces an invalid
reference with a synthetic recovery-correlation reference of the exact form
`kqa_request_sha256_<64 lowercase hexadecimal characters>`. Its suffix is
SHA-256 over the trimmed child idempotency key; the attempt ID plus checkpoint
generation reconstruct that child key and therefore recompute the reference.
The raw invalid provider value never enters accounting lineage or ordinary
non-debug storage. Explicit debug mode may retain it only as part of the already
specified complete raw-response field. MeshX applies this contract both in its
MaaS adapter and at the generic inference boundary.

Settlement lineage then has an explicit storage-safety envelope: at most 4,096
ordered distinct references, each at most 255 bytes, and at most 4 MiB after
JSON encoding. Before every physical model call, MeshX reserves one count slot
and up to 1,533 encoded bytes (the worst-case escaped 255-byte string plus quotes
and a separator; the first entry uses one byte less). If either ceiling would be
crossed, it returns stable resource exhaustion without making that call. The
post-call producer contract guarantees
that a preflighted slot can always hold the returned reference or its recovery
digest, while the closed usage projection remains below the 65,535-byte usage
document limit. A newly returned usage event therefore cannot be stranded by
checkpoint capacity. MeshX validates the same envelope when persisting its
`LONGTEXT`/`TEXT` checkpoint; AgentTeam validates it again before writing the
attempt's native JSON array.

The 1-MiB execute-request envelope otherwise admits fewer than 16,384
normalized history turns even under a conservative 64-byte lower bound; at
most three logical calls per history turn can sit outside the action budget,
plus 524 logical action/repair/recompaction calls. Thus fewer than 49,676
logical calls and, after transient retries, fewer than 298,056 physical calls
are possible, but the lineage envelope is the tighter bound whenever calls
return distinct settlement references. The 4-MiB encoded lineage plus the
65,535-byte usage document remains below 6 MiB even after conservatively
reserving an additional 256 bytes for each of 4,096 native-JSON entries:
960 KiB remains for identifiers, timestamps, fixed columns, and row encoding.
This supports TiDB's default 6-MiB transaction-entry limit without relying on
the nominal 4-GiB `LONGTEXT` length or a non-default TiDB configuration.

The effective turn snapshot records the requested model and reasoning level,
organization policy version, runtime version, prompt version, and authorized
roots. There is no server policy version. Questions, answers, evidence bodies,
and requester identity never appear in policy audit or aggregate metrics.

`knowledge_qa_turns` and canonical assistant messages remain the conversation
facts. Runtime context is derived and rebuildable: AgentTeam stores no second copy
of the uncompacted tail, and MeshX never owns a durable conversation transcript.
AgentTeam reads the summary plus all later terminal turns using a constant-query,
owner/session/current-turn-bound projection. A MeshX summary candidate is
committed by generation compare-and-swap in the same transaction as the
terminal turn and, for completed turns, citations and the assistant message.

## 5. Request Flow

### 5.1 Availability

`GET /api/v1/workspaces/:workspaceId/knowledge-qa/policy` resolves the caller's
organization, reads its switch, and loads organization-scoped MaaS availability.
It returns the availability status, all hosted model options, supported reasoning
levels, each model's supported/default reasoning levels, and the organization
policy version. It does not mutate storage.

### 5.2 Create

1. Web writes the Human-authored root message and creates the canonical thread.
2. Web posts the opaque session ID, thread/message identity, narrowed scope,
   selected model, and reasoning level.
3. Server rechecks organization enablement and validates the selection against
   the current hosted availability response.
4. Server creates the session and initial turn idempotently, then notifies the
   durable worker queue.
5. The worker claims the attempt, rechecks the organization switch, resolves
   current authorized roots, executes the hosted model, settles usage, and
   atomically writes the assistant message with the terminal turn state.

Follow-up creation and retry repeat submission-time availability checks. A
catalog change after admission can still fail at MaaS execution; AgentTeam records a
stable failure instead of substituting another model.

Owner-visible turn progress uses the workspace event stream. Opening a thread
loads one bounded turn projection, and every accepted create, retry, stop,
activity, status, or terminal update publishes a member-local
`knowledge_qa.turn.updated` event for the session owner. The browser refreshes
only that exact turn projection. A terminal event whose transaction also
committed a formal assistant message additionally marks the exact thread message
projection as changed. Stream reconnect refreshes active turn projections; a
bounded non-terminal safety reconciliation may close a state/event commit gap,
but it must stop once the latest turn is terminal.

Every completed answer exposes two answer-specific feedback actions: `helpful`
and `problem`. Helpful feedback is a reversible one-click signal. Problem
feedback opens an explicit form whose bounded reason set and free-text comment
are optional. One reporter owns at most one feedback record per turn; a later
submission replaces that reporter's previous rating, and deleting the feedback
removes the submitted snapshot.

Feedback intake reauthorizes the session owner and loads the completed turn from
server-owned facts. The stored improvement snapshot contains the question,
formal assistant answer, already-projected runtime activities, citation
locations, authorized-root identifiers and revisions, and selected/effective
runtime version metadata. It never accepts those diagnostic fields from the
browser and never includes source bodies, unshown evidence excerpts, other
thread messages, debug model output, raw error detail, usage or settlement
records, credentials, or environment values. The browser discloses this scope
before problem feedback is submitted. Thread history returns only the current
viewer’s rating, reasons, comment, and update time; it does not expose another
member’s feedback or the operator snapshot.

`knowledge_qa_feedback` owns the cross-workspace improvement record and its
immutable-at-submission content snapshot. Problem feedback enters operator
triage as `new`; helpful feedback is retained as a closed signal. Authorized
AgentTeam operators may move problem records through `new`, `triaged`, `fixed`, and
`closed` without writing back into the workspace conversation.

Durable progress has only `queued`, `preparing`, `generating`, and terminal
states. The activity projection contains actual tool or diagnostic records;
AgentTeam does not synthesize searching, reading, thinking, or answer-delta events
that have no runtime producer. The thread UI distinguishes waiting for an
execution slot, preparing model and knowledge access, and model-backed
retrieval/generation from these durable states. Owner history projects only a
fixed allowlist of stable stage names, grounding diagnostic codes, and
non-negative content-free counts from the current attempt's event payload.
Malformed, unknown, or non-allowlisted payload fields fail closed without
making history unavailable. The browser renders recognized stages from that
structured projection in the active locale and uses the existing tool name,
model-call count, and summary only as a rolling-upgrade fallback for legacy or
unknown events.

The primary activity-bubble status and icon always come from the durable turn
status. A grounding warning on a completed turn remains a subordinate activity
and recovery hint; it does not replace the completed primary status. When live
policy disables submission for a recognized credit, entitlement, model, or
runtime reason, the composer blocker keeps both the localized cause and its
localized recovery action visible.

While a turn is running, its activity bubble stays expanded. A successful
completed turn collapses to one line with its available positive search, read,
and source counts; zero-valued counts are omitted. Failed, no-answer, canceled,
and warning-completed turns stay expanded so their recovery and diagnostic
details remain visible. The formal Knowledge Q&A answer uses a left-aligned
full-width message layout with answer-specific typography and starts expanded
when it exceeds the ordinary long-message threshold; an explicit user collapse
remains authoritative. Verified evidence uses compact neutral numbered markers
with border, surface, hover, and focus states rather than link color alone, and
the authenticated shared-answer reader reuses the same answer typography.
Mermaid fences reuse the conversation renderer's built-in `neo` look with the
appearance-aware `neo` or `neo-dark` theme inside a lightly bounded, scrollable
diagram surface. Opening evidence in a Knowledge Q&A topic adds the resizable
conversation right-side column on desktop, shrinking the message surface
instead of covering it; mobile keeps the existing sheet interaction. The topic
header exposes only the latest completed
answer's authenticated share action and the subscription toggle. Ordinary
conversation messages and topic headers keep their existing layout.

The runtime activity structs remain internal facts without HTTP serialization
tags. The owning `internal/api/dto` package defines the browser wire shape, and
the Knowledge Q&A response converter explicitly copies only the activity and
count fields owned by that DTO.

A failed turn shows the closest actionable localized failure category, a
separate recovery action, and an owner-visible diagnostic ID that reuses the
turn ID. The stable content-free error code remains available in the diagnostic
details; attempt identity and raw internal error detail remain server-side.
Operators may explicitly enable
the MeshX model-output debug projection, which is disabled by default. In that
mode only, the latest failed attempt's ordered bounded invalid-response
validator projections are stored together with its last complete raw MaaS
response within the existing 8 MiB response-read boundary. The raw response is
converted to valid UTF-8, and the combined payload is stored once in the turn's
sparse debug-output field. Ordinary error detail retains its 2048-byte bound.
The owner-only turn history loads that field with a separate exact query only
for the latest failed turn and exposes it as `debugModelOutput`; the thread
failure UI displays it verbatim. Successful model responses, assistant messages,
activities, workspace events, accounting checkpoints, organization metrics, and
ordinary turn/history/runtime-context queries never receive this projection.
Operators must treat the debug output as sensitive because the last model output
may contain reasoning, function arguments, or knowledge-derived text.

While an attempt remains `generating`, AgentTeam may read that attempt's exact,
owner-bound accounting checkpoint at most once every ten seconds. It emits a
progress activity only when the monotonically increasing hosted-model generation
crosses one of ten exponential milestones. The activity exposes only the actual
completed model-call count; it contains no prompt, response, tool arguments,
evidence, repository identity, or usage amount. Checkpoint reads do not mutate
accounting or extend checkpoint lifetime, and read or activity-write failures do
not affect execution. This keeps feedback tied to real runtime work while
bounding both checkpoint reads and durable activity growth independently of
knowledge-base size.

### 5.3 Authenticated Answer Sharing

Share creation uses:

`POST /api/v1/workspaces/:workspaceId/knowledge-qa/sessions/:sessionId/turns/:turnId/share`

The workspace-authenticated handler authorizes the caller as session owner,
requires the exact completed turn and canonical assistant message, scrubs
citation destinations, creates or refreshes the snapshot, and rotates the
invitation token. The response is `private, no-store` and returns the external
URL against the configured public deployment base as
`/kb/shared#<token>`. The raw token appears only once, in that URL fragment;
clients must not rebuild the link from a Desktop renderer's local or `app://`
origin. The bearer token therefore does not enter the recipient's initial HTTP
request target, reverse-proxy access logs, or referrer. The fragment is removed
from browser history after redemption.

The recipient flow uses canonical workspace-routed authenticated routes. The
recipient's selected workspace is the transport and session-validation anchor;
it does not grant source-workspace access or replace the account-bound share
authorization checks:

- `POST /api/v1/workspaces/:workspaceId/knowledge-qa/shares/open` hashes the submitted token, loads the
  exact share, upserts the current Human's recipient row, and returns the
  scrubbed reader projection;
- `GET /api/v1/workspaces/:workspaceId/knowledge-qa/shares/:shareId` requires an existing recipient row
  for the current Human and refreshes its last-open timestamp;
- `GET /api/v1/workspaces/:workspaceId/knowledge-qa/shares/:shareId/evidence/:evidenceId` requires the
  exact recipient row and share-owned evidence mapping, asks MeshX to recheck
  current source access, and returns either source-mode code plus a product
  route or the same bounded evidence-only payload used by restricted citations;
- `GET /api/v1/workspaces/:workspaceId/knowledge-qa/shares` returns at most 20 recipient-bound shares,
  ordered by last-open time for the sidebar. Its summary projection excludes
  answer bodies; detail/open are the only reader endpoints that return one
  scrubbed answer.

These routes use ordinary session authentication and the configured identity-
verification gate.
There is no `public`, anonymous, token-only GET, or source-workspace fallback
route. Reader responses are `private, no-store` and omit invitation token,
  source workspace/organization/session/turn IDs, owner user ID, owner citation
  IDs, and all retrieval/runtime metadata. A missing owner display name uses a localized
generic reader label rather than exposing the owner user ID. Invalid, rotated,
malformed, deleted, or unauthorized tokens and share IDs return the same
not-found boundary.

### 5.4 Runtime Context And Compaction

AgentTeam sends the persisted summary and complete uncompacted terminal tail on
every model-backed turn. There is no fixed turn-count or dialogue-byte
truncation. The runtime's separate 2 MiB exploration safety boundary continues
to protect process memory and tool-result growth; it is not a conversation
history selection policy. The boundary measures the serialized model-context
payload, including system/user/assistant/tool messages and the active function
schemas. Compaction applies the same accounting to its prefixed input and
summary-only schema.

MeshX first attempts the selected frozen model with that context. `agentteam-maas`
normalizes a provider-confirmed context-window rejection to
`upstream.context_window.exceeded`. Only that stable error, or the runtime
safety boundary when prior context is present, initiates compaction. MeshX
summarizes the oldest uncompacted terminal prefix with the same model and fixed
`low` reasoning, keeps the newest tail verbatim, and retries with a new child
idempotency key. If no prior context can be compacted, the turn fails with the
stable resource-exhausted category.

Compaction is an explicit, separate inference mode. It exposes only the
`knowledge_context_summary` function with a bounded `{summary}` schema; it never
receives the repository exploration functions. Its native function call is
decoded as the structured summary candidate. It shares accounting with the
attempt but retains its own monotonically distinct child idempotency key.

The summary preserves dialogue referents and terminal outcomes but is never
evidence. Every factual answer must still be grounded in explicit reads from
the current turn's currently authorized roots. Summary calls, rejected calls,
and retried exploration calls share the current attempt's monotonic accounting
checkpoint; all legal usage projections and provider or synthetic recovery
references are recorded on that attempt. A provider rejection without trusted usage releases its MaaS
reservation, while each changed request uses a distinct idempotency key.

Within one unchanged model step, MeshX retries only the stable transient MaaS
categories `upstream.timeout`, `upstream.unavailable`, and
`upstream.rate_limit.exceeded`. It permits at most five additional calls with
bounded exponential backoff capped at eight seconds; turn cancellation or the
execution deadline interrupts that wait immediately. Every physical retry uses
the next monotonic model-call generation and a distinct child idempotency key,
while preserving the same model, mode, prompt, and valid message history.
Returned usage and settlement lineage are normalized at the producer boundary
and checkpointed before any retry wait, so a transient failure never replays the
whole exploration step or loses accounting. If a transient result itself
violates the accounting contract, the bounded projection/recovery digest is
checkpointed and stable MaaS accounting recovery takes precedence; that
physical call is not retried. Other failures remain terminal for that step.
The settlement-lineage storage envelope is preflighted before every initial or
transient physical call; capacity exhaustion therefore cannot create a new
billable call whose usage event has no durable checkpoint slot.

### 5.5 Hosted Repository Exploration

For each attempt, MeshX resolves and authorizes the ready roots once and binds
each opaque root handle to one immutable commit. Initial authorization loads
the request's handles in one authority-scoped batch query; subsequent tool
actions use only the in-memory execution session and do not return to the
database per root or per action. The selected hosted model then drives a
bounded read-only native function-calling agentteam over:

- `knowledge_search`: search file contents in one or more attempt-local root
  aliases, optionally narrowed by path globs;
- `knowledge_list`: list one directory level from an initial root alias or a
  directory reference returned by an earlier list. A request may repeat the
  directory reference's matching root alias, but an unknown reference or an
  alias from a different authorized root is rejected before repository I/O and
  enters the attempt's bounded invalid-response repair path;
- `knowledge_read`: read an explicit line range from a file reference returned
  by search or list;
- `knowledge_ref`: resolve one explicitly typed local branch or tag in an
  already-authorized primary Source root to a new attempt-local root alias
  fixed to the ref's immutable commit. The ref result is navigation, not
  evidence, and does not mutate Source configuration;
- `knowledge_answer`: terminate with a non-empty ordered array of grounded
  Markdown claim strings and, only for an explicit mirrored-Source switch
  request, optionally reference a branch-type root issued by `knowledge_ref` to
  create a confirmable source-change proposal. Tag roots are not eligible;
- `knowledge_no_answer`: terminate without an answer when the authorized
  knowledge does not provide sufficient evidence.

After root authorization and before the first model call, MeshX resolves the
selected model's complete compatibility profile once from capability-scoped
MaaS `/maas/v1/models`. It requires an exact locally supported profile and
freezes a detached copy for the whole attempt, including exploration,
compaction, and context-overflow retries. Missing, unknown, conflicting, or
duplicate model/profile projections fail before generation. Every model call
sends the frozen profile ID in
`X-AgentTeam-Chat-Completions-Compatibility-Profile`; MaaS compares it with the
route-bound profile before reservation and does not forward that header
upstream. If a route change after submission resolves to a profile that would
remap the Human-selected exploration reasoning level, MeshX fails before the
first model request instead of silently changing that selection. Internal
context-summary calls may use the frozen profile's explicit effort mapping.

Every request uses `/maas/v1/chat/completions` with `stream:false`, mapped
`reasoning_effort`, and complete JSON Schemas for its functions. OpenAI-profile
requests also send `store:false`, `n:1`, `parallel_tool_calls:false`,
`tool_choice:"required"`, and `max_completion_tokens` when an explicit output
limit exists. DeepSeek V4 thinking requests omit all four unsupported
parameters and use `max_tokens` for an explicit output limit; omitting
`tool_choice` selects the profile's only supported `auto` mode. Schemas declare
required fields, types and bounds, and reject additional properties. MeshX
still decodes with unknown-field rejection and applies semantic validation;
provider-side schema support is not an authorization or validation boundary.

The model-visible search result remains capped at 50 matches and 32 KiB. A read
returns at most 96 KiB of evidence content. `knowledge_answer` accepts one
non-empty claim-string array without a product-level claim-count or per-claim
length limit. `knowledge_no_answer` accepts only an empty object. The complete
assistant message remains subject to the 256-KiB native protocol envelope, and
the exploration remains subject to the 2-MiB serialized context boundary.
Context summaries accept at most 16,384 characters and 64 KiB. These envelope
limits provide transport and process backpressure rather
than shape the answer: a complex answer is not rejected merely because it is
organized as one long claim or many claims. Before repository I/O, MeshX
reserves the complete conservatively encoded tool-result batch. If that batch
cannot fit but bounded error results can, MeshX skips repository I/O, returns
`batch_too_large` for every call in the response, and lets the model retry with
fewer calls. After execution it charges the exact serialized tool messages.

Every exploration response must contain exactly one choice at index zero with
`finish_reason:"tool_calls"` and between one and 24 assistant
`type:"function"` calls. An attempt may execute at most 512 total function
calls, including `knowledge_answer` and `knowledge_no_answer`. Because every
valid exploration response contains at least one call, the same attempt budget
also bounds the response count; context-overflow recompaction does not reset it.
Call IDs must be non-empty and distinct within the response; each name must be
one of the six functions, and each `arguments` value must be one valid JSON
object satisfying the selected function's schema and MeshX validation.
Multi-call responses may contain only search, list, read, and ref actions;
`knowledge_answer` and `knowledge_no_answer` must each be the sole call in
their response. Context
compaction still requires exactly one `knowledge_context_summary` call. Plain
assistant text, malformed JSON, missing or over-limit calls, duplicate IDs,
mixed terminal calls, unknown functions, bad arguments, or missing, reordered, or
mismatched tool results are never executed or added to conversation history.
Before any repository I/O for a response, MeshX also resolves every supplied
attempt-local root, file, and directory reference against the current execution.
An unknown reference or a root/reference mismatch rejects the complete response,
so no earlier call from the same batch executes. MeshX may make at most five
repair calls with the same frozen model, new child idempotency keys, and unchanged
valid history. Each repair request appends trusted validator feedback to the
system contract. The feedback is a bounded JSON projection containing only a
closed set of server-authored error codes, allowed tool and field names, and
static requirements; it never echoes model-authored argument values, parser
errors, handles, paths, or references. Locally parsed tool-argument and
attempt-local reference failures receive specific feedback, such as
`knowledge_read`'s `read_range_reversed`; invalid transport or assistant
envelopes receive only `response_contract_invalid` because there is no safe,
validated call to diagnose. The rejected response's usage and settlement remain
part of the attempt accounting, but it consumes no exploration action. A sixth
rejected response fails with the stable content-free category for that final
rejection. When the explicit model-output debug projection is enabled, a failed
result contains the ordered bounded validator projections for all rejected
responses together with the last bounded raw response described in section 5.2;
this does not make a rejected response executable or part of model history.
Authenticated MaaS `hosted.request.status` responses with
`settlement_pending` or `reconciliation_pending` are accounting-recovery
signals rather than invalid model responses. MeshX preserves their usage-event
lineage and terminates the attempt without consuming the invalid-response
repair budget or issuing another model call.
There is no legacy model-authored
`{"type":"search"}`/list/read/answer protocol and no silent or dual-protocol
fallback.

After a non-terminal response, MeshX appends the full assistant message
containing `tool_calls`, provider-returned `content`, and, when present, exact
`reasoning_content`. It reserves context for the complete result batch before
repository I/O; an oversized reservation produces ordered `batch_too_large`
tool results instead of terminating the attempt. Otherwise it executes
validated read-only functions sequentially in response order and appends one
`role:"tool"` result per call in that same order, with an exactly matching
`tool_call_id`. DeepSeek V4 thinking requires both string
`content` and string `reasoning_content` on every assistant tool-call response
and exact replay before the ordered tool results. Null/missing content,
missing/non-string reasoning, or plain assistant text enters the same single
structured contract repair path and fails after its five repair calls are
exhausted.
OpenAI-profile responses keep nullable assistant content and optional reasoning.
Context sizing includes replayed reasoning.
Repository content and tool output remain untrusted data even on the native tool
transport. Duplicate valid actions return a bounded tool error inviting
refinement without re-executing the repository operation.

Root handles are execution capabilities. Terminal cleanup revokes only the
exact handle IDs consumed by that execution, because a retry may prepare newer
handles while an older attempt with the same turn ID is still unwinding.

Repository content access uses local Git CLI operations against the exact
commit (`git grep`, `git ls-tree`, and `git show`), plus a narrow local
branch/tag resolver that returns one immutable commit SHA and peels annotated
tags. It does not use AGS HTTP,
GraphQL, public code-search APIs, go-git content traversal, a worktree, or an
unsandboxed shell. Tool arguments are structured and validated; paths must stay
relative to the authorized root, symbolic links and binary reads fail closed,
and the process inherits cancellation, deadlines, output backpressure, and
bounded result sizes. Range reads preserve exact requested line boundaries,
including empty lines.

Search and list results help the model refine its exploration but are not
citable evidence. Search returns at most 50 short matches and at most 32 KiB,
each with an attempt-local file reference, root alias, display path, line, and
optional preview. A broad result is truncated with a refinement hint rather
than returning hundreds of entries. List returns immediate entries with
attempt-local `f*` file and `d*` directory references. Only a successful
explicit range read issues an `E*` evidence ID and returns bounded content plus
its model-needed display path and actual line range. A successful answer may
cite only evidence IDs returned by reads from the current turn. The model may
continue searching, listing, and reading until it has enough evidence or
reaches the runtime's resource boundary; there is no fixed one-pass candidate
set, fixed context window around a match, or single prepacked evidence bundle.

Immutable revisions, durable root handles, repository identity, and citation
metadata remain server-side. Each attempt maps authorized roots to `r1`, `r2`,
and so on, then maps navigation results to attempt-local `f*`/`d*` references.
These references cannot be replayed across attempts. Model-visible roots and
tool results contain only those aliases/references, Source display name and
configured default ref, root classification and freshness, display paths and
line coordinates, entry classification, truncation markers, bounded content,
and current-turn evidence IDs. A derived ref root retains the same Source
authority and repository identity server-side while substituting only its
immutable revision and recording the resolved ref name and kind for citations.

A source-change proposal is accepted only when it references an issued derived
branch-type root for a mirrored Source. AgentTeam stores only the bounded KB ID, Source
ID, expected current ref, and target ref in formal-message metadata. The Web
confirmation uses the existing editor-authorized mirror update and manual-sync
APIs. The update compares the expected current ref under the Source lock so two
answers or browser tabs cannot silently overwrite a newer branch selection.

The final response is an ordered claim-string array from `knowledge_answer`, or
an explicit no-answer result from `knowledge_no_answer`. Claim text may contain
Markdown paragraphs, lists, tables, fenced code, and Mermaid diagrams. The
server renders usable claim text in order whether or not each claim includes an
evidence marker. A marker that references evidence not issued by the current
exploration, or an inconsistent marker association, becomes a bounded,
content-free warning diagnostic in the owner-visible activity projection; it
does not discard the answer, and a warned completed turn remains retryable.
Omitting an evidence marker is accepted without a warning. Only verified
current-exploration evidence becomes an exact-revision citation. A malformed,
empty, or otherwise non-renderable model response still fails because there is
no answer to publish. Opening a stored citation performs a fresh product-
authorization check before reading the historical revision.

The exploration prompt asks the model to answer directly in its first one or
two sentences, avoid forced headings for simple questions, use two to four
descriptive sections or a concise list only when the answer is complex, keep
paragraphs focused, format code identifiers as inline code, avoid repetition,
and remain concise unless the user requests detail. These are presentation
guidelines, not claim-count or claim-length limits. Evidence markers must follow
the assertions they support. A claim containing only exact evidence markers is
rejected before terminalization and enters the same bounded structured repair
path as other invalid `knowledge_answer` arguments.

Evidence markers use the exact syntax `[E<positive decimal>]`, such as `[E1]`.
`knowledge_answer` accepts only an ordered claim-string array and does not
accept claim objects or a redundant model-authored `evidenceIds` array. MeshX
derives each claim's ordered, deduplicated evidence IDs from any exact markers
that it contains, checks them against evidence issued by explicit reads in the
current exploration, and returns the existing ordered `GroundedClaim` plus
attempt-local evidence-ID/citation-metadata associations to AgentTeam. Inconsistent
associations and markers that target unavailable evidence remain content-free
grounding warnings. A claim without a marker does not trigger a grounding
warning. MeshX does not flatten the association into answer text and does not
construct AgentTeam routes or URLs.

AgentTeam deduplicates exact citation metadata, allocates stable `kqc_*` IDs before
rendering the assistant message, and maps each verified attempt-local evidence
ID to its stable citation. A verified marker is rendered as a Markdown link
whose href is `agentteam-kqa-citation://<session-id>/<citation-id>`. If a usable
outer `GroundedClaim` ever omits a marker that is present in its verified,
server-derived `evidenceIds`, AgentTeam defensively adds the corresponding linked
marker after the claim so verified evidence remains reachable. Unsupported
markers remain visible but inert. Model-authored citation destinations are
never authoritative: AgentTeam removes every model-authored
`agentteam-kqa-citation://` destination, discards any Markdown destination already
attached to an exact evidence marker, and then links only verified markers to
the server-allocated destination. Evidence-like text inside code spans or
fenced code blocks stays literal. Replacing citations, appending the linked
assistant message, and completing the current attempt are one transaction;
stop or retry cannot expose citations or a message from a losing attempt.
Before linking, AgentTeam defensively folds a citation-only claim into the preceding
semantic claim when an older runtime returns one, and after linking removes
only exact adjacent repeats of the same verified citation. Markdown lists,
tables, inline code, fenced code, and Mermaid blocks remain structurally intact;
evidence-like text inside code is never normalized as a citation.

The href is an opaque reference, not a knowledge-base route and not a carrier
for repository metadata. The browser accepts only the exact protocol and valid
session/citation ID shape, then calls the owner-scoped citation endpoint. The
endpoint resolves only a citation belonging to the session's current completed
attempt, rechecks current product authorization in MeshX, verifies that the
historical revision remains readable, and selects one of two server-authorized
open modes:

- `source`: independent current source-repository authority exists. AgentTeam
  returns the exact historical excerpt and a server-selected product route.
  The browser first shows the excerpt in the right sidebar and offers the route
  as an explicit source-repository action. Primary evidence targets the source
  file at the immutable revision and line. When the citation was read from a
  named branch or tag, AgentTeam also carries the bounded ref name and kind as
  display metadata; the code browser shows `Branch: <name>` or `Tag: <name>`
  while all content reads continue to use the immutable SHA. Existing citations
  without that metadata fall back to displaying the SHA. Insights evidence
  targets the generated source wiki page. Lexicon evidence targets the owning
  knowledge-base workbench because lexicon roots have no source page.
- `evidence`: current product policy permits hosted retrieval but the requester
  has no independent, currently materialized source-repository authority. This
  includes the KB manager's `allow_knowledge_qa_without_source_access` switch
  and inherited hosted-read policy that does not bulk-materialize AGS grants.
  MeshX rereads only the retained citation's exact path, immutable revision, and
  line range, capped to the original hosted read envelope of 1,000 lines and 96
  KiB. AgentTeam returns that bounded excerpt and display-only path/revision/range
  metadata, never a product route. The browser shows it in a closed evidence
  preview with no repository identity, credential, tree, full-file, raw,
  download, history, or expand action.

Direct source authority takes precedence when both modes are available. Neither
mode falls forward to a newer revision. `forbidden`, `source_deleted`,
`revision_unavailable`, and `target_unavailable` remain explicit non-navigation
results that the browser shows to the user.

### 5.6 Cancellation And Accounting Recovery

AgentTeam enters the durable `generating` state immediately before model dispatch,
after history resolution and capability issuance have succeeded. Therefore an
expired pre-dispatch attempt cannot be mistaken for ambiguous model usage.
AgentTeam's worker, its outbound MeshX request, and MeshX's request fallback enforce
the same 20-minute per-turn execution deadline so no transport layer expires a
valid turn early. The attempt-scoped MaaS capability and prepared root handles
derive their expiry from that deadline with one bounded minute of clock and
request-transit margin, so neither credential shortens the execution window.

After each hosted-model call returns, MeshX durably advances the attempt's full
accounting aggregate before it executes another repository action or model
call. Equal generations must be exact idempotent replays; later generations
cannot reduce usage or remove/reorder settlement references. MeshX marks the
checkpoint terminal on every ordinary runtime exit using a short detached
accounting-only context so request cancellation immediately stops inference and
repository work.
If a post-call checkpoint write fails, MeshX preserves the returned usage and
settlement lineage and fails with the stable
`knowledge_qa.maas_accounting_recovery` category rather than an inference
category. Every checkpoint write failure, including a detached terminal-marker
failure, logs the underlying persistence error with only the content-free turn,
attempt, generation, and state identifiers.
Attempt usage and settlement lineage are stored as native JSON object and array
documents, never TiDB opaque BLOB scalars. Accounting recovery narrowly accepts
legacy opaque string/BLOB envelopes at this storage seam, validates the decoded
JSON shape, and rewrites the merged result as native JSON. Both the ordinary
completion path and accounting recovery enforce the 65,535-byte usage, 4,096-ref,
255-byte-per-ref, and 4-MiB encoded-lineage storage envelope before writing the
affected attempt row.

If AgentTeam loses the runtime response after dispatch, or cannot persist the
returned settled aggregate before its terminal fallback, it commits the
user-visible terminal turn first and atomically marks that exact attempt for
accounting recovery. A background worker reads the checkpoint through an
internal endpoint bound to the original organization, workspace, requester,
turn, and attempt, then merges only usage and settlement lineage without
reopening or otherwise changing the terminal turn. It does not replay model
execution. The same indexed recovery path handles server restarts and the
terminal-write/recovery crash window. A running checkpoint may be accepted only
after the execution deadline plus a quiescence grace; missing checkpoints retry
with bounded backoff until the recovery window expires.

## 6. Scale, Privacy, And Observability

- Organization policy reads are bounded to one organization row. Missing rows
  do not cause writes.
- Availability performs one organization-scoped MaaS request per explicit page
  load or submission validation; it does not fan out by organization or model.
- Organization usage overview refreshes in a separate organization-scoped
  request whenever an administrator enters its settings page, and reads only
  the indexed trailing 30-day window.
- Queue scans remain bounded and fair across organizations.
- Turn preparation and execution authorization perform storage work proportional
  to the explicitly authorized root count. Search matches and model-directed
  list/read calls do not trigger product-database or root-handle N+1 reads.
- Runtime-context reads authorize one explicit session and use a constant
  number of queries regardless of tail length. They never fan out across
  sessions and never write on read.
- The exploration agentteam has bounded model steps, message/result bytes, path and
  range validation, process cancellation, and per-command output backpressure.
- Accounting persistence performs at most one checkpoint upsert per bounded
  model step. Ambiguous attempts create no extra content rows: AgentTeam scans only
  indexed due recovery state in bounded batches, performs one owner-bound
  checkpoint read per selected item, and updates only that exact attempt.
- Metrics labels must not contain user, organization, workspace, thread, turn,
  KB, source, model prompt, question, answer, or citation text.
- Logs and activity projections may contain stable IDs, bounded public runtime
  status, and stable grounding-warning codes, but never credentials, raw
  chain-of-thought, evidence body, or answer text in a diagnostic event.
- Share invitation tokens carry 256 bits of randomness, are persisted only as
  fixed-size hashes, travel in URL fragments before authenticated redemption,
  and never appear in reader/list responses. Received-share list/detail queries
  are bounded directly by recipient user ID and never fan out through source
  workspaces, KBs, Sources, citations, or repositories. One evidence open does
  one exact recipient/share/evidence lookup and one bounded MeshX citation read;
  it cannot enumerate source or citation metadata.

## 7. Validation

Required regressions cover:

- missing policy defaults to disabled without materialization;
- organization admins can toggle only their organization;
- ordinary members receive all hosted models and fixed reasoning options;
- unavailable models remain visible but cannot be submitted;
- create, follow-up, retry, and worker execution preserve the session selection;
- owner activity history exposes only recognized stages, grounding diagnostics,
  and non-negative allowlisted counts from the current attempt while legacy,
  malformed, unknown, and sensitive payload fields remain on the safe fallback
  path;
- recognized activities render from localized structured data, and failed turns
  expose the turn ID for support correlation without exposing attempt identity;
- ordinary questions receive prior same-session context without keyword
  detection; terminal status projection excludes partial/error/tool content;
  only the latest terminal turn is retryable;
- context overflow normalization, low-reasoning summary generation, distinct
  child idempotency keys, accounting aggregation, generation-CAS persistence,
  separate summary-only function schema, summary non-evidence treatment, and
  canonical-tail rebuild;
- organization disable, insufficient credits, missing entitlement, unavailable
  runtime/model, empty scope, per-user queue limits, submission-rate controls,
  cancellation, and idempotent replay;
- cancellation after one or more settled calls, terminal-first recovery,
  process-crash recovery from a quiescent checkpoint, owner isolation,
  monotonic checkpoint generations beyond 64, settlement lineages beyond 64
  references and 16 KiB, exact storage-envelope boundaries, pre-call capacity
  rejection without inference, checkpoint-write failure classification and
  cause logging, bounded retry/expiry, and TTL cleanup;
- iterative search refinement, tree listing, explicit range reads, exact commit
  binding, authorization isolation, constant root-authorization query shape,
  process/resource cancellation, non-blocking grounding diagnostics, verified
  citation filtering, exact single/multiple marker handling across multiple
  claims, citation deduplication, CJK punctuation preservation, warning-
  completed retry/current-attempt isolation, primary/insights/lexicon target
  projection, unavailable citation states, and browser click-through
  navigation;
- exact non-stream Chat Completions fields and all function schemas; full
  assistant/content/reasoning/tool message round trips; exact OpenAI and
  DeepSeek payload shapes; profile resolution once across exploration,
  compaction and retry; rejection of missing/unknown/conflicting profiles,
  DeepSeek null content or missing reasoning, plain text, malformed,
  missing, over-limit, duplicate-ID, mixed-terminal, unknown, mismatched, legacy,
  and invalid-argument calls; bounded ordered multi-call exploration batches;
  attempt-local root/file/directory references; the 50-match/32-KiB search
  boundary and refinement hint; duplicate-action handling; answer/no-answer
  terminal calls and exact marker-derived evidence IDs;
- hosted-model executability requires `chat_completions.tools`, reasoning
  effort, every independently admitted feature that its profile-driven request
  will send, and a complete exact supported compatibility profile in addition
  to Chat Completions; mixed-version MaaS responses without the profile remain
  non-executable;
- no Agent/Machine selection or platform Knowledge Q&A settings route remains;
- only completed-turn owners can rotate share links; anonymous requests cannot
  read a share; malformed/rotated tokens fail closed; redemption is account
  bound; another user cannot load that stable share ID; list ordering and limits
  are recipient scoped; source/owner deletion cascades; every shared reader
  snapshot is owner-citation-destination- and authority-metadata-free; shared
  evidence requires the exact recipient mapping; direct source permission opens
  the code sidebar and route; missing source permission opens only bounded
  restricted evidence;
- login/workspace selection preserves the fragment invitation, successful
  redemption replaces it with the stable detail path, and received answers
  render directly and appear in the localized `来自分享` / “Shared with me”
  sidebar even when the recipient workspace cannot submit Knowledge Q&A;
- schema/bootstrap parity and content-free policy audit/usage projections.
