Commit Graph

78 Commits

Author SHA1 Message Date
Tianyi Cui
a9d5a5ba68 Merge branch 'feat/acp-1-max-tokens-turn-end' into feat/acp-2-bridge 2026-06-17 15:20:36 +08:00
Tianyi Cui
977c23d31f Merge remote-tracking branch 'origin/master' into feat/acp-1-max-tokens-turn-end
# Conflicts:
#	AGENTS.md
2026-06-17 15:16:26 +08:00
Tianyi Cui
c870c8fcb1 Merge remote-tracking branch 'origin/split/agent-factory' into split/session-persistence-sqlite 2026-06-17 15:05:30 +08:00
Tianyi Cui
cae1517407 Merge remote-tracking branch 'origin/master' into split/agent-factory 2026-06-17 15:03:51 +08:00
Tianyi Cui
edd6eb28dd Merge pull request #33 from deepseek-ai/split/session-persistence
feat(session-persistence): abstract seam + JSONL backend + wiring (split 3/5)
2026-06-17 15:01:52 +08:00
Tianyi Cui
ffc107aa57 docs: record verify-md-wrap in the doc-sync source-of-truth docs
Adding verify-md-wrap to the shared doc-sync gate left its defining docs
stale (Codex review):
- ADR 0014 described doc-sync as two gates; add a dated amendment for the
  third (verify-md-wrap) and drop the "two checkable classes" wording.
- CI step label/comment said "doc code blocks + event taxonomy"; include
  the markdown wrap check.
2026-06-17 10:50:58 +08:00
Tianyi Cui
dbaef018cc Merge remote-tracking branch 'origin/split/agent-factory' into split/session-persistence-sqlite
# Conflicts:
#	docs/adr/0018-session-persistence.md
2026-06-16 23:53:54 +08:00
Tianyi Cui
d3c9f6ca1e Merge remote-tracking branch 'origin/split/session-persistence' into split/agent-factory 2026-06-16 23:51:16 +08:00
Tianyi Cui
2bae18f811 fix(session): synthesize tool results for interrupted tool calls on crash recovery (review #33)
The loop logs the assistant/message (carrying tool-call blocks) BEFORE running
the tools, so a crash mid-tool leaves durable tool calls with no matching
tool/result. interruptedTurnClosers only added step/end + turn/end, so a resumed
session's deriveMessages() replayed a dangling assistant tool-call — which every
provider rejects as an invalid transcript on the next request.

interruptedTurnClosers now scans the interrupted turn for tool-call blocks
without a matching tool/result and synthesizes an error tool/result for each
(before the step/end), so the rehydrated history is a valid transcript. Adds a
dedicated repair.spec.ts and a shared-contract case proving both backends pair
every orphaned call with a result. Docs (ADR 0018, both persistence READMEs,
load() JSDoc) updated.

Also fixes the echo-agent README session-cleanup path: demo:echo runs from the
repo root, so sessions land in <repo-root>/.sessions/_no-cwd/, not
examples/echo-agent/.sessions/ (review #33).
2026-06-16 23:50:52 +08:00
Tianyi Cui
c2f8af30da Merge branch 'feat/acp-1-max-tokens-turn-end' into feat/acp-2-bridge
# Conflicts:
#	AGENTS.md
#	docs/cookbook/extension-cookbook.md
#	yarn.lock
2026-06-16 23:40:23 +08:00
Tianyi Cui
840dfbab84 Merge remote-tracking branch 'origin/master' into worktree-md-wrap-guard
# Conflicts:
#	AGENTS.md
2026-06-16 23:38:58 +08:00
Tianyi Cui
63425a2b87 refactor: detect md hard-wraps via mdast AST, not regex
Per review feedback (use a real markdown parser with an AST linked to
source positions), rewrite verify-md-wrap to parse each file with
mdast-util-from-markdown (the CommonMark parser behind remark) + the GFM
extension, then flag any `paragraph` node whose source span covers more
than one line.

Why a parser over the hand-rolled line scanner:
- It is a checker, not a formatter — it reports and never rewrites, so
  zero cosmetic churn (no emphasis-marker or table-delimiter
  normalization, which is why Prettier was rejected for this).
- The AST owns every structural exemption (fenced code of any fence
  length, tables, lists, blockquotes, HTML, headings, reference defs),
  fixing both bugs the regex version had: it now catches wrapped
  list-item / blockquote prose (a `paragraph` inside those nodes) and no
  longer false-positives on a longer ```` fence wrapping an inner ```.

Also unwrap two pre-existing hard-wrapped blockquotes (architecture.md,
adding-a-tool.md) that the stricter AST check correctly surfaced.
2026-06-16 23:35:33 +08:00
Tianyi Cui
ddf121320b Merge remote-tracking branch 'origin/split/session-persistence-sqlite' into feat/acp-1-max-tokens-turn-end
# Conflicts:
#	packages/session/src/types.ts
2026-06-16 23:31:14 +08:00
Tianyi Cui
973399e03c Merge pull request #45 from deepseek-ai/worktree-docs+todo-markers
docs(development): document FIXME/TODO/XXX markers
2026-06-16 23:21:37 +08:00
Tianyi Cui
9fb12740c7 Merge remote-tracking branch 'origin/split/agent-factory' into split/session-persistence-sqlite 2026-06-16 23:20:29 +08:00
Tianyi Cui
16e7bbc7c6 Merge remote-tracking branch 'origin/split/session-persistence' into split/agent-factory 2026-06-16 23:19:34 +08:00
Tianyi Cui
16e75c2631 Merge remote-tracking branch 'origin/master' into split/session-persistence 2026-06-16 23:18:06 +08:00
Tianyi Cui
c2dc63f2ea Merge pull request #46 from deepseek-ai/split/turn-enclosure
feat(agent-loop): turn-enclosure invariant + post-turn error model (split 2/5, re-land)
2026-06-16 23:16:13 +08:00
Tianyi Cui
326b026ab3 docs(development): document FIXME/TODO/XXX markers
Define the three issue-urgency tags so contributors can flag a release
blocker, a soon-to-fix item, and a someday-maybe consistently.
2026-06-16 22:45:19 +08:00
Tianyi Cui
f0d9383f49 Merge branch 'split/agent-factory' into split/session-persistence-sqlite
# Conflicts:
#	docs/adr/0018-session-persistence.md
#	docs/architecture.md
2026-06-16 22:32:49 +08:00
Tianyi Cui
8511b9639c Merge branch 'split/session-persistence' into split/agent-factory
# Conflicts:
#	docs/adr/0017-turn-enclosure-invariant.md
#	docs/architecture.md
2026-06-16 22:27:51 +08:00
Tianyi Cui
67447fcdc3 feat: enforce merge-commit policy and markdown wrap convention
- AGENTS.md: require merging PRs with a merge commit (gh pr merge
  --merge), never squash/rebase — the per-PR commit history (review-fix
  and regression-test commits) is intentional record.
- Add scripts/verify-md-wrap.ts: a doc-sync gate that fails on
  hard-wrapped prose paragraphs (one physical line per paragraph), with
  smart exemptions for fenced code, tables, lists, blockquotes, headings,
  HTML comments, hrs, and reference defs. Scope covers README.md,
  docs/**/*.md, packages/*/README.md, plus AGENTS.md / packages/AGENTS.md
  (the files doc-sync did not previously cover). Folded into doc-sync so
  it rides the existing pre-push and CI gates.
- Sync AGENTS.md and docs/development.md doc-sync descriptions and
  command lists to include verify-md-wrap.
2026-06-16 22:14:25 +08:00
Tianyi Cui
efee449cfe feat(session-persistence): preserve interrupted turns on crash; don't truncate (review #33)
A crash can leave a durable log whose final turn never closed. The old
behavior truncated everything after the last turn/end as a "crash tail".
But a single turn can be HUGE in a long-horizon task (many steps, large
tool output), so truncating it silently destroys real, durably-written
work — truncating a turn is wrong.

New crash recovery (ADR 0018): load() PRESERVES the interrupted turn's
events and CLOSES the orphaned turn by durably appending synthetic
boundary events — a step/end if a step was open, then a turn/end carrying
the new merge-extensible TurnEndReason {kind:'interrupted'}. load()
returns the balanced log, so a resumed session is immediately usable. Only
a never-fully-written TORN tail fragment is discarded; corruption in the
committed region is still unloadable.

- dsh-session: TurnEndReason {kind:'interrupted'} + shared
  interruptedTurnClosers() repair helper.
- JSONL backend: scanLog preserves the longest contiguous prefix
  (including a partial final turn); loadCore truncates a torn fragment and
  durably writes the closers, returning the balanced log.
- runPersistenceContract gains a crash-recovery test (both backends + mock).
- Docs: ADR 0018/0017, architecture.md, package READMEs.

Also (review #33): RFC 013 records the "move event vocabulary to Zod"
question (merge-extensible maps → runtime schema registry) + blast radius;
deferred, not done here.
2026-06-16 21:27:50 +08:00
Tianyi Cui
8e6fd91e15 docs: document module-graph gate; unwrap generated prose
Codex review follow-up:
- Update docs/development.md: add verify-module-graph to the pre-push and
  CI gate lists and gen/verify-module-graph to the daily commands, so the
  contributor guide matches the new freshness gate.
- Emit the module-graph.md intro paragraph as a single line (repo Markdown
  convention: one line per paragraph), since regenerating would otherwise
  reintroduce hard wrapping.
2026-06-16 21:21:21 +08:00
Tianyi Cui
b33668ef05 refactor: order module-graph table topologically (low→high level)
Replace the alphabetical package ordering with a Kahn-style topological
sort (alphabetical tiebreak within each layer to stay deterministic), so
the table and graph list leaf interfaces first and dependents last.
2026-06-16 21:11:09 +08:00
Tianyi Cui
4c8c1da8b3 feat: generate module dependency graph with freshness gate
Add scripts/gen-module-graph.ts, which derives the inter-package
dependency graph from each package's @deepseek-ai/dsh-* peerDependencies
and renders docs/module-graph.md (a GitHub-native Mermaid graph plus a
dependency table). Output is deterministic so a regenerate-and-diff
check is stable.

Wire a freshness gate the same way doc-sync is wired (ADR 0007: hooks
and CI run the same package.json scripts): verify-module-graph runs in
pre-push (lefthook) and as a CI step. It fails if the committed file
drifts from what the generator would produce.
2026-06-16 21:00:24 +08:00
Tianyi Cui
fb9636db44 feat(acp): ACP bridge — drive the coding agent from an editor over JSON-RPC stdio
Implements the RFC 010 MVP: a new `@deepseek-ai/dsh-acp` package bridges the
harness agent to the Agent Client Protocol (JSON-RPC 2.0 over newline-delimited
stdio), so Zed and other ACP editors can drive the coding agent — streaming
render, tool-call display, and resumable sessions via `session/load`.

- packages/acp: AgentSideConnection wiring; initialize/newSession/loadSession/
  prompt/cancel; a total TurnEndReason→StopReason codec; settle-once with a
  fallback chain (agent/turn-end → logged turn/end → idle); single-session
  guard; cwd-must-equal-launch-dir validation; load replays from the persisted
  event log (assistant/chunk→agent_message_chunk, tool/call/result→tool_call*).
- agent: add Agent.whenIdle() quiescence signal to the interface; LoopAgent
  implements it (resolves on the first running→idle/disposed transition). The
  bridge awaits it on disposal so teardown reaches quiescence, not just abort.
- examples: extract the shared provider/tool core into examples/base.yml;
  coding-agent nest-includes it; new examples/acp-agent serves the agent over
  ACP with JSONL persistence and no stdout logger (stdout is the protocol).
- Permission gate deferred (TODO(rfc010-permission-gate)): tools run with the
  executor's full authority; only the Agent→sessionId ownership seam is laid
  down. Cancel is best-effort for a not-yet-started queued turn
  (TODO(rfc010-cancel-prestep)). RFC 010 stays `proposed`.
- Docs: package README + Zed snippet; client-driver cookbook section; root and
  packages layout/commands; RFC 010 implementation-status note.

48 bridge tests + whenIdle coverage; 100% per-file coverage; e2e boots the
example as a subprocess and verifies a written file on disk (key-gated, with a
no-key stdout-purity check).
2026-06-16 18:44:31 +08:00
Tianyi Cui
c27b1bba6e Merge branch 'split/agent-factory' into split/session-persistence-sqlite
# Conflicts:
#	yarn.lock
2026-06-16 17:09:39 +08:00
Tianyi Cui
f40dcb5f7b Merge branch 'split/session-persistence' into split/agent-factory
# Conflicts:
#	docs/adr/README.md
#	packages/agent-loop/package.json
#	yarn.lock
2026-06-16 17:04:54 +08:00
Tianyi Cui
96331432b8 Merge branch 'split/turn-enclosure' into split/session-persistence
# Conflicts:
#	docs/adr/README.md
#	packages/agent-loop/package.json
#	yarn.lock
2026-06-16 17:01:36 +08:00
Tianyi Cui
c4fd22f0fa Merge branch 'split/session-meta' into split/turn-enclosure
# Conflicts:
#	docs/adr/README.md
2026-06-16 16:53:37 +08:00
Tianyi Cui
49e74ed8d0 docs: add ADR 0016 for the pnpm migration
Records the why behind the Yarn 4 → pnpm move (PR #39): ecosystem
alignment, strict-linker phantom-dependency safety, build-script
allowlisting, and the package-manager-independent constraints script.
Captures migration-time install benchmarks and notes the gate suite
passes unchanged on pnpm.
2026-06-16 15:55:21 +08:00
07akioni
dabc2ff411 feat: migrate to pnpm 2026-06-16 14:55:37 +08:00
Tianyi Cui
add59a3336 feat(agent-loop): surface max-tokens as a distinct turn-end reason
Add a `max-tokens` variant to `TurnEndReasonMap` and carry the model
finish reason up from `runStep` to `runTurn`, applying the rule "any
max-tokens step in the turn surfaces as max-tokens" (disposed/aborted/
error still take precedence). This lets consumers distinguish a clean
stop from a truncated one — the contract RFC 010's ACP bridge maps to
the `max_tokens` stop reason.

Also add an AGENTS.md rule: write an ADR when (and only when) a PR makes
a durable, contested, surprising decision.
2026-06-16 11:27:19 +08:00
Tianyi Cui
11e166db71 Merge branch 'split/agent-factory' into split/session-persistence-sqlite 2026-06-16 00:44:19 +08:00
Tianyi Cui
d76d02b666 Merge branch 'split/session-persistence' into split/agent-factory
# Conflicts:
#	docs/adr/0016-session-persistence.md
2026-06-16 00:40:10 +08:00
Tianyi Cui
9838fdb626 docs(adr-0016): soften 'typed error' to 'clear error' (review #34)
The resume seam intentionally throws a plain Error (the JSDoc and #34
were aligned to "clear error"). Match the ADR 0016 prose, which still
said "typed error". Docs-only; no behavior change. (Also carries the
#32 finalizer-containment fixes via the forward merge.)
2026-06-16 00:38:55 +08:00
Tianyi Cui
bc670e69f3 Merge branch 'split/agent-factory' into split/session-persistence-sqlite 2026-06-15 22:14:02 +08:00
Tianyi Cui
6455a1600d Merge branch 'split/session-persistence' into split/agent-factory 2026-06-15 22:13:51 +08:00
Tianyi Cui
5f3a1e4d60 Merge branch 'split/turn-enclosure' into split/session-persistence 2026-06-15 22:13:40 +08:00
Tianyi Cui
3cc074ba5c Merge branch 'split/session-meta' into split/turn-enclosure
# Conflicts:
#	packages/agent-loop/tests/review-fixes.spec.ts
2026-06-15 22:13:22 +08:00
Tianyi Cui
247c408e75 Merge pull request #21 from deepseek-ai/fix/agent-loop-step-start-order
fix(agent-loop): append step/start before emitting agent/step-start
2026-06-15 22:08:52 +08:00
Tianyi Cui
9126697d87 feat(session-persistence-sqlite): second backend validating the abstraction
Add a SQLite SessionPersistence backend (node:sqlite), a SECOND
implementation built to prove the abstract seam + the shared
runPersistenceContract suite are genuinely backend-agnostic. Each
SessionEvent maps 1:1 onto an events row (session_id, seq, type, time,
data); append is an INSERT inside a transaction asserting the
contiguous-seq contract; the mutable SessionSummary lives in the
sessions metadata row.

It satisfies the SAME contract semantics as the JSONL backend, expressed
over rows instead of file bytes:
- Lazy materialization: create() records intent in memory; no row until
  the first append (a never-appended session is absent from has()/list()
  via a materialized flag set inside the first append transaction).
- Crash-tail-on-load: load() returns events only through the last
  complete turn/end and deletes the uncommitted tail; a seq gap in the
  committed region makes the session unloadable.
- Transactional append: a mid-batch failure (a UNIQUE seq collision from
  a concurrent writer) rolls back entirely, keeping the cursor truthful.

Like the JSONL backend it is also the write-path plugin (session/event →
buffer → session/flush drain, onCreated seed/adopt/collision handling,
HMR seeding, dispose-to-quiescence). The package runs the shared
runPersistenceContract suite plus SQLite-specific tests (transaction
rollback, crash-tail cut, schema version, HMR adoption).

Docs flip every "SQLite is future/deferred" reference (ADR 0016,
architecture.md, the persistence module doc + README) to "implemented;
the contract holds both backends to identical semantics".
2026-06-15 21:45:21 +08:00
Tianyi Cui
9a4006cb2b feat(agent): create/resume factory seam
Add the agent-creation factory seam on ctx.agents (AgentRegistry):
setFactory/create/resume plus the AgentFactory interface and
CreateAgentOptions/ResumeAgentOptions. AgentLoop implements AgentFactory
and registers itself via ctx.agents.setFactory(this), so plugins
create/resume agents through the interface without depending on the
concrete loop package.

- create({ agentId, sessionId, meta?, agentOptions? }) — programmatic
  create on a caller-supplied session id (e.g. an ACP-generated id).
- resume({ agentId, resumeSessionId, agentOptions? }) — load a persisted
  session via ctx.sessionPersistence (RFC 009) and resume an agent on it;
  the live session id is the resumed id, turn numbering and derived
  history continue from the loaded log. sessionPersistence is NOT
  hard-injected (non-persistent demos still work); resume rejects with a
  typed error when it is absent. assertAgentIdFree runs before any
  session is created (and again after the load await) so a duplicate id
  never leaves an orphaned live session.

Adds the runtime dsh-session-persistence dependency to agent-loop.
2026-06-15 21:12:14 +08:00
Tianyi Cui
df4b7d3d9a feat(session-persistence): abstract seam + JSONL backend + wiring
Add the durable session-persistence capability seam (ADR 0016): an
abstract SessionPersistence service (dsh-session-persistence,
ctx.sessionPersistence) defining create/append/load/list/has/delete/
update over the existing SessionEvent — no parallel persisted type — and
a first implementation (dsh-session-persistence-jsonl): an append-only
JSONL log per session with crash-safe atomic writes, truncation-repair
of a never-committed crash tail, and a read/replay path. SessionMeta
(format version, cwd, lineage) travels out-of-log via session.header.

A shared runPersistenceContract suite holds every backend to the same
append-only / contiguous-seq / lazy-materialization / serializability
semantics.

Config-driven create() now uses a per-run ${id}-session-<uuid> session
id so a fixed name no longer collides with an on-disk log once a durable
backend is loaded; each run is a new session (a demo simplification). The
examples drop their hand-rolled session-jsonl.ts and load the JSONL
backend via cordis.yml; CI smoke-loads it too.

The agent-facing create/resume factory that consumes load() is a
separate seam, deferred to a follow-up; this change stops at the load
primitive and does not reach into the loop.
2026-06-15 21:05:46 +08:00
Tianyi Cui
b0bc0b5792 feat(agent-loop): turn-enclosure invariant + post-turn error model
Every session event now lives inside a turn (between turn/start and its
turn/end). The loop records queued user/message events AFTER turn/start;
an idle agent.inject() wraps its context/message in a one-shot injection
turn. This makes the turn the single durability/replay boundary so a
persistence backend can treat anything after the last turn/end as a
crash tail without dropping legitimate between-turn context.

A failure once the turn is already closed (rejecting session/flush, a
throwing agent/turn-end listener) has no in-turn position for a session
error event, so it is reported via agent/error + logger only; the turn
stays balanced. failTurn appends an error event only while the turn is
open.

The dsh-invariants plugin enforces turn-enclosure via a default case:
every non-boundary event type — including plugin-added merge-extensible
keys — must sit inside an open turn or it throws.

Documented in ADR 0017 + architecture.md.
2026-06-15 20:56:17 +08:00
Tianyi Cui
a1eea4d36e docs: note multi-language Code Mode backends in RFC 012
Clarify that the CodeRuntime seam can host backends differing by
language/runtime, not just trust level — e.g. an AssemblyScript/WASM
backend (naturally sandboxed) and a Python backend over CPython or a
more controllable/embeddable interpreter. Note the execution contract
is language-agnostic while SDK codegen/prompt presentation is per-
language, and add these backends to the deferred follow-up list.
2026-06-15 08:37:45 +08:00
Tianyi Cui
1b7c376aec docs: address second-round PR review on RFC 012 (alternatives, framing)
- Add an Alternatives section comparing Code Mode against the narrower
  result-elision/summarization route over native tool-calling (solves
  context-bloat but not composition/round-trips) and against parallel native
  dispatch (a core-loop change that still lacks composition); states why
  Code Mode is chosen and why the new code-execution surface is the price.
- Fix the Problem-section framing: it said the model "can run independent
  calls concurrently," which contradicted the serialize-by-default decision.
  Reworded to "express fan-out, initially serialized until concurrency-safety
  metadata exists" — early win is composition + fewer round-trips, not parallelism.
2026-06-15 01:46:26 +08:00
Tianyi Cui
6d9934103d docs: address PR review on RFC 012 (concurrency, vm guard, prompt budget)
- Concurrency: change from "may serialize" to mandatory serialize-by-default
  via a per-run dispatch queue in the SDK bindings, with a non-overlap test as
  a hard acceptance criterion (the binding shape otherwise makes Promise.all
  dispatch concurrently before the tool contract has concurrency-safety metadata).
- node:vm guard: make it enforceable, not a README warning — CodeRuntime exposes
  safe:boolean, the VM stub throws unless constructed { unsafe:true }, and
  code-mode refuses to register run_code over an unsafe runtime unless separately
  acknowledged (allowUnsafeRuntime); refusal path is tested.
- Prompt budget: drop the "zero prompt tokens" claim (the SDK .d.ts is injected
  into the system prompt, so types do consume context) and add the explicit
  budget/caching tradeoff — Code Mode's saving is on output/round-trips, not the
  input-side tool description.
2026-06-15 01:39:21 +08:00
Tianyi Cui
1cc6e1caf7 docs: add RFC 012 (optional Code Mode for all tools)
Proposes an optional Code Mode where the model writes a TypeScript program
against a generated SDK wrapping every registered tool, instead of emitting
one native tool-call per step. Implemented Cordis-style as a capability-seam
trio (code-runtime interface / code-runtime-vm node:vm reference stub /
code-mode consumer plugin) with zero core-package changes; the hardened
execution substrate is deferred to a follow-up RFC.
2026-06-15 01:20:09 +08:00