@dreamlake/dreamlake-cli 0.97.2 → 0.99.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 (70) 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 +217 -511
  6. package/dist/api/index.js +12 -2
  7. package/dist/api/native-experiments.d.ts +77 -0
  8. package/dist/api/native-experiments.js +31 -0
  9. package/dist/api/note-edits.d.ts +40 -2
  10. package/dist/api/note-edits.js +197 -2
  11. package/dist/api/note-events.d.ts +40 -4
  12. package/dist/api/note-events.js +55 -2
  13. package/dist/api/note-facade.d.ts +268 -0
  14. package/dist/api/note-facade.js +376 -0
  15. package/dist/api/note-reading.d.ts +27 -0
  16. package/dist/api/note-reading.js +27 -0
  17. package/dist/api/note-write.d.ts +110 -0
  18. package/dist/api/note-write.js +217 -0
  19. package/dist/api/notes.d.ts +33 -44
  20. package/dist/api/notes.js +44 -34
  21. package/dist/api/sessions.d.ts +240 -7
  22. package/dist/api/sessions.js +56 -1
  23. package/dist/api/skills.d.ts +122 -0
  24. package/dist/api/skills.js +220 -0
  25. package/dist/cli/client.d.ts +2 -41
  26. package/dist/cli/client.js +13 -90
  27. package/dist/cli/experiments/index.js +2 -0
  28. package/dist/cli/experiments/native-commands.d.ts +13 -0
  29. package/dist/cli/experiments/native-commands.js +88 -0
  30. package/dist/cli/help-examples.generated.js +23 -6
  31. package/dist/cli/index.js +2 -0
  32. package/dist/cli/notes/api-transport.js +6 -6
  33. package/dist/cli/notes/document.d.ts +32 -26
  34. package/dist/cli/notes/document.js +150 -95
  35. package/dist/cli/notes/edit-commands.d.ts +26 -5
  36. package/dist/cli/notes/edit-commands.js +163 -36
  37. package/dist/cli/notes/events.d.ts +3 -33
  38. package/dist/cli/notes/events.js +4 -51
  39. package/dist/cli/notes/html-read.d.ts +6 -0
  40. package/dist/cli/notes/html-read.js +12 -0
  41. package/dist/cli/notes/index.d.ts +10 -1
  42. package/dist/cli/notes/index.js +98 -27
  43. package/dist/cli/notes/move-command.d.ts +4 -0
  44. package/dist/cli/notes/move-command.js +7 -0
  45. package/dist/cli/session-affiliation.js +3 -2
  46. package/dist/cli/sessions/affiliation.d.ts +12 -1
  47. package/dist/cli/sessions/affiliation.js +37 -0
  48. package/dist/cli/sessions/control.d.ts +11 -0
  49. package/dist/cli/sessions/control.js +49 -4
  50. package/dist/cli/sessions/index.js +70 -17
  51. package/dist/cli/sessions/live.d.ts +85 -0
  52. package/dist/cli/sessions/live.js +258 -0
  53. package/dist/cli/sessions/runner/exec.d.ts +118 -6
  54. package/dist/cli/sessions/runner/exec.js +298 -47
  55. package/dist/cli/sessions/runner/native.js +4 -1
  56. package/dist/cli/sessions/runner/serve.d.ts +37 -2
  57. package/dist/cli/sessions/runner/serve.js +273 -28
  58. package/dist/cli/sessions/wrap.d.ts +63 -0
  59. package/dist/cli/sessions/wrap.js +226 -0
  60. package/dist/cli/skill/index.d.ts +19 -1
  61. package/dist/cli/skill/index.js +65 -12
  62. package/dist/cli/skill/read.d.ts +25 -0
  63. package/dist/cli/skill/read.js +65 -0
  64. package/dist/cli/skill/registry.d.ts +95 -0
  65. package/dist/cli/skill/registry.js +284 -0
  66. package/dist/cli/skill/reminders.js +2 -1
  67. package/dist/cli/vault/sshTransfer.d.ts +1 -1
  68. package/dist/cli/version.d.ts +1 -1
  69. package/dist/cli/version.js +1 -1
  70. package/package.json +9 -9
@@ -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
  }
@@ -51,16 +51,24 @@ export declare function runNotesFind(query: string | undefined, opts: ConnOpts &
51
51
  flags?: string;
52
52
  json?: boolean;
53
53
  limit?: string;
54
+ at?: string;
55
+ caseSensitive?: boolean;
54
56
  }): Promise<number>;
55
57
  export declare function runNotesToc(opts: ConnOpts & {
56
58
  note?: string;
57
59
  json?: boolean;
58
60
  html?: boolean;
61
+ at?: string;
59
62
  }): Promise<number>;
60
63
  type MutateOpts = ConnOpts & {
61
64
  note?: string;
62
65
  selector?: string;
66
+ /** A mapped element address (`s1.p2`) from the reading view: its full original span. */
67
+ address?: string;
63
68
  text?: string;
69
+ /** Exact UTF-8 text from a file (`-` for stdin) instead of --text. */
70
+ file?: string;
71
+ lines?: string;
64
72
  regex?: string;
65
73
  flags?: string;
66
74
  line?: string;
@@ -74,20 +82,33 @@ type MutateOpts = ConnOpts & {
74
82
  legacy?: boolean;
75
83
  baseRevision?: string;
76
84
  exact?: boolean;
85
+ commandId?: string;
77
86
  };
87
+ /** `notes replace|delete NOTE_ID --lines a:b …`: with a span selector and no --note, a
88
+ * 24-hex positional is the note, not a query (Notes API: IDs are primary). */
89
+ export declare function positionalNote<T extends {
90
+ note?: string;
91
+ lines?: string;
92
+ line?: string;
93
+ address?: string;
94
+ ind?: string;
95
+ }>(query: string | undefined, opts: T): [string | undefined, T];
78
96
  export declare function runNotesReplace(query: string | undefined, opts: MutateOpts & {
79
97
  html?: string;
80
98
  }): Promise<number>;
99
+ /** `notes delete` and its contract alias `notes remove`: delete selected source, never the Note. */
81
100
  export declare function runNotesDelete(query: string | undefined, opts: MutateOpts): Promise<number>;
82
101
  /** Set an element's inner source verbatim. Markup, not escaped. */
83
102
  export declare function elementHtmlPlan(source: string, css: string, html: string): EditPlan;
84
103
  export declare function setElementHtml(source: string, css: string, html: string): string;
85
- export declare function runNotesInsert(opts: MutateOpts & {
104
+ type InsertOpts = MutateOpts & {
86
105
  position?: string;
87
- legacy?: boolean;
88
- baseRevision?: string;
89
- exact?: boolean;
90
- }): Promise<number>;
106
+ before?: string;
107
+ after?: string;
108
+ cursor?: string;
109
+ };
110
+ /** `notes insert [NOTE] --before|--after ADDRESS | --cursor N | --line N | --ind N | --selector CSS`; the note may be positional (IDs are primary). */
111
+ export declare function runNotesInsert(noteOrOpts: string | undefined | InsertOpts, maybeOpts?: InsertOpts): Promise<number>;
91
112
  /** `dreamlake notes select "#contact" --note NOTE` */
92
113
  export declare function runNotesSelect(css: string, opts: ConnOpts & {
93
114
  note?: string;