@dreamlake/dreamlake-cli 0.97.2 → 0.98.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/dist/api/client.d.ts +1 -1
  2. package/dist/api/client.js +4 -4
  3. package/dist/api/http.d.ts +48 -1
  4. package/dist/api/http.js +111 -4
  5. package/dist/api/index.d.ts +17 -513
  6. package/dist/api/index.js +6 -2
  7. package/dist/api/note-edits.d.ts +40 -2
  8. package/dist/api/note-edits.js +197 -2
  9. package/dist/api/note-events.d.ts +40 -4
  10. package/dist/api/note-events.js +55 -2
  11. package/dist/api/note-facade.d.ts +268 -0
  12. package/dist/api/note-facade.js +376 -0
  13. package/dist/api/note-reading.d.ts +27 -0
  14. package/dist/api/note-reading.js +27 -0
  15. package/dist/api/note-write.d.ts +110 -0
  16. package/dist/api/note-write.js +217 -0
  17. package/dist/api/notes.d.ts +33 -44
  18. package/dist/api/notes.js +44 -34
  19. package/dist/api/sessions.d.ts +5 -5
  20. package/dist/cli/client.d.ts +2 -41
  21. package/dist/cli/client.js +13 -90
  22. package/dist/cli/help-examples.generated.js +1 -1
  23. package/dist/cli/notes/api-transport.js +6 -6
  24. package/dist/cli/notes/document.d.ts +32 -26
  25. package/dist/cli/notes/document.js +150 -95
  26. package/dist/cli/notes/edit-commands.d.ts +26 -5
  27. package/dist/cli/notes/edit-commands.js +163 -36
  28. package/dist/cli/notes/events.d.ts +3 -33
  29. package/dist/cli/notes/events.js +4 -51
  30. package/dist/cli/notes/html-read.d.ts +6 -0
  31. package/dist/cli/notes/html-read.js +12 -0
  32. package/dist/cli/notes/index.d.ts +10 -1
  33. package/dist/cli/notes/index.js +98 -27
  34. package/dist/cli/notes/move-command.d.ts +4 -0
  35. package/dist/cli/notes/move-command.js +7 -0
  36. package/dist/cli/sessions/runner/serve.d.ts +1 -1
  37. package/dist/cli/vault/sshTransfer.d.ts +1 -1
  38. package/dist/cli/version.d.ts +1 -1
  39. package/dist/cli/version.js +1 -1
  40. package/package.json +9 -9
@@ -9,98 +9,17 @@ import { affiliateSuccessfulWrite } from './session-affiliation.js';
9
9
  // clean message (matching lakeshore's auth/commands.ts error style).
10
10
  // Callers that need to branch on status (404/409) catch HttpError and
11
11
  // inspect `.status`.
