Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

feat(cli): doc history, restore and comment list for agents; refuse stale collab restores (MUL-9915) (#11248)

Bohan Jiangdda36e90d908
diff --git a/apps/collab/src/collab.test.ts b/apps/collab/src/collab.test.ts
index 531bd9060a..1d0df9b6db 100644
--- a/apps/collab/src/collab.test.ts
+++ b/apps/collab/src/collab.test.ts
@@ -315,6 +315,39 @@ describe("collaboration server", () => {
expect(markdown(a.document)).toBe("One\n\nTwo (Ada)");
});
+ it("refuses a restore from a revision someone has since saved over, keeping their text", async () => {
+ resetDoc("Old body");
+ const a = await connect(ada);
+ typeInto(a.document, 0, 8, " (Ada)");
+ await waitFor(() => markdown(a.document).includes("Ada"));
+ // The caller read revision 1; Ada's pending edit is saved as revision 2
+ // before the restore is checked.
+ const stale = await internal("write", {
+ actor: agent,
+ base_revision: 1,
+ content: "Restored body",
+ action: "restore",
+ action_ref: 1,
+ });
+ expect(stale.status).toBe(409);
+ expect(stale.body.error).toBe("revision_conflict");
+ expect(stale.body.revision).toBe(2);
+ expect(stale.body.content).toBe("Old body (Ada)");
+ expect(fake.content).toBe("Old body (Ada)");
+ expect(markdown(a.document)).toBe("Old body (Ada)");
+
+ const fresh = await internal("write", {
+ actor: agent,
+ base_revision: 2,
+ content: "Restored body",
+ action: "restore",
+ action_ref: 1,
+ });
+ expect(fresh.status).toBe(200);
+ await waitFor(() => markdown(a.document) === "Restored body");
+ expect(fake.content).toBe("Restored body");
+ });
+
describe("keeps what Markdown cannot express", () => {
const image = { type: "image", attrs: { src: "https://cdn.example.com/a.png", alt: "a", width: 800, height: 600 } };
const file = { type: "fileCard", attrs: { href: "https://cdn.example.com/f.pdf", filename: "f.pdf", fileSize: 12345 } };
diff --git a/apps/collab/src/documents.ts b/apps/collab/src/documents.ts
index ae35c555a7..42a57001b8 100644
--- a/apps/collab/src/documents.ts
+++ b/apps/collab/src/documents.ts
@@ -60,7 +60,9 @@ interface DocState {
export interface WriteRequest {
actor: Actor;
- /** Stored revision and content the writer based `content` on. */
+ /** Stored revision and content the writer based `content` on. A restore
+ * replaces the whole document, so it is refused unless `base_revision` is
+ * still the stored revision once pending edits are saved. */
base_revision?: number;
base_content?: string;
content?: string;
@@ -81,6 +83,7 @@ export interface EditRequest {
export type WriteResult =
| { status: "ok"; revision: number; content: string; title: string; merged: boolean }
| { status: "conflict"; revision: number; content: string; conflicts: MergeConflict[] }
+ | { status: "stale"; revision: number; content: string }
| { status: "edit_failed"; revision: number; content: string; failure: EditFailure }
| { status: "too_large"; revision: number }
| { status: "gone" };
@@ -212,6 +215,9 @@ export class DocumentStore {
/** Whole-document write: three-way merged into the live document. */
write(name: string, req: WriteRequest): Promise<WriteResult> {
return this.withDocument(name, req.actor, async (document, state) => {
+ if (req.action === "restore" && req.base_revision !== undefined && req.base_revision !== state.revision) {
+ return { status: "stale", revision: state.revision, content: this.codec.ydocToMarkdown(document) };
+ }
let merged = false;
if (req.content !== undefined) {
const current = this.codec.ydocToJSON(document);
diff --git a/apps/collab/src/server.ts b/apps/collab/src/server.ts
index 9fd156a8ca..8483c01d64 100644
--- a/apps/collab/src/server.ts
+++ b/apps/collab/src/server.ts
@@ -141,6 +141,8 @@ function sendResult(response: ServerResponse, result: WriteResult): boolean {
return send(response, 404, { error: "document not found" });
case "conflict":
return send(response, 409, { error: "merge_conflict", ...result });
+ case "stale":
+ return send(response, 409, { error: "revision_conflict", ...result });
case "edit_failed":
return send(response, 409, { error: "edit_failed", ...result });
case "too_large":
diff --git a/server/cmd/multica/cmd_doc.go b/server/cmd/multica/cmd_doc.go
index 3c38a24b02..395b518c81 100644
--- a/server/cmd/multica/cmd_doc.go
+++ b/server/cmd/multica/cmd_doc.go
@@ -29,8 +29,9 @@ var docCmd = &cobra.Command{
"People may be editing a doc while you work on it. For targeted changes prefer " +
"`multica doc edit`: it replaces text you quote and lands wherever that text now is. " +
"`multica doc update` replaces the whole doc and needs --base-revision, the revision you read " +
- "with `multica doc get`; edits made since then are merged in, and the update is refused only " +
- "when you and someone else changed the same paragraph. " +
+ "with `multica doc get`; edits made since then are usually merged in. The update is refused, with nothing " +
+ "written, when you and someone else changed the same paragraph, and also when your revision is too old " +
+ "to merge from or the live-editing service is unavailable. " +
"Pass --message to say what changed and why — it shows in the doc's history.",
}
@@ -95,6 +96,48 @@ var docEditCmd = &cobra.Command{
RunE: runDocEdit,
}
+var docHistoryCmd = &cobra.Command{
+ Use: "history <doc-id>",
+ Short: "List a doc's versions, or show one with --version",
+ Long: "List the saved versions of a doc, newest first: who saved each one, its action " +
+ "(edit or restore) and the change summary. --output json adds the run and issue an agent saved it from.\n\n" +
+ "Pass --version <n> to get that version with its full content (`--output content` prints only the Markdown), " +
+ "for example to compare it with `multica doc get --output content` or to pick one for `multica doc restore`.",
+ Args: exactArgs(1),
+ RunE: runDocHistory,
+}
+
+var docRestoreCmd = &cobra.Command{
+ Use: "restore <doc-id>",
+ Short: "Restore a doc to an earlier version",
+ Long: "Replace a doc's title and content with an earlier version from `multica doc history`.\n\n" +
+ "The restore is saved as a new version, so nothing is lost: the content it replaces stays in the history. " +
+ "It replaces the whole doc, including edits made after the version you restore; " +
+ "to undo one change and keep the rest, use `multica doc edit` instead. " +
+ "--base-revision is the revision from `multica doc get`; when the doc changed after it, " +
+ "live edits included, nothing is restored.",
+ Args: exactArgs(1),
+ RunE: runDocRestore,
+}
+
+var docCommentCmd = &cobra.Command{
+ Use: "comment",
+ Short: "Read the discussion on a doc",
+ Long: "Read the comment threads people left on a doc. Writing in doc discussions " +
+ "(commenting, replying, resolving) is reserved for people, so there are no write commands.",
+}
+
+var docCommentListCmd = &cobra.Command{
+ Use: "list <doc-id>",
+ Short: "List the comment threads on a doc",
+ Long: "List the comment threads on a doc, each root comment followed by its replies. " +
+ "A root comment's QUOTE (anchor_quote in --output json) is the doc text it was left on.\n\n" +
+ "Resolved threads are hidden unless you pass --include-resolved. " +
+ "The table shortens long comments; --output json has the full text.",
+ Args: exactArgs(1),
+ RunE: runDocCommentList,
+}
+
var docFolderCmd = &cobra.Command{
Use: "folder",
Short: "Manage knowledge base doc folders",
@@ -136,8 +179,18 @@ var docFolderMoveCmd = &cobra.Command{
}
func init() {
- docCmd.AddCommand(docListCmd, docSearchCmd, docGetCmd, docCreateCmd, docUpdateCmd, docEditCmd, docMoveCmd, docFolderCmd)
+ docCmd.AddCommand(docListCmd, docSearchCmd, docGetCmd, docCreateCmd, docUpdateCmd, docEditCmd, docMoveCmd,
+ docHistoryCmd, docRestoreCmd, docCommentCmd, docFolderCmd)
docFolderCmd.AddCommand(docFolderListCmd, docFolderCreateCmd, docFolderUpdateCmd, docFolderMoveCmd)
+ docCommentCmd.AddCommand(docCommentListCmd)
+ docHistoryCmd.Flags().Int("version", 0, "Show this version with its content instead of listing versions")
+ docHistoryCmd.Flags().String("output", "", "Output format: table or json for the list (default table); json or content with --version (default json)")
+ docRestoreCmd.Flags().Int("version", 0, "Version number from doc history to restore (required)")
+ docRestoreCmd.Flags().Int64("base-revision", 0, "Revision from doc get (required)")
+ docRestoreCmd.Flags().String("message", "", "Change summary for history")
+ docRestoreCmd.Flags().String("output", "json", "Output format: table or json")
+ docCommentListCmd.Flags().Bool("include-resolved", false, "Include resolved threads")
+ docCommentListCmd.Flags().String("output", "table", "Output format: table or json")
docMoveCmd.Flags().String("folder", "", "Destination folder id, or `root` for the top level (required)")
docMoveCmd.Flags().String("output", "json", "Output format: table or json")
docListCmd.Flags().String("output", "table", "Output format: table or json")
@@ -224,6 +277,11 @@ func docWriteError(action string, base int64, err error) error {
var httpErr *cli.HTTPError
if errors.As(err, &httpErr) && httpErr.StatusCode == http.StatusConflict {
switch {
+ case action == "restore doc" && strings.Contains(httpErr.Body, "revision_conflict"):
+ return fmt.Errorf("%s: the doc changed since revision %d, so nothing was restored. "+
+ "A restore replaces the whole doc, including those newer edits: run `multica doc get` to read them, "+
+ "and retry with the new --base-revision only if the whole doc should still go back to that version (%s)",
+ action, base, httpErr.Body)
case strings.Contains(httpErr.Body, "revision_conflict"):
return fmt.Errorf("%s: the doc changed since revision %d, so nothing was written. "+
"Run `multica doc get` for the latest content and revision, merge your change into it, and retry with the new --base-revision (%s)",
@@ -553,6 +611,174 @@ func runDocEdit(cmd *cobra.Command, args []string) error {
return printDocSummary(doc, output)
}
+func docActor(m map[string]any, typeKey, idKey string) string {
+ if strVal(m, idKey) == "" {
+ return ""
+ }
+ return strVal(m, typeKey) + ":" + truncateID(strVal(m, idKey))
+}
+
+func runDocHistory(cmd *cobra.Command, args []string) error {
+ number, _ := cmd.Flags().GetInt("version")
+ output, _ := cmd.Flags().GetString("output")
+ if cmd.Flags().Changed("version") && number <= 0 {
+ return fmt.Errorf("--version must be a version number from `multica doc history`")
+ }
+ switch {
+ case number > 0 && output != "" && output != "json" && output != "content":
+ return fmt.Errorf("--output must be json or content with --version")
+ case number == 0 && output != "" && output != "table" && output != "json":
+ return fmt.Errorf("--output must be table or json; pass --version to see a version's content")
+ }
+
+ client, err := newAPIClient(cmd)
+ if err != nil {
+ return err
+ }
+ ctx, cancel := cli.APIContext(context.Background())
+ defer cancel()
+
+ id, err := resolveDocRef(ctx, client, args[0], false)
+ if err != nil {
+ return err
+ }
+
+ if number > 0 {
+ var version map[string]any
+ if err := client.GetJSON(ctx, fmt.Sprintf("/api/docs/%s/versions/%d", id, number), &version); err != nil {
+ return fmt.Errorf("get doc version %d: %w", number, err)
+ }
+ if output == "content" {
+ _, err := fmt.Fprint(os.Stdout, strVal(version, "content"))
+ return err
+ }
+ return cli.PrintJSON(os.Stdout, version)
+ }
+
+ var result struct {
+ Versions []map[string]any `json:"versions"`
+ }
+ if err := client.GetJSON(ctx, "/api/docs/"+id+"/versions", &result); err != nil {
+ return fmt.Errorf("list doc versions: %w", err)
+ }
+ if result.Versions == nil {
+ result.Versions = []map[string]any{}
+ }
+ if output == "json" {
+ return cli.PrintJSON(os.Stdout, result.Versions)
+ }
+ rows := make([][]string, 0, len(result.Versions))
+ for _, v := range result.Versions {
+ action := strVal(v, "action")
+ if ref := strVal(v, "action_ref"); action == "restore" && ref != "" {
+ action = "restore of v" + ref
+ }
+ saved := strVal(v, "updated_at")
+ if len(saved) >= 16 {
+ saved = strings.Replace(saved[:16], "T", " ", 1)
+ }
+ rows = append(rows, []string{
+ strVal(v, "number"), saved, docActor(v, "author_type", "author_id"),
+ action, oneLine(strVal(v, "message"), 60),
+ })
+ }
+ cli.PrintTable(os.Stdout, []string{"VERSION", "SAVED", "AUTHOR", "ACTION", "MESSAGE"}, rows)
+ return nil
+}
+
+func runDocRestore(cmd *cobra.Command, args []string) error {
+ number, _ := cmd.Flags().GetInt("version")
+ if number <= 0 {
+ return fmt.Errorf("--version is required: a version number from `multica doc history`")
+ }
+ base, _ := cmd.Flags().GetInt64("base-revision")
+ if base <= 0 {
+ return fmt.Errorf("--base-revision is required: pass the revision from `multica doc get`")
+ }
+ body := map[string]any{"base_revision": base, "action": "restore", "action_ref": number}
+ if v, _ := cmd.Flags().GetString("message"); v != "" {
+ body["message"] = v
+ }
+
+ client, err := newAPIClient(cmd)
+ if err != nil {
+ return err
+ }
+ ctx, cancel := cli.APIContext(context.Background())
+ defer cancel()
+
+ id, err := resolveDocRef(ctx, client, args[0], false)
+ if err != nil {
+ return err
+ }
+ var doc map[string]any
+ if err := client.PatchJSON(ctx, "/api/docs/"+id, body, &doc); err != nil {
+ return docWriteError("restore doc", base, err)
+ }
+ delete(doc, "content")
+ output, _ := cmd.Flags().GetString("output")
+ return printDocSummary(doc, output)
+}
+
+func runDocCommentList(cmd *cobra.Command, args []string) error {
+ client, err := newAPIClient(cmd)
+ if err != nil {
+ return err
+ }
+ ctx, cancel := cli.APIContext(context.Background())
+ defer cancel()
+
+ id, err := resolveDocRef(ctx, client, args[0], false)
+ if err != nil {
+ return err
+ }
+ var result struct {
+ Comments []map[string]any `json:"comments"`
+ }
+ if err := client.GetJSON(ctx, "/api/docs/"+id+"/comments", &result); err != nil {
+ return fmt.Errorf("list doc comments: %w", err)
+ }
+
+ // Group replies under their root, keeping the server's chronological order.
+ includeResolved, _ := cmd.Flags().GetBool("include-resolved")
+ var roots []map[string]any
+ replies := map[string][]map[string]any{}
+ for _, c := range result.Comments {
+ if parent := strVal(c, "parent_id"); parent != "" {
+ replies[parent] = append(replies[parent], c)
+ continue
+ }
+ if includeResolved || strVal(c, "resolved_at") == "" {
+ roots = append(roots, c)
+ }
+ }
+ threads := make([]map[string]any, 0, len(result.Comments))
+ for _, root := range roots {
+ threads = append(threads, root)
+ threads = append(threads, replies[strVal(root, "id")]...)
+ }
+
+ if output, _ := cmd.Flags().GetString("output"); output == "json" {
+ return cli.PrintJSON(os.Stdout, threads)
+ }
+ rows := make([][]string, 0, len(threads))
+ for _, c := range threads {
+ replyTo, status, quote := strVal(c, "parent_id"), "", ""
+ if replyTo == "" {
+ replyTo, status, quote = "-", "open", oneLine(strVal(c, "anchor_quote"), 40)
+ if strVal(c, "resolved_at") != "" {
+ status = "resolved"
+ }
+ }
+ rows = append(rows, []string{
+ strVal(c, "id"), replyTo, docActor(c, "author_type", "author_id"),
+ status, quote, oneLine(strVal(c, "content"), 80),
+ })
+ }
+ cli.PrintTable(os.Stdout, []string{"ID", "REPLY TO", "AUTHOR", "STATUS", "QUOTE", "COMMENT"}, rows)
+ return nil
+}
+
func printDocFolderSummary(folder map[string]any, output string) error {
if output == "table" {
parent := strVal(folder, "parent_id")
diff --git a/server/cmd/multica/cmd_doc_test.go b/server/cmd/multica/cmd_doc_test.go
index c68bec0aee..f7d3464414 100644
--- a/server/cmd/multica/cmd_doc_test.go
+++ b/server/cmd/multica/cmd_doc_test.go
@@ -10,13 +10,16 @@ import (
"strings"
"testing"
+ "github.com/spf13/cobra"
+
"github.com/multica-ai/multica/server/internal/cli"
)
func TestDocCommandsExposeOnlyAgentReadWrite(t *testing.T) {
expected := map[string]bool{
"list": true, "search": true, "get": true, "create": true,
- "edit": true, "update": true, "move": true, "folder": true,
+ "edit": true, "update": true, "move": true, "history": true,
+ "restore": true, "comment": true, "folder": true,
}
for _, command := range docCmd.Commands() {
if !expected[command.Name()] {
@@ -38,6 +41,10 @@ func TestDocCommandsExposeOnlyAgentReadWrite(t *testing.T) {
if len(expectedFolder) != 0 {
t.Fatalf("missing doc folder commands: %v", expectedFolder)
}
+ // Writing in doc discussions is human-only on the server.
+ if names := commandNames(docCommentCmd); len(names) != 1 || names[0] != "list" {
+ t.Fatalf("doc comment commands = %v, want only list", names)
+ }
if !docFolderUpdateCmd.HasAlias("rename") {
t.Fatal("doc folder update should accept rename as an alias")
}
@@ -444,3 +451,201 @@ func TestResolveDocRefMatchesSharedPrefixRules(t *testing.T) {
})
}
}
+
+func commandNames(cmd interface{ Commands() []*cobra.Command }) []string {
+ var names []string
+ for _, c := range cmd.Commands() {
+ names = append(names, c.Name())
+ }
+ return names
+}
+
+func setDocTestServer(t *testing.T, handler http.HandlerFunc) {
+ t.Helper()
+ srv := httptest.NewServer(handler)
+ t.Cleanup(srv.Close)
+ t.Setenv("MULTICA_SERVER_URL", srv.URL)
+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")
+ t.Setenv("MULTICA_TOKEN", "mat_test-token")
+}
+
+// setDocFlag sets a flag on a shared command and restores its default after the test.
+func setDocFlag(t *testing.T, cmd *cobra.Command, name, value string) {
+ t.Helper()
+ f := cmd.Flags().Lookup(name)
+ if err := cmd.Flags().Set(name, value); err != nil {
+ t.Fatalf("set --%s: %v", name, err)
+ }
+ t.Cleanup(func() {
+ _ = cmd.Flags().Set(name, f.DefValue)
+ f.Changed = false
+ })
+}
+
+func TestRunDocHistoryListsVersionsAndShowsOne(t *testing.T) {
+ const docID = "11111111-2222-3333-4444-555555555555"
+ var gotPaths []string
+ setDocTestServer(t, func(w http.ResponseWriter, r *http.Request) {
+ gotPaths = append(gotPaths, r.URL.Path)
+ w.Header().Set("Content-Type", "application/json")
+ switch r.URL.Path {
+ case "/api/docs/" + docID + "/versions":
+ _ = json.NewEncoder(w).Encode(map[string]any{"versions": []any{
+ map[string]any{"number": 3, "action": "restore", "action_ref": 1, "author_type": "agent",
+ "author_id": "aaaaaaaa-0000-0000-0000-000000000000", "message": "roll back", "updated_at": "2026-11-23T04:53:02Z"},
+ map[string]any{"number": 2, "action": "edit", "author_type": "member",
+ "author_id": "bbbbbbbb-0000-0000-0000-000000000000", "message": "", "updated_at": "2026-11-22T10:00:00Z"},
+ }})
+ case "/api/docs/" + docID + "/versions/2":
+ _ = json.NewEncoder(w).Encode(map[string]any{"number": 2, "title": "Runbook", "content": "# Old body\n"})
+ default:
+ http.NotFound(w, r)
+ }
+ })
+
+ out, err := captureStdout(t, func() error { return runDocHistory(docHistoryCmd, []string{docID}) })
+ if err != nil {
+ t.Fatalf("list: %v", err)
+ }
+ for _, want := range []string{"restore of v1", "agent:aaaaaaaa", "roll back", "2026-11-23 04:53", "member:bbbbbbbb"} {
+ if !strings.Contains(out, want) {
+ t.Fatalf("history table missing %q:\n%s", want, out)
+ }
+ }
+
+ setDocFlag(t, docHistoryCmd, "version", "2")
+ setDocFlag(t, docHistoryCmd, "output", "content")
+ out, err = captureStdout(t, func() error { return runDocHistory(docHistoryCmd, []string{docID}) })
+ if err != nil {
+ t.Fatalf("show version: %v", err)
+ }
+ if out != "# Old body\n" {
+ t.Fatalf("--output content = %q", out)
+ }
+ if last := gotPaths[len(gotPaths)-1]; last != "/api/docs/"+docID+"/versions/2" {
+ t.Fatalf("version request path = %s", last)
+ }
+
+ setDocFlag(t, docHistoryCmd, "output", "table")
+ if err := runDocHistory(docHistoryCmd, []string{docID}); err == nil || !strings.Contains(err.Error(), "json or content") {
+ t.Fatalf("table output for one version must be refused: %v", err)
+ }
+}
+
+func TestRunDocRestoreSendsRestoreAction(t *testing.T) {
+ const docID = "11111111-2222-3333-4444-555555555555"
+ var gotMethod, gotPath string
+ var gotBody map[string]any
+ conflict := false
+ setDocTestServer(t, func(w http.ResponseWriter, r *http.Request) {
+ gotMethod, gotPath = r.Method, r.URL.Path
+ _ = json.NewDecoder(r.Body).Decode(&gotBody)
+ w.Header().Set("Content-Type", "application/json")
+ if conflict {
+ w.WriteHeader(http.StatusConflict)
+ _ = json.NewEncoder(w).Encode(map[string]any{"code": "revision_conflict", "actual_revision": 9})
+ return
+ }
+ _ = json.NewEncoder(w).Encode(map[string]any{"id": docID, "title": "Runbook", "revision": 8, "content": "restored"})
+ })
+
+ if err := runDocRestore(docRestoreCmd, []string{docID}); err == nil || !strings.Contains(err.Error(), "--version is required") {
+ t.Fatalf("missing --version must explain itself: %v", err)
+ }
+ setDocFlag(t, docRestoreCmd, "version", "2")
+ if err := runDocRestore(docRestoreCmd, []string{docID}); err == nil || !strings.Contains(err.Error(), "--base-revision is required") {
+ t.Fatalf("missing --base-revision must explain itself: %v", err)
+ }
+ setDocFlag(t, docRestoreCmd, "base-revision", "7")
+ setDocFlag(t, docRestoreCmd, "message", "undo broken rewrite")
+ out, err := captureStdout(t, func() error { return runDocRestore(docRestoreCmd, []string{docID}) })
+ if err != nil {
+ t.Fatalf("restore: %v", err)
+ }
+ if gotMethod != http.MethodPatch || gotPath != "/api/docs/"+docID {
+ t.Fatalf("request = %s %s", gotMethod, gotPath)
+ }
+ if gotBody["action"] != "restore" || gotBody["action_ref"] != float64(2) || gotBody["base_revision"] != float64(7) ||
+ gotBody["message"] != "undo broken rewrite" {
+ t.Fatalf("body = %v", gotBody)
+ }
+ if _, ok := gotBody["content"]; ok {
+ t.Fatalf("restore must not send content: %v", gotBody)
+ }
+ if strings.Contains(out, "restored") {
+ t.Fatalf("restore output should omit the doc body: %s", out)
+ }
+
+ conflict = true
+ err = runDocRestore(docRestoreCmd, []string{docID})
+ if err == nil || !strings.Contains(err.Error(), "nothing was restored") || !strings.Contains(err.Error(), "only if the whole doc should still go back") {
+ t.Fatalf("stale revision must ask to re-read before restoring again: %v", err)
+ }
+ if strings.Contains(err.Error(), "merge your change") {
+ t.Fatalf("a restore has no change to merge: %v", err)
+ }
+}
+
+func TestRunDocCommentListGroupsThreadsAndHidesResolved(t *testing.T) {
+ const docID = "11111111-2222-3333-4444-555555555555"
+ var gotPath string
+ setDocTestServer(t, func(w http.ResponseWriter, r *http.Request) {
+ gotPath = r.URL.Path
+ w.Header().Set("Content-Type", "application/json")
+ // Server order is chronological, so a reply can come after a later root.
+ _ = json.NewEncoder(w).Encode(map[string]any{"comments": []any{
+ map[string]any{"id": "c-open", "author_type": "member", "author_id": "m1", "content": "Cite the source\nhere",
+ "anchor_quote": "growth doubled"},
+ map[string]any{"id": "c-done", "author_type": "member", "author_id": "m1", "content": "typo",
+ "anchor_quote": "teh", "resolved_at": "2026-11-22T00:00:00Z"},
+ map[string]any{"id": "c-reply", "parent_id": "c-open", "author_type": "member", "author_id": "m2", "content": "agreed"},
+ map[string]any{"id": "c-done-reply", "parent_id": "c-done", "author_type": "member", "author_id": "m2", "content": "fixed"},
+ }})
+ })
+
+ setDocFlag(t, docCommentListCmd, "output", "json")
+ out, err := captureStdout(t, func() error { return runDocCommentList(docCommentListCmd, []string{docID}) })
+ if err != nil {
+ t.Fatalf("list: %v", err)
+ }
+ if gotPath != "/api/docs/"+docID+"/comments" {
+ t.Fatalf("request path = %s", gotPath)
+ }
+ var threads []map[string]any
+ if err := json.Unmarshal([]byte(out), &threads); err != nil {
+ t.Fatalf("json output: %v\n%s", err, out)
+ }
+ if ids := commentIDs(threads); strings.Join(ids, ",") != "c-open,c-reply" {
+ t.Fatalf("default list = %v, want the open thread with its reply", ids)
+ }
+
+ setDocFlag(t, docCommentListCmd, "include-resolved", "true")
+ out, err = captureStdout(t, func() error { return runDocCommentList(docCommentListCmd, []string{docID}) })
+ if err != nil {
+ t.Fatalf("list --include-resolved: %v", err)
+ }
+ threads = nil
+ _ = json.Unmarshal([]byte(out), &threads)
+ if ids := commentIDs(threads); strings.Join(ids, ",") != "c-open,c-reply,c-done,c-done-reply" {
+ t.Fatalf("--include-resolved list = %v", ids)
+ }
+
+ setDocFlag(t, docCommentListCmd, "output", "table")
+ out, err = captureStdout(t, func() error { return runDocCommentList(docCommentListCmd, []string{docID}) })
+ if err != nil {
+ t.Fatalf("table: %v", err)
+ }
+ for _, want := range []string{"growth doubled", "Cite the source here", "resolved", "open"} {
+ if !strings.Contains(out, want) {
+ t.Fatalf("table missing %q:\n%s", want, out)
+ }
+ }
+}
+
+func commentIDs(comments []map[string]any) []string {
+ ids := make([]string, 0, len(comments))
+ for _, c := range comments {
+ ids = append(ids, strVal(c, "id"))
+ }
+ return ids
+}
diff --git a/server/internal/collab/client.go b/server/internal/collab/client.go
index c3959e43a9..337aa9915e 100644
--- a/server/internal/collab/client.go
+++ b/server/internal/collab/client.go
@@ -76,8 +76,11 @@ type MergeConflict struct {
// Result statuses.
const (
- StatusOK = "ok"
- StatusConflict = "conflict"
+ StatusOK = "ok"
+ StatusConflict = "conflict"
+ // StatusStale: a restore named a revision that is no longer the stored
+ // one once pending edits are saved. Nothing was written.
+ StatusStale = "stale"
StatusEditFailed = "edit_failed"
StatusGone = "gone"
// StatusTooLarge: the write would make the doc larger than the API stores.
diff --git a/server/internal/daemon/execenv/runtime_config_kind_test.go b/server/internal/daemon/execenv/runtime_config_kind_test.go
index 7dcf928324..e03de6a707 100644
--- a/server/internal/daemon/execenv/runtime_config_kind_test.go
+++ b/server/internal/daemon/execenv/runtime_config_kind_test.go
@@ -84,7 +84,7 @@ func TestBuildMetaSkillContentDocsFollowFlag(t *testing.T) {
for _, enabled := range []bool{false, true} {
out := buildMetaSkillContent("claude", TaskContextForEnv{IssueID: "issue-1", DocsEnabled: enabled})
- for _, line := range []string{"`multica doc list|search|get|create|edit|update|move|folder`", "mention://doc/<doc-id>"} {
+ for _, line := range []string{"`multica doc list|search|get|create|edit|update|move|history|restore|comment|folder`", "mention://doc/<doc-id>"} {
if got := strings.Contains(out, line); got != enabled {
t.Errorf("DocsEnabled=%v: brief contains %q = %v\n---\n%s", enabled, line, got, out)
}
diff --git a/server/internal/daemon/execenv/runtime_config_sections.go b/server/internal/daemon/execenv/runtime_config_sections.go
index 05ace49ba5..6ea0d12f53 100644
--- a/server/internal/daemon/execenv/runtime_config_sections.go
+++ b/server/internal/daemon/execenv/runtime_config_sections.go
@@ -295,7 +295,7 @@ func writeAvailableCommands(b *strings.Builder, ctx TaskContextForEnv) {
b.WriteString("- `multica issue wakeup <create|list|get|update|disable|trigger|delete|runs|events>` — persist an event, condition or time wakeup on this issue, then finish the current run. When the platform can check the fact itself, use one `--until-*` condition so no run starts before it holds; check the rule's `last_error` for missing PR links or snapshots, which are retried automatically. Conditions, PR rules and actor filters: `multica issue wakeup create --help` and the multica-platform issues reference.\n")
b.WriteString("- `multica issue children <id> [--output json]` — list a parent's sub-issues grouped by stage.\n")
if ctx.DocsEnabled {
- b.WriteString("- `multica doc list|search|get|create|edit|update|move|folder` — workspace docs and folders (`doc folder list|create|update|move`); `doc search <query>` matches titles and content; people may be editing a doc live, so change part of it with `doc edit <id> --old <exact text> --new <text>`; `doc update` rewrites the whole doc and needs `--base-revision` from `multica doc get` (details: `multica doc --help`).\n")
+ b.WriteString("- `multica doc list|search|get|create|edit|update|move|history|restore|comment|folder` — workspace docs and folders (`doc folder list|create|update|move`); `doc search <query>` matches titles and content; people may be editing a doc live, so change part of it with `doc edit <id> --old <exact text> --new <text>`; `doc update` rewrites the whole doc and needs `--base-revision` from `multica doc get`; `doc comment list <id>` shows the open review threads on a doc; `doc history` / `doc restore` read and roll back versions (details: `multica doc --help`).\n")
}
b.WriteString("- `multica issue comment add <issue-id> [--content \"...\" | --content-file <path> | --content-stdin] [--parent <comment-id>] [--attachment <path>]` — post a comment. Agent-authored bodies MUST use `--content-file` with a file inside your working directory; full flags: `multica issue comment add --help`.\n")
b.WriteString("- `multica repo checkout <url> [--ref <branch-or-sha>] [--fresh]` — repository checkout on a dedicated branch; re-running it keeps a checkout that has uncommitted or unpushed work, or is already on this task's branch, and only fetches; a clean, fully pushed checkout on another branch starts over on a new branch. `--fresh` discards uncommitted and untracked files for a new branch; commits stay on the old branch, so push any you still need first.\n\n")
@@ -771,7 +771,7 @@ const platformSkillName = "multica-platform"
// description, repeated in the brief's recall hint for agents that never read
// the skill listing. TestPlatformSkillDomainsMatchDescription keeps it equal to
// the description, so a new reference cannot ship without reaching the brief.
-const platformSkillDomains = "issue and PR contracts, sub-issues, batch changes, saved views, comment charts and files, mentions, inbox, agents, squads, autopilots, projects, runtimes, local environments, skill import, themes"
+const platformSkillDomains = "issue and PR contracts, sub-issues, batch changes, saved views, comment charts and files, mentions, inbox, docs, agents, squads, autopilots, projects, runtimes, local environments, skill import, themes"
// subIssueContractsSkill returns how the brief should refer to the skill
// carrying the sub-issue contracts, and whether any such skill is installed.
diff --git a/server/internal/handler/doc_collab.go b/server/internal/handler/doc_collab.go
index 9bfb5bc440..fad02098b4 100644
--- a/server/internal/handler/doc_collab.go
+++ b/server/internal/handler/doc_collab.go
@@ -304,7 +304,9 @@ func (h *Handler) updateDocViaCollab(w http.ResponseWriter, r *http.Request, wsU
}
return true
}
- write.Title, write.Content = &source.Title, &source.Content
+ // The service checks it against the live session, so a restore
+ // never replaces edits the caller had not seen.
+ write.BaseRevision, write.Title, write.Content = req.BaseRevision, &source.Title, &source.Content
case req.Content != nil:
// The content the writer started from is the merge base.
var base string
@@ -339,6 +341,10 @@ func (h *Handler) updateDocViaCollab(w http.ResponseWriter, r *http.Request, wsU
writeError(w, http.StatusInternalServerError, "failed to update doc")
return true
}
+ if result.Status == collab.StatusStale {
+ writeRevisionConflict(w, "doc", doc.ID, req.BaseRevision, result.Revision)
+ return true
+ }
h.writeCollabResult(w, r, wsUUID, doc.ID, result)
return true
}
diff --git a/server/internal/handler/doc_collab_test.go b/server/internal/handler/doc_collab_test.go
index 6534fef8ff..3b350ee4a9 100644
--- a/server/internal/handler/doc_collab_test.go
+++ b/server/internal/handler/doc_collab_test.go
@@ -153,6 +153,30 @@ func TestUpdateDocGoesThroughCollabWithItsMergeBase(t *testing.T) {
testutil.Call(t, testHandler.UpdateDoc, withURLParam(newRequest("PATCH", "/api/docs/"+doc.ID, map[string]any{"base_revision": 9, "content": "x"}), "id", doc.ID)).Want(http.StatusConflict)
}
+func TestRestoreDocThroughCollabRefusesAStaleRevision(t *testing.T) {
+ doc := createDocForTest(t)
+ testutil.Call(t, testHandler.UpdateDoc, withURLParam(newRequest("PATCH", "/api/docs/"+doc.ID, map[string]any{"base_revision": 1, "content": "# First\n\nTheirs"}), "id", doc.ID)).Want(http.StatusOK)
+
+ var got collab.WriteRequest
+ service := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ _ = json.NewDecoder(r.Body).Decode(&got)
+ // Someone's pending edit was saved first, so the live revision is 3.
+ w.WriteHeader(http.StatusConflict)
+ _, _ = w.Write([]byte(`{"error":"revision_conflict","status":"stale","revision":3,"content":"# First\n\nTheirs, live"}`))
+ }))
+ defer service.Close()
+ useCollab(t, service.URL)
+
+ var conflict map[string]any
+ testutil.Call(t, testHandler.UpdateDoc, withURLParam(newRequest("PATCH", "/api/docs/"+doc.ID, map[string]any{"base_revision": 2, "action": "restore", "action_ref": 1}), "id", doc.ID)).Want(http.StatusConflict).JSON(&conflict)
+ if got.Action != "restore" || got.BaseRevision != 2 || got.Content == nil || *got.Content != doc.Content {
+ t.Fatalf("restore must carry the caller's revision and the version's content: %+v", got)
+ }
+ if conflict["code"] != "revision_conflict" || conflict["expected_revision"] != float64(2) || conflict["actual_revision"] != float64(3) {
+ t.Fatalf("unexpected response: %v", conflict)
+ }
+}
+
func TestCollabTicketCarriesTheStateSavedWithTheCurrentRevision(t *testing.T) {
doc := createDocForTest(t)
service := httptest.NewServer(http.NotFoundHandler())
diff --git a/server/internal/service/builtin_skills/multica-platform/SKILL.md b/server/internal/service/builtin_skills/multica-platform/SKILL.md
index ba0e2ec0c3..fc99c732fc 100644
--- a/server/internal/service/builtin_skills/multica-platform/SKILL.md
+++ b/server/internal/service/builtin_skills/multica-platform/SKILL.md
@@ -1,6 +1,6 @@
---
name: multica-platform
-description: "Use for Multica actions the runtime brief does not fully cover: issue and PR contracts, sub-issues, batch changes, saved views, comment charts and files, mentions, inbox, agents, squads, autopilots, projects, runtimes, local environments, skill import, themes. Not for product code you are editing."
+description: "Use for Multica actions the runtime brief does not fully cover: issue and PR contracts, sub-issues, batch changes, saved views, comment charts and files, mentions, inbox, docs, agents, squads, autopilots, projects, runtimes, local environments, skill import, themes. Not for product code you edit."
user-invocable: false
allowed-tools: Bash(multica *), Bash(git *), Bash(gh *)
---
@@ -23,6 +23,7 @@ Read the invariants below, then open the reference(s) your task actually needs
| `references/batch-changes.md` | Changing many issues at once (`issue batch update`, `issue delete <id>... --dry-run`): label and property operations, per-issue results, dry runs |
| `references/sub-issues.md` | Sub-issues: whether to split an issue at all, `todo` vs `backlog` children, serial chains, stages and the parent wakeups they drive |
| `references/mentions.md` | Writing a `mention://` link: which types enqueue a run, which are inert, why one silently did nothing; steering another agent's running turn (`comment add --steer`) |
+| `references/docs.md` | Docs (the workspace knowledge base): reading, searching, editing a doc people may be editing live, folders, review comment threads, version history and restore, which doc actions are human-only |
| `references/agents.md` | Creating, copying or debugging an agent definition: fields, secrets, MCP config, skill binding |
| `references/squads.md` | Squads: leader routing, roster, recording leader activity, why a squad did or did not run |
| `references/autopilots.md` | Autopilots: schedule / webhook / manual triggers, `create_issue` vs `run_only`, why one did not fire |
diff --git a/server/internal/service/builtin_skills/multica-platform/references/docs.md b/server/internal/service/builtin_skills/multica-platform/references/docs.md
new file mode 100644
index 0000000000..cb421f79e7
--- /dev/null
+++ b/server/internal/service/builtin_skills/multica-platform/references/docs.md
@@ -0,0 +1,97 @@
+# Docs
+
+Docs are the workspace knowledge base: Markdown documents in a folder tree,
+edited live by people in the app while you work on them. `multica doc` reads
+and writes the same docs the app shows.
+
+Docs can be turned off for a deployment. Then every `multica doc` command,
+`doc list` included, fails with the generic permission error; `--debug` shows
+the server's `docs_disabled` code. Tell the person Docs are not available here
+instead of retrying.
+
+## Read first
+
+```bash
+multica doc list --output json # every folder and doc
+multica doc search "release runbook" --output json # titles and content
+multica doc get <doc-id> --output json # content plus current revision
+multica doc get <doc-id> --output content # Markdown only
+multica doc comment list <doc-id> # open review threads
+multica doc history <doc-id> # versions, newest first
+multica doc history <doc-id> --version 3 --output content
+```
+
+Doc and folder arguments take a full id or a unique id prefix from
+`doc list`. A doc's `revision` is what writes check against; a `version` is a
+saved snapshot in its history. They are different numbers.
+
+## Write
+
+```bash
+multica doc edit <doc-id> --old "<exact current text>" --new "<replacement>" --message "why"
+multica doc update <doc-id> --content-file ./doc.md --base-revision <revision> --message "why"
+multica doc create --title "Runbook" --folder <folder-id> --content-file ./doc.md
+multica doc move <doc-id> --folder <folder-id|root>
+multica doc folder create --title "Ops" --parent <folder-id|root>
+```
+
+People may be typing in the doc while you write. Prefer `doc edit` for a
+targeted change: it replaces the text you quote wherever it now is, and fails
+only when that text is gone or appears more than once (quote more context, or
+pass `--replace-all`). `doc update` replaces the whole doc and needs the
+`--base-revision` you read with `doc get`. Edits made since then are usually
+merged in, and the update is refused with nothing written when you and someone
+else changed the same paragraph. It is also refused, whatever paragraphs
+changed, when your revision is too old to merge from or the live-editing
+service is unavailable. On any refusal, read the doc again and redo your change
+on top of it; never retry the same body with a newer revision, which would
+erase their work.
+
+Pass `--message` on every `create`, `edit`, `update` and `restore`. It is what
+the doc's history shows next to your name, and your run and issue are recorded
+with it. Moves and folder commands do not take it.
+
+## Review comments
+
+Reviewers leave feedback as comment threads anchored to doc text. Before
+revising a doc someone reviewed, run `multica doc comment list <doc-id>`.
+Resolved threads are hidden unless you pass `--include-resolved`; each root
+comment's `anchor_quote` is the text it was left on, and `--output json` has
+the full comment text.
+
+Writing in doc discussions is reserved for people: commenting, replying,
+resolving and reopening all answer `403` to agent credentials, and the CLI has
+no command for them. Report which threads you addressed in your issue
+comment, so the reviewer can resolve them.
+
+## History and restore
+
+```bash
+multica doc history <doc-id> # who saved what, and why
+multica doc history <doc-id> --version 3 --output content # one version's Markdown
+multica doc restore <doc-id> --version 3 --base-revision <revision> --message "why"
+```
+
+A restore saves the chosen version as a new version, so the content it
+replaces stays in the history. It replaces the whole doc, including every edit
+made after that version, by anyone. To undo one change and keep the rest, use
+`doc edit` instead. Restore only a doc you broke, or when the person asked for
+that version back.
+
+A restore is refused with nothing written when the doc changed after the
+revision you pass, live edits included. Read the doc again and restore only if
+the whole doc should still go back.
+
+## Human-only actions
+
+Deleting a doc or a folder answers `403` to agent credentials, and the CLI has
+no delete command. When something should be deleted, say so in your comment
+and leave it to a person. Do not empty a doc as a substitute.
+
+There is no CLI command to upload an image or file into a doc. Link to where
+the file is delivered instead.
+
+## Linking
+
+`[Doc title](mention://doc/<doc-id>)` is a clickable link with no side effect:
+it notifies no one and starts no run.
diff --git a/server/internal/service/builtin_skills_test.go b/server/internal/service/builtin_skills_test.go
index 4a962ac8e5..9b4b5b4617 100644
--- a/server/internal/service/builtin_skills_test.go
+++ b/server/internal/service/builtin_skills_test.go
@@ -365,6 +365,7 @@ func TestPlatformSkillDescriptionNamesEveryDomain(t *testing.T) {
"references/skill-import.md": "skill import",
"references/themes.md": "theme",
"references/inbox.md": "inbox",
+ "references/docs.md": "docs",
}
skill, ok := findSkill(t, PlatformSkillName)
@@ -441,6 +442,7 @@ func TestPlatformSkillCoversPlatformContracts(t *testing.T) {
"references/skill-import.md",
"references/themes.md",
"references/inbox.md",
+ "references/docs.md",
// Invariants deduplicated out of the eight merged bodies. Each
// was repeated in most of them; the router is now their only
// home, so losing one here loses it everywhere.
@@ -740,6 +742,20 @@ func TestPlatformSkillCoversPlatformContracts(t *testing.T) {
{
// MUL-9549: an agent manages only its triggering owner's inbox,
// cannot delete, and bulk sweeps need explicit confirmation.
+ file: "references/docs.md",
+ want: []string{
+ "`--debug` shows\nthe server's `docs_disabled` code",
+ "Moves and folder commands do not take it",
+ "Prefer `doc edit` for a\ntargeted change",
+ "never retry the same body with a newer revision",
+ "multica doc comment list <doc-id>",
+ "Writing in doc discussions is reserved for people",
+ "multica doc restore <doc-id> --version 3 --base-revision <revision>",
+ "To undo one change and keep the rest, use `doc edit` instead",
+ "Deleting a doc or a folder answers `403`",
+ },
+ },
+ {
file: "references/inbox.md",
want: []string{
"**runtime owner's** inbox",