12
- export class HttpError extends Error {
13
- status;
14
- body;
15
- /**
16
- * The typed fields of a Source v1 error envelope, absent on every other
17
- * shape.
18
- *
19
- * Kept as fields rather than folded into the message because they are what a
20
- * caller BRANCHES on. `code` is the stable identity of a failure — the
21
- * message is a human sentence the server is free to reword — and `retryable`
22
- * is the server's own answer to "would repeating this identical request
23
- * help", which no client can derive from a status alone: a 503 from a rate
24
- * limiter and a 503 from a misconfigured binding look the same on the wire.
25
- *
26
- * `undefined` means "this response was not a v1 envelope", never "the server
27
- * said no". A caller that must fail closed has to treat undefined as
28
- * unknown rather than as false.
29
- */
30
- code;
31
- retryable;
32
- requestId;
33
- constructor(status, body) {
34
- const parsed = HttpError.parse(body);
35
- super(`(${status}) ${parsed.message}`);
36
- this.name = "HttpError";
37
- this.status = status;
38
- this.body = body;
39
- this.code = parsed.code;
40
- this.retryable = parsed.retryable;
41
- this.requestId = parsed.requestId;
12
+ import { HttpError, RequestNotSent } from "../api/http.js";
13
+ export { HttpError, RequestNotSent };
14
+ function buildUrl(base, path, query) {
15
+ let url;
16
+ try {
17
+ url = new URL(base.replace(/\/+$/, "") + path);
42
18
  }
43
- /**
44
- * Pull a human message, and any typed fields, out of an error body.
45
- *
46
- * Three shapes reach here and they are not variations of one another:
47
- *
48
- * Source v1 {"error": {"code", "message", "retryable", "requestId"}}
49
- * legacy flat {"error": "..."} or {"message": "..."}
50
- * not JSON an HTML 404 page, a proxy's plain-text 502
51
- *
52
- * The v1 branch is tested FIRST and by type, not by presence. Both envelopes
53
- * key on `error`, so the old `if (parsed.error) return parsed.error` matched
54
- * the v1 object too and interpolated it — a real defect, measured before this
55
- * was written: a 503 carrying a code, a message and a requestId rendered as
56
- * `(503) [object Object]`, and the three fields a caller could have acted on
57
- * were gone. Ordering alone does not prevent that; the `typeof` check is what
58
- * does, because it is the only thing that distinguishes the two.
59
- */
60
- static parse(body) {
61
- if (!body)
62
- return { message: "request failed" };
63
- try {
64
- const parsed = JSON.parse(body);
65
- // Source v1 (§15): one nested envelope for every Source route.
66
- if (typeof parsed.error === "object" && parsed.error !== null) {
67
- const e = parsed.error;
68
- // Each field is carried only when it has the type the contract gives
69
- // it. A malformed envelope degrades to whatever it did supply rather
70
- // than to a wrong value of the right shape.
71
- const out = {
72
- message: typeof e.message === "string" && e.message !== "" ? e.message : "request failed",
73
- };
74
- if (typeof e.code === "string")
75
- out.code = e.code;
76
- if (typeof e.retryable === "boolean")
77
- out.retryable = e.retryable;
78
- if (typeof e.requestId === "string")
79
- out.requestId = e.requestId;
80
- return out;
81
- }
82
- // Email-allowlist rejections put the human text in `message`
83
- // (`error` is just "Forbidden").
84
- if (parsed.code === "email_domain_not_allowed" && parsed.message) {
85
- return { message: parsed.message };
86
- }
87
- if (typeof parsed.error === "string" && parsed.error) {
88
- const detail = typeof parsed.message === "string" && parsed.message && parsed.message !== parsed.error
89
- ? `: ${parsed.message}` : "";
90
- return { message: parsed.error + detail };
91
- }
92
- if (parsed.message)
93
- return { message: parsed.message };
94
- }
95
- catch {
96
- // not JSON
97
- }
98
- const oneLine = body.replace(/\s+/g, " ").trim();
99
- return { message: oneLine.length > 200 ? oneLine.slice(0, 200) + "\u2026" : oneLine };
19
+ catch (error) {
20
+ // Nothing has left the process: callers deciding "was this sent?" must not treat it as uncertain.
21
+ throw new RequestNotSent(`invalid request URL: ${base.replace(/\/+$/, "")}${path}`, { cause: error });
100
22
  }
101
- }
102
- function buildUrl(base, path, query) {
103
- const url = new URL(base.replace(/\/+$/, "") + path);
104
23
  if (query) {
105
24
  for (const [k, v] of Object.entries(query)) {
106
25
  if (v === undefined || v === null)
@@ -119,6 +38,8 @@ function authHeaders(token) {
119
38
  */
120
39
  export async function requestJson(base, path, opts = {}) {
121
40
  const { method = "GET", json, query, token, headers = {}, timeoutMs = 30000, redirect = "follow" } = opts;
41
+ if (!(Number.isSafeInteger(timeoutMs) && timeoutMs > 0 && timeoutMs <= 2 ** 31 - 1))
42
+ throw new RequestNotSent(`timeoutMs must be an integer between 1 and ${2 ** 31 - 1}, got ${timeoutMs}`);
122
43
  const init = {
123
44
  method,
124
45
  headers: {
@@ -184,6 +105,8 @@ export async function requestJson(base, path, opts = {}) {
184
105
  */
185
106
  export async function requestRaw(url, opts = {}) {
186
107
  const { method = "GET", token, timeoutMs = 300000, headers = {}, signal, followRedirects = true, } = opts;
108
+ if (!(Number.isSafeInteger(timeoutMs) && timeoutMs > 0 && timeoutMs <= 2 ** 31 - 1))
109
+ throw new RequestNotSent(`timeoutMs must be an integer between 1 and ${2 ** 31 - 1}, got ${timeoutMs}`);
187
110
  const res = await fetch(url, {
188
111
  method,
189
112
  headers: { ...authHeaders(token), ...noteAgentHeaders(new URL(url).pathname), ...resourceSessionHeaders(new URL(url).pathname), ...headers, ...telemetryHeaders() },
@@ -83,7 +83,7 @@ export const helpExamples = {
83
83
  "notes presence": "# Read the participant roster without joining. Text is the default.\nNOTE_ID=release-plan\ndreamlake notes presence \"$NOTE_ID\"",
84
84
  "notes select": "export DREAMLAKE_AGENT_ID=\"review-session-42\"\nexport DREAMLAKE_AGENT_NAME=\"Codex\"\nNOTE_ID=\"your-note-id\"\ndreamlake notes select --text \"The next step is tested in simulation.\" --note \"$NOTE_ID\"\n# Select the last occurrence of a repeated passage.\ndreamlake notes select --text \"simulation\" --note \"$NOTE_ID\" -o -1",
85
85
  "notes rm": "# Read it first and confirm it is the note you mean.\ndreamlake notes read NOTE_ID\n# Asks for confirmation, showing the title and owning namespace.\ndreamlake notes rm NOTE_ID\n# Scripts and agents: skip the prompt and take a JSON receipt.\ndreamlake notes rm NOTE_ID --yes --json\n# Afterwards a read reports not found.\ndreamlake notes read NOTE_ID",
86
- "notes patch": "set -euo pipefail\ndreamlake notes create \"Patch tutorial\" --text 'Hello world.' > created.txt\nNOTE_ID=$(sed -n 's/^ id //p' created.txt)\ndreamlake notes read \"$NOTE_ID\" > baseline.txt\n# Normal reads print note, hash, and revision before the source.\nBASE=$(sed -n '3s/^revision: //p' baseline.txt)\ndreamlake notes patch \"$NOTE_ID\" --base-revision \"$BASE\" > receipt.txt <<'PATCH'\n@@ chars 0:12 @@\n~ Hello [-world-]{+team+}.\nPATCH\nACK=$(sed -n '3s/^revision: //p' receipt.txt)\ndreamlake notes read \"$NOTE_ID\" --if-match \"$ACK\"\n# Expect Hello team. Inspect the result; do not repeat a successful patch.",
86
+ "notes patch": "set -euo pipefail\ndreamlake notes create \"Patch tutorial\" --text 'Hello world.' > created.txt\nNOTE_ID=$(sed -n 's/^ id //p' created.txt)\ndreamlake notes read \"$NOTE_ID\" --view source --json > baseline.json\n# A plain text read is the mapped reading view and --view source is bytes only;\n# --json is the structured snapshot with note, hash and revision.\nBASE=$(jq -er .revision baseline.json)\ndreamlake notes patch \"$NOTE_ID\" --file - --base-revision \"$BASE\" --json > receipt.json <<'PATCH'\n@@ chars 0:12 @@\n~ Hello [-world-]{+team+}.\nPATCH\nACK=$(jq -er .revision receipt.json)\ndreamlake notes read \"$NOTE_ID\" --if-match \"$ACK\"\n# Expect Hello team. Inspect the result; do not repeat a successful patch.",
87
87
  "notes append": "dreamlake notes append \"$NOTE_ID\" --file addition.md --base-revision \"$BASE\" --json\n# ACK is the revision in the successful append receipt.\ndreamlake notes read \"$NOTE_ID\" --at \"$ACK\"",
88
88
  "notes insert": "dreamlake notes insert --note \"$NOTE_ID\" --ind 0 --text 'Review: ' \\\n --base-revision \"$BASE\" --json\n# ACK is the revision returned by the insertion receipt.\ndreamlake notes read \"$NOTE_ID\" --at \"$ACK\"",
89
89
  "notes delete": "dreamlake notes delete 'obsolete paragraph' --note \"$NOTE_ID\" \\\n --base-revision \"$BASE\" --json\n# Pin verification to the receipt's acknowledged revision.\ndreamlake notes read \"$NOTE_ID\" --at \"$ACK\"",
@@ -1,19 +1,19 @@
1
1
  /** Adapt explicit resolved CLI credentials; attribution remains owned by the CLI transport. */
2
2
  import { requestJson, requestRaw } from '../client.js';
3
- import { requestUrl } from '../../api/http.js';
3
+ import { requestUrl, RequestNotSent } from '../../api/http.js';
4
4
  export function noteTransport(c) {
5
5
  return {
6
- request: (method, path, options) => {
6
+ request: async (method, path, options) => {
7
7
  if (method === 'HEAD')
8
- throw new Error('Notes JSON transport does not support HEAD');
8
+ throw new RequestNotSent('Notes JSON transport does not support HEAD');
9
9
  const { body, timeoutMs, ...request } = options ?? {};
10
10
  if (body !== undefined)
11
- throw new Error('Notes collaboration transport requires JSON');
11
+ throw new RequestNotSent('Notes collaboration transport requires JSON');
12
12
  return requestJson(c.remote, path, { token: c.token, method, ...request, timeoutMs: timeoutMs ?? undefined });
13
13
  },
14
- raw: (method, path, options) => {
14
+ raw: async (method, path, options) => {
15
15
  if (method !== 'GET' && method !== 'HEAD')
16
- throw new Error('Notes streaming transport requires GET or HEAD');
16
+ throw new RequestNotSent('Notes streaming transport requires GET or HEAD');
17
17
  return requestRaw(requestUrl(c.remote, path, options?.query), { token: c.token, method, headers: options?.headers, signal: options?.signal, timeoutMs: options?.timeoutMs ?? undefined, followRedirects: false });
18
18
  },
19
19
  };
@@ -1,3 +1,5 @@
1
+ import type { SourceSnapshot, DocumentPatchPayload } from "../../api/note-edits.js";
2
+ import { type NotePatchRequest, type NoteWriteReceipt } from "../../api/note-write.js";
1
3
  import { ctx, type ConnOpts } from "./index.js";
2
4
  export interface DocumentReadOptions extends ConnOpts {
3
5
  at?: string;
@@ -19,6 +21,7 @@ export interface DocumentReadOptions extends ConnOpts {
19
21
  startLine?: string;
20
22
  endLine?: string;
21
23
  numbered?: boolean;
24
+ lines?: string;
22
25
  }
23
26
  export interface DocumentPatchOptions extends ConnOpts {
24
27
  file?: string;
@@ -31,43 +34,46 @@ export interface DocumentPatchOptions extends ConnOpts {
31
34
  json?: boolean;
32
35
  dryRun?: boolean;
33
36
  legacy?: boolean;
37
+ commandId?: string;
34
38
  }
35
39
  interface Tokens {
36
40
  note: string;
37
41
  hash: string;
38
42
  revision: string;
39
43
  }
40
- interface PatchReceipt extends Tokens {
41
- mode: "merge" | "exact";
42
- baseRevision: string;
43
- }
44
44
  export declare function tokens(result: Tokens, note: string): void;
45
45
  type DocumentContext = NonNullable<Awaited<ReturnType<typeof ctx>>>;
46
- export interface SourceSnapshot extends Tokens {
47
- content: string;
48
- }
46
+ export type { SourceSnapshot, SourceEdit, DocumentPatchPayload } from "../../api/note-edits.js";
47
+ export { documentEdits, documentInsertion } from "../../api/note-edits.js";
48
+ /** The retained snapshot every v2 editor plans from, read through the shared core. */
49
49
  export declare function readDocumentSnapshot(c: DocumentContext, id: string, at?: string): Promise<SourceSnapshot>;
50
- export interface DocumentPatchPayload {
51
- format: "inline-dff" | "diff";
52
- patch: string;
53
- baseRevision: string;
54
- mode: "merge" | "exact";
55
- }
56
- export interface SourceEdit {
57
- start: number;
58
- end: number;
59
- text: string;
60
- }
61
- /** Exact original-source spans, with untouched gaps omitted from the PATCH. */
62
- export declare function documentEdits(source: SourceSnapshot, edits: SourceEdit[], exact?: boolean): DocumentPatchPayload;
63
- /** One literal insertion at an original-source Unicode code-point boundary. */
64
- export declare function documentInsertion(source: SourceSnapshot, at: number, text: string, exact?: boolean): DocumentPatchPayload;
65
- /** Shared submission owns receipt validation; input preparation stays with each editor. */
66
- export declare function submitDocumentPatch(c: DocumentContext, id: string, payload: DocumentPatchPayload, headers?: Record<string, string>): Promise<PatchReceipt>;
67
- export declare function printPatchReceipt(result: PatchReceipt, json?: boolean): void;
50
+ /** Inserted text must not carry a generated reading-view header (the core's rule); whole-body writes are checked against their baseline by writePlan. */
51
+ export declare function canonicalInput(text: string, what: string): boolean;
52
+ export declare function canonicalPatch(patch: string, format: "inline-dff" | "diff"): boolean;
53
+ /** `--command-id`: validated client-side with the server's rule, before any request. */
54
+ export declare function commandIdFlag(opts: {
55
+ commandId?: string;
56
+ legacy?: boolean;
57
+ force?: boolean;
58
+ }): boolean;
59
+ /** The exact request body: `commandId` appears only when the flag was given. */
60
+ export declare function withCommandId(payload: DocumentPatchPayload, opts: {
61
+ commandId?: string;
62
+ }): NotePatchRequest;
63
+ /** One submission path for every editor: the shared core verifies the receipt and the command-id echo. */
64
+ export declare function submitDocumentPatch(c: DocumentContext, id: string, payload: NotePatchRequest, options?: {
65
+ ifMatch?: string;
66
+ }): Promise<NoteWriteReceipt>;
67
+ export declare function printPatchReceipt(result: NoteWriteReceipt, json?: boolean): void;
68
+ /** `dreamlake notes command-status NOTE COMMAND_ID`: the durable record behind one --command-id. */
69
+ export declare function runNotesCommandStatus(ref: string, commandId: string, opts: ConnOpts & {
70
+ json?: boolean;
71
+ }): Promise<number>;
72
+ /** The core classifies PATCH failures (see note-write.ts); this maps them to exit codes. */
68
73
  export declare function documentWriteError(error: unknown): number;
74
+ /** `--lines a:b`: two integers, 1-based and inclusive; the conversion to code points happens in the core. */
75
+ export declare function parseLines(raw: string): [number, number];
69
76
  export declare function runDocumentRead(ref: string | undefined, opts: DocumentReadOptions): Promise<number>;
70
77
  /** Shared native fd-0 transport; callers choose decoding and empty-input semantics. */
71
78
  export declare function readStdinBytes(label?: string): Promise<Buffer>;
72
79
  export declare function runDocumentPatch(ref: string, opts: DocumentPatchOptions): Promise<number>;
73
- export {};
@@ -1,8 +1,11 @@
1
- import { readNoteView } from "../../api/note-reading.js";
1
+ import { readNoteView, focusedRead } from "../../api/note-reading.js";
2
2
  import { validateHtmlSnapshot } from "./html-read.js";
3
+ import { notesApi } from "../../api/notes.js";
4
+ import { COMMAND_ID_PATTERN, UncertainOutcome, CommandIdentityUnsupported, NoteWriteNotSubmitted, CommandInProgress, CommandIntentMismatch, refuseReadingView, refuseReadingViewPatch, failureInfo, provenUnsubmitted } from "../../api/note-write.js";
5
+ import { noteTransport } from "./api-transport.js";
3
6
  /** V2 transports exact source and opaque revisions; the backend owns patch parsing. */
4
7
  import { createHash } from "node:crypto";
5
- import { readFileSync, fstatSync } from "node:fs";
8
+ import { readFileSync } from "node:fs";
6
9
  import { HttpError, requestJson, requestRaw } from "../client.js";
7
10
  import { emitJson, fail } from "../helpers.js";
8
11
  import { ctx, report, resolveNote, seg } from "./index.js";
@@ -20,108 +23,121 @@ export function tokens(result, note) {
20
23
  function printTokens(result) {
21
24
  return `note: ${result.note}\nhash: ${result.hash}\nrevision: ${result.revision}\n`;
22
25
  }
23
- export async function readDocumentSnapshot(c, id, at) {
24
- const query = new URLSearchParams({ contract: "v2" });
25
- if (at !== undefined)
26
- query.set("at", at);
27
- const result = await requestJson(c.remote, `/namespaces/${seg(c.ns)}/notes/${seg(id)}/body?${query}`, { token: c.token, redirect: "error" });
28
- tokens(result, id);
29
- if (at !== undefined && result.revision !== at)
30
- throw new Error("server did not return the requested pinned revision");
31
- validateSourceHash(result);
32
- return result;
26
+ export { documentEdits, documentInsertion } from "../../api/note-edits.js";
27
+ /** The retained snapshot every v2 editor plans from, read through the shared core. */
28
+ export function readDocumentSnapshot(c, id, at) {
29
+ return notesApi(noteTransport(c), c.ns).source(id, at);
33
30
  }
34
- function validateSourceHash(result) {
35
- if (typeof result.content !== "string" || `sha256:${createHash("sha256").update(result.content, "utf8").digest("hex")}` !== result.hash) {
36
- throw new Error("source does not match the returned hash");
31
+ /** Inserted text must not carry a generated reading-view header (the core's rule); whole-body writes are checked against their baseline by writePlan. */
32
+ export function canonicalInput(text, what) {
33
+ try {
34
+ refuseReadingView(text, what);
35
+ return true;
37
36
  }
38
- }
39
- function inlineLiteral(text) {
40
- return text.replace(/[\\\n\r\t\[\]{}+\-]/g, char => char === "\n" ? "\\n" : char === "\r" ? "\\r" : char === "\t" ? "\\t" : `\\${char}`);
41
- }
42
- /** Exact original-source spans, with untouched gaps omitted from the PATCH. */
43
- export function documentEdits(source, edits, exact = false) {
44
- const points = Array.from(source.content);
45
- let lastEnd = 0, lastStart = -1;
46
- const hunks = [];
47
- for (const edit of edits) {
48
- if (!Number.isSafeInteger(edit.start) || !Number.isSafeInteger(edit.end) || edit.start < lastEnd
49
- || edit.start <= lastStart || edit.end < edit.start || edit.end > points.length) {
50
- throw new Error("Edit spans must be ordered and disjoint within the original source");
51
- }
52
- lastStart = edit.start;
53
- lastEnd = edit.end;
54
- const old = points.slice(edit.start, edit.end).join("");
55
- if (old === edit.text)
56
- continue;
57
- hunks.push(`@@ chars ${edit.start}:${edit.end} @@\n~ ${old ? `[-${inlineLiteral(old)}-]` : ""}${edit.text ? `{+${inlineLiteral(edit.text)}+}` : ""}\n`);
37
+ catch (error) {
38
+ fail(error.message);
39
+ return false;
58
40
  }
59
- return { format: "inline-dff", patch: hunks.join(""), baseRevision: source.revision, mode: exact ? "exact" : "merge" };
60
- }
61
- /** One literal insertion at an original-source Unicode code-point boundary. */
62
- export function documentInsertion(source, at, text, exact = false) {
63
- return documentEdits(source, [{ start: at, end: at, text }], exact);
64
41
  }
65
- class DocumentWriteUnknownError extends Error {
66
- }
67
- /** Shared submission owns receipt validation; input preparation stays with each editor. */
68
- export async function submitDocumentPatch(c, id, payload, headers = {}) {
69
- let result;
42
+ export function canonicalPatch(patch, format) {
70
43
  try {
71
- result = await requestJson(c.remote, `/namespaces/${seg(c.ns)}/notes/${seg(id)}/body`, {
72
- token: c.token, method: "PATCH", headers, json: payload, redirect: "error",
73
- });
44
+ refuseReadingViewPatch(patch, format);
45
+ return true;
74
46
  }
75
47
  catch (error) {
76
- if (error instanceof HttpError && [400, 401, 403, 404, 409, 412, 413, 415, 422, 503].includes(error.status))
77
- throw error;
78
- throw new DocumentWriteUnknownError("Notes write outcome unknown; keep the original baseline and draft, inspect the note before resubmitting");
48
+ fail(error.message);
49
+ return false;
79
50
  }
80
- try {
81
- tokens(result, id);
82
- if (result.mode !== payload.mode || result.baseRevision !== payload.baseRevision)
83
- throw new Error("inconsistent receipt");
51
+ }
52
+ function validateSourceHash(result) {
53
+ if (typeof result.content !== "string" || `sha256:${createHash("sha256").update(result.content, "utf8").digest("hex")}` !== result.hash) {
54
+ throw new Error("source does not match the returned hash");
84
55
  }
85
- catch {
86
- throw new DocumentWriteUnknownError("Notes write outcome unknown: invalid receipt; keep the original baseline and draft, inspect the note before resubmitting");
56
+ }
57
+ /** `--command-id`: validated client-side with the server's rule, before any request. */
58
+ export function commandIdFlag(opts) {
59
+ if (opts.commandId === undefined)
60
+ return true;
61
+ if (opts.legacy || opts.force) {
62
+ fail("--command-id requires the v2 write; it cannot combine with --legacy or --force");
63
+ return false;
64
+ }
65
+ if (!COMMAND_ID_PATTERN.test(opts.commandId)) {
66
+ fail("--command-id must be 8–128 characters of A-Z a-z 0-9 . _ : -");
67
+ return false;
87
68
  }
88
- return result;
69
+ return true;
70
+ }
71
+ /** The exact request body: `commandId` appears only when the flag was given. */
72
+ export function withCommandId(payload, opts) {
73
+ return opts.commandId === undefined ? payload : { ...payload, commandId: opts.commandId };
74
+ }
75
+ /** One submission path for every editor: the shared core verifies the receipt and the command-id echo. */
76
+ export function submitDocumentPatch(c, id, payload, options = {}) {
77
+ return notesApi(noteTransport(c), c.ns).patch(id, payload, options);
89
78
  }
90
79
  export function printPatchReceipt(result, json) {
91
80
  if (json)
92
81
  emitJson(result);
82
+ // Text output is unchanged without --command-id; the identity lines are appended only when one was sent.
93
83
  else
94
- process.stdout.write(`${printTokens(result)}mode: ${result.mode}\nbaseRevision: ${result.baseRevision}\n`);
84
+ process.stdout.write(`${printTokens(result)}mode: ${result.mode}\nbaseRevision: ${result.baseRevision}\n${result.commandId === null ? "" : `outcome: ${result.outcome}\ncommandId: ${result.commandId}\nreplayed: ${result.replayed}\n`}`);
95
85
  }
96
- /** Current API proof only. Human text and unknown marker versions cannot
97
- * prove whether a requested native edit reached RTC. */
98
- function baselinePatchNotSubmitted(error) {
99
- if (error.status !== 503)
100
- return false;
86
+ /** `dreamlake notes command-status NOTE COMMAND_ID`: the durable record behind one --command-id. */
87
+ export async function runNotesCommandStatus(ref, commandId, opts) {
88
+ if (!COMMAND_ID_PATTERN.test(commandId)) {
89
+ fail("command id must be 8–128 characters of A-Z a-z 0-9 . _ : -");
90
+ return 1;
91
+ }
92
+ const c = await ctx(opts);
93
+ if (!c)
94
+ return 1;
101
95
  try {
102
- const body = JSON.parse(error.body);
103
- if (!body || typeof body !== "object" || Array.isArray(body))
104
- return false;
105
- const envelope = body, marker = envelope.mutation;
106
- if (envelope.error !== "rtc_unavailable" || !marker || typeof marker !== "object" || Array.isArray(marker))
107
- return false;
108
- const value = marker;
109
- return Object.keys(value).length === 3 && value.apiVersion === 1 && value.started === false && value.phase === "baseline_read";
96
+ const id = await resolveNote(c, ref);
97
+ if (!id)
98
+ return 1;
99
+ const status = await notesApi(noteTransport(c), c.ns).commandStatus(id, commandId);
100
+ if (opts.json) {
101
+ emitJson(status);
102
+ return 0;
103
+ }
104
+ process.stdout.write(`commandId: ${status.commandId}\nstate: ${status.state}\n${status.outcome ? `outcome: ${status.outcome}\n` : ""}${status.receipt ? `revision: ${status.receipt.revision}\nhash: ${status.receipt.hash}\n` : ""}createdAt: ${status.createdAt}\nupdatedAt: ${status.updatedAt}\n`);
105
+ return 0;
110
106
  }
111
- catch {
112
- return false;
107
+ catch (error) {
108
+ return report(error);
113
109
  }
114
110
  }
111
+ /** The core classifies PATCH failures (see note-write.ts); this maps them to exit codes. */
115
112
  export function documentWriteError(error) {
116
- if (error instanceof HttpError && baselinePatchNotSubmitted(error)) {
117
- fail("patch not submitted: the requested edit did not start because its baseline is unavailable; preserve the original baseline and draft");
113
+ if (error instanceof NoteWriteNotSubmitted) {
114
+ fail(error.message);
118
115
  return 1;
119
116
  }
120
- if (error instanceof DocumentWriteUnknownError) {
117
+ if (error instanceof UncertainOutcome) {
121
118
  fail(error.message);
122
119
  return 4;
123
120
  }
124
- if (error instanceof HttpError && [409, 412, 422, 503].includes(error.status)) {
121
+ if (error instanceof CommandInProgress) {
122
+ fail(error.message);
123
+ return 4;
124
+ }
125
+ if (error instanceof CommandIntentMismatch) {
126
+ fail(error.message);
127
+ return 1;
128
+ }
129
+ if (error instanceof CommandIdentityUnsupported) {
130
+ fail(`${error.message}; the write may have been applied: inspect the note before resubmitting, and upgrade the server before relying on --command-id`);
131
+ return 4;
132
+ }
133
+ // The core turns a PATCH 503 into a typed outcome above, so a raw 503 here came from the
134
+ // baseline read (or note resolution): nothing was submitted and nothing is ambiguous.
135
+ if (error instanceof HttpError && error.status === 503) {
136
+ fail(provenUnsubmitted(failureInfo(error).body) ? new NoteWriteNotSubmitted().message
137
+ : `patch not submitted: the original baseline could not be read, so nothing was sent; preserve the original baseline and draft (${error.message})`);
138
+ return 1;
139
+ }
140
+ if (error instanceof HttpError && [409, 412, 422].includes(error.status)) {
125
141
  const reason = error.status === 412 ? "the original revision or RTC identities are no longer valid for this request"
126
142
  : error.status === 422 ? "the patch was rejected; inspect the server explanation and preserve the original snapshot and draft"
127
143
  : "the realtime acknowledgment is unavailable; the result may be ambiguous";
@@ -130,9 +146,23 @@ export function documentWriteError(error) {
130
146
  }
131
147
  return report(error);
132
148
  }
149
+ /** `--lines a:b`: two integers, 1-based and inclusive; the conversion to code points happens in the core. */
150
+ export function parseLines(raw) {
151
+ const match = /^(\d{1,15}):(\d{1,15})$/.exec(raw);
152
+ if (!match)
153
+ throw new Error("--lines takes two integers a:b, 1-based and inclusive");
154
+ return [Number(match[1]), Number(match[2])];
155
+ }
133
156
  export async function runDocumentRead(ref, opts) {
134
157
  try {
135
- opts = { ...opts, view: opts.view ?? (opts.toc || opts.section || opts.tag ? "html" : "source") };
158
+ // Text output defaults to the mapped Markdown view (agreed reading direction);
159
+ // --json, --since, --lines and --legacy keep exact source, --view source restores the old text.
160
+ const explicitSource = opts.view === "source";
161
+ const defaultedView = opts.view === undefined && !opts.toc && !opts.section && !opts.tag && !opts.json && !opts.legacy
162
+ && opts.since === undefined && opts.format === undefined && opts.lines === undefined;
163
+ opts = { ...opts, view: opts.view ?? (opts.toc || opts.section || opts.tag ? "html" : defaultedView ? "markdown" : "source") };
164
+ if (opts.lines !== undefined && (opts.view !== "source" || opts.since !== undefined || opts.format !== undefined))
165
+ throw new Error("--lines returns an exact source slice; it cannot combine with --view html/markdown, --toc/--section/--tag, --since or --format");
136
166
  if (opts.view !== undefined && opts.view !== "source" && opts.view !== "html" && opts.view !== "markdown")
137
167
  throw new Error("--view must be source, html or markdown");
138
168
  if ((opts.view === "html" || opts.view === "markdown") && (opts.since !== undefined || opts.format !== undefined || opts.json || opts.legacy))
@@ -160,6 +190,22 @@ export async function runDocumentRead(ref, opts) {
160
190
  const id = await resolveNote(c, target);
161
191
  if (!id)
162
192
  return 1;
193
+ if (opts.lines !== undefined) {
194
+ const lines = parseLines(opts.lines);
195
+ const focused = focusedRead(await readDocumentSnapshot(c, id, opts.at), lines);
196
+ if (opts.ifMatch && focused.revision !== opts.ifMatch) {
197
+ fail("note changed since the acknowledged revision; keep the original draft and baseline");
198
+ return 3;
199
+ }
200
+ if (opts.json)
201
+ emitJson(focused);
202
+ // --view source: the selected exact bytes only; otherwise the focused presentation with its address.
203
+ else if (explicitSource)
204
+ process.stdout.write(focused.content);
205
+ else
206
+ process.stdout.write(`${printTokens(focused)}scope: lines ${focused.lines[0]}:${focused.lines[1]} chars ${focused.chars[0]}:${focused.chars[1]}\ncomplete: false\n\n${focused.content}`);
207
+ return 0;
208
+ }
163
209
  const query = new URLSearchParams({ contract: "v2" });
164
210
  if (opts.at)
165
211
  query.set("at", opts.at);
@@ -167,8 +213,14 @@ export async function runDocumentRead(ref, opts) {
167
213
  const transport = { request: (method, path, options = {}) => { if (method !== "GET")
168
214
  throw new Error("reading transport requires GET"); return requestJson(c.remote, path, { method, query: options.query, headers: options.headers, token: c.token, redirect: "error" }); } };
169
215
  let at = opts.at, start = 0, hash, total;
216
+ let fallback = false;
170
217
  do {
171
218
  const page = await readNoteView(transport, c.ns, id, { at, start, section: opts.section, tag: opts.tag, toc: opts.toc });
219
+ // An HTML-source note has no Markdown reading view: the defaulted read falls back to exact source.
220
+ if (page.sourceType !== 'markdown' && defaultedView && start === 0) {
221
+ fallback = true;
222
+ break;
223
+ }
172
224
  if (page.sourceType !== 'markdown')
173
225
  throw new Error('annotated Markdown requires a Markdown note; use --view html for HTML source');
174
226
  if (opts.ifMatch && page.revision !== opts.ifMatch) {
@@ -185,7 +237,9 @@ export async function runDocumentRead(ref, opts) {
185
237
  break;
186
238
  start = page.next;
187
239
  } while (true);
188
- return 0;
240
+ if (!fallback)
241
+ return 0;
242
+ opts = { ...opts, view: "source" };
189
243
  }
190
244
  if (opts.view === "html") {
191
245
  if (opts.section !== undefined)
@@ -238,35 +292,32 @@ export async function runDocumentRead(ref, opts) {
238
292
  emitJson(result);
239
293
  else if (opts.since !== undefined) {
240
294
  process.stdout.write(`note: ${result.note}\nformat: ${result.format}\nbase: ${result.base}\nhash: ${result.hash}\nrevision: ${result.revision}\nunit: unicode-code-point\n${result.since ? `since: ${result.since}\n` : ""}\n${result.patch}`);
295
+ // --view source prints the exact source bytes only: no header, no added LF (use --json for provenance).
241
296
  }
242
297
  else
243
- process.stdout.write(`${printTokens(result)}\n${result.content}`);
298
+ process.stdout.write(result.content);
244
299
  return 0;
245
300
  }
246
301
  catch (error) {
247
302
  return report(error);
248
303
  }
249
304
  }
250
- /** An explicit input conflicts with a pipe or redirected regular file, including empty input. */
251
- function redirectedInput() {
252
- if (process.stdin.isTTY)
253
- return false;
254
- const stat = fstatSync(0);
255
- return stat.isFIFO() || stat.isFile() || stat.isSocket();
256
- }
305
+ /** The patch text: `--diff STRING`, `--file PATH`, or `--file -` for stdin. Stdin is read only when
306
+ * asked for (Notes CLI stream contract): a pipe is never consumed implicitly, and `--diff`/`--file PATH`
307
+ * ignore whatever stdin is, so the outcome does not depend on how the command was launched. */
257
308
  async function patchInput(opts) {
258
309
  if (opts.file !== undefined && opts.diff !== undefined)
259
- throw new Error("choose stdin, --file, or --diff; do not combine them");
260
- if ((opts.file !== undefined && opts.file !== "-") || opts.diff !== undefined) {
261
- if (redirectedInput())
262
- throw new Error("explicit patch input conflicts with redirected stdin");
310
+ throw new Error("choose --file or --diff; do not combine them");
311
+ if (opts.diff !== undefined || (opts.file !== undefined && opts.file !== "-")) {
263
312
  const bytes = opts.diff !== undefined ? Buffer.from(opts.diff, "utf8") : readFileSync(opts.file);
264
313
  if (bytes.length > 8_000_000)
265
314
  throw new Error("patch exceeds 8000000 bytes");
266
315
  return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
267
316
  }
317
+ if (opts.file !== "-")
318
+ throw new Error("give the patch with --diff <string>, --file <path> or --file - (stdin is read only with --file -)");
268
319
  if (process.stdin.isTTY)
269
- throw new Error("provide a quoted multiline here-document, pipe, or --file; interactive stdin is not accepted");
320
+ process.stderr.write("reading the patch from the terminal; end it with Ctrl-D\n");
270
321
  return new TextDecoder("utf-8", { fatal: true }).decode(await readStdinBytes());
271
322
  }
272
323
  /** Shared native fd-0 transport; callers choose decoding and empty-input semantics. */
@@ -287,6 +338,8 @@ export async function readStdinBytes(label = "patch") {
287
338
  return Buffer.concat(chunks);
288
339
  }
289
340
  export async function runDocumentPatch(ref, opts) {
341
+ if (!commandIdFlag(opts))
342
+ return 1;
290
343
  try {
291
344
  const selectedFormat = format(opts.format);
292
345
  if (opts.force)
@@ -304,6 +357,8 @@ export async function runDocumentPatch(ref, opts) {
304
357
  const patch = await patchInput(opts);
305
358
  if (!patch.trim())
306
359
  throw new Error("patch input is empty; no edit was sent. Check stdin or pass --file with the patch path");
360
+ if (!canonicalPatch(patch, selectedFormat))
361
+ return 1;
307
362
  const c = await ctx(opts);
308
363
  if (!c)
309
364
  return 1;
@@ -313,7 +368,7 @@ export async function runDocumentPatch(ref, opts) {
313
368
  const path = `/namespaces/${seg(c.ns)}/notes/${seg(id)}/body`;
314
369
  const headers = opts.ifMatch === undefined ? {} : { "If-Match": opts.ifMatch };
315
370
  const mode = opts.exact || opts.ifMatch !== undefined ? "exact" : "merge";
316
- const payload = { format: selectedFormat, patch, baseRevision, mode };
371
+ const payload = withCommandId({ format: selectedFormat, patch, baseRevision, mode }, opts);
317
372
  if (opts.dryRun) {
318
373
  if (opts.json)
319
374
  emitJson({ dryRun: true, method: "PATCH", path, headers, payload });
@@ -321,7 +376,7 @@ export async function runDocumentPatch(ref, opts) {
321
376
  process.stdout.write(`method: PATCH\npath: ${path}\nmode: ${mode}\nbase-revision: ${baseRevision}\n${opts.ifMatch === undefined ? "" : `if-match: ${opts.ifMatch}\n`}format: ${selectedFormat}\n\n${patch}`);
322
377
  return 0;
323
378
  }
324
- const result = await submitDocumentPatch(c, id, payload, headers);
379
+ const result = await submitDocumentPatch(c, id, payload, { ifMatch: opts.ifMatch });
325
380
  printPatchReceipt(result, opts.json);
326
381
  return 0;
327
382
  }