@north-light/cli 0.3.706 → 0.3.708

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 (187) hide show
  1. package/dist/api/client.d.ts +1 -2
  2. package/dist/api/client.js +3 -3
  3. package/dist/api/contract.d.ts +1 -1
  4. package/dist/api/contract.js +1 -1
  5. package/dist/api/dto/human.d.ts +9 -6
  6. package/dist/api/dto/inbox.d.ts +2 -0
  7. package/dist/api/dto/review-comments.d.ts +12 -35
  8. package/dist/api/dto/reviews.d.ts +3 -10
  9. package/dist/api/routes.d.ts +0 -1
  10. package/dist/api/routes.js +1 -1
  11. package/dist/builtin-memory/05-kinds/review/companion/00-base.md +2 -2
  12. package/dist/builtin-memory/crouter-sdk/release-notes.md +6 -0
  13. package/dist/clients/attach/chrome/canvas-panels.d.ts +1 -1
  14. package/dist/clients/attach/chrome/canvas-panels.js +1 -1
  15. package/dist/clients/attach/chrome/roster.js +6 -6
  16. package/dist/clients/attach/chrome/status-line.js +1 -1
  17. package/dist/clients/attach/chrome/ticket-panel.js +1 -1
  18. package/dist/clients/attach/input/controller.d.ts +0 -1
  19. package/dist/clients/attach/input/controller.js +3 -3
  20. package/dist/clients/attach/input/overlay-owner.d.ts +0 -1
  21. package/dist/clients/attach/input/overlay-owner.js +1 -1
  22. package/dist/clients/attach/session/keys.d.ts +0 -2
  23. package/dist/clients/attach/session/keys.js +1 -1
  24. package/dist/clients/attach/session/surface-host.d.ts +0 -5
  25. package/dist/clients/attach/session/surface-host.js +1 -1
  26. package/dist/clients/attach/viewer.js +545 -560
  27. package/dist/clients/editor-roundtrip.js +3 -0
  28. package/dist/clients/inbox/controller.d.ts +1 -6
  29. package/dist/clients/inbox/controller.js +1 -1
  30. package/dist/clients/inbox/dto-adapt.js +1 -1
  31. package/dist/clients/inbox/tui/page-body.js +1 -1
  32. package/dist/clients/inbox/tui/render.js +2 -2
  33. package/dist/clients/open-browser.d.ts +2 -0
  34. package/dist/clients/open-browser.js +1 -0
  35. package/dist/clients/surfaces/host.d.ts +0 -6
  36. package/dist/commands/human/review.js +1 -1
  37. package/dist/commands/sys/context/admin/shell.js +1 -1
  38. package/dist/core/canvas/schema-pg/025-review-anchors.sql +19 -0
  39. package/dist/core/canvas/schema-version.d.ts +1 -1
  40. package/dist/core/canvas/schema-version.js +1 -1
  41. package/dist/core/human/page-markdown.js +10 -12
  42. package/dist/core/human/tickets.js +1 -1
  43. package/dist/core/human/types.d.ts +4 -6
  44. package/dist/core/keybindings/attach-control.d.ts +0 -3
  45. package/dist/core/keybindings/attach-control.js +1 -1
  46. package/dist/core/keybindings/catalog.d.ts +1 -1
  47. package/dist/core/keybindings/catalog.js +1 -1
  48. package/dist/core/review/anchors.d.ts +28 -0
  49. package/dist/core/review/anchors.js +6 -0
  50. package/dist/core/review/comments.d.ts +2 -2
  51. package/dist/core/review/comments.js +7 -8
  52. package/dist/core/review/companion.d.ts +2 -1
  53. package/dist/core/review/companion.js +1 -1
  54. package/dist/core/review/document.d.ts +4 -17
  55. package/dist/core/review/document.js +1 -2
  56. package/dist/core/review/fork.js +2 -4
  57. package/dist/core/review/project.d.ts +1 -1
  58. package/dist/core/review/project.js +2 -2
  59. package/dist/core/review/realize.js +1 -1
  60. package/dist/core/review/stage.d.ts +2 -9
  61. package/dist/core/review/stage.js +1 -1
  62. package/dist/core/review/types.d.ts +16 -12
  63. package/dist/core/review/types.js +1 -1
  64. package/dist/core/runtime/broker/turn-replies.d.ts +1 -3
  65. package/dist/core/runtime/broker-cli.js +3 -3
  66. package/dist/core/runtime/broker-extension-render.js +1 -1
  67. package/dist/core/runtime/tmux-bindings.js +3 -3
  68. package/dist/daemon/api/canvas-host.js +1 -1
  69. package/dist/daemon/api/document-page.d.ts +12 -1
  70. package/dist/daemon/api/document-page.js +6 -6
  71. package/dist/daemon/api/handlers/inbox.js +1 -1
  72. package/dist/daemon/api/handlers/review-comments.js +1 -1
  73. package/dist/daemon/api/handlers/reviews.js +1 -1
  74. package/dist/daemon/api/map.js +2 -2
  75. package/dist/daemon/api/review-page.d.ts +3 -0
  76. package/dist/daemon/api/review-page.js +13 -0
  77. package/dist/daemon/broker-memory-cap.d.ts +9 -0
  78. package/dist/daemon/broker-memory-cap.js +2 -0
  79. package/dist/daemon/broker-signals/bus.d.ts +1 -1
  80. package/dist/daemon/broker-signals/bus.js +1 -1
  81. package/dist/daemon/crtrd.js +14 -14
  82. package/dist/daemon/machine-daemon.js +1 -1
  83. package/dist/daemon/review/comment-notify.js +2 -2
  84. package/dist/daemon/review/deliver.d.ts +2 -2
  85. package/dist/daemon/review/deliver.js +6 -2
  86. package/dist/daemon/review/finish.js +1 -1
  87. package/dist/doc-editor/Geist-Variable.woff2 +0 -0
  88. package/dist/doc-editor/GeistMono-Variable.woff2 +0 -0
  89. package/dist/doc-editor/editor.css +1 -1
  90. package/dist/doc-editor/review.css +2 -0
  91. package/dist/doc-editor/review.js +149 -0
  92. package/dist/pi-extensions/canvas-review-boundary.js +3 -3
  93. package/dist/shared/turn-replies.d.ts +3 -3
  94. package/dist/shared/turn-replies.js +3 -3
  95. package/docs/sdk/release-notes.md +6 -0
  96. package/package.json +13 -4
  97. package/packages/crouter-api/dist/api/client.js +0 -3
  98. package/packages/crouter-api/dist/api/contract.js +1 -1
  99. package/packages/crouter-api/dist/api/routes.js +0 -1
  100. package/packages/crouter-api/dist/clients/attach/chrome/canvas-panels.js +3 -3
  101. package/packages/crouter-api/dist/clients/attach/chrome/roster.js +9 -20
  102. package/packages/crouter-api/dist/clients/attach/chrome/status-line.js +1 -6
  103. package/packages/crouter-api/dist/clients/attach/chrome/ticket-panel.js +1 -1
  104. package/packages/crouter-api/dist/clients/attach/input/controller.js +0 -3
  105. package/packages/crouter-api/dist/clients/attach/input/overlay-owner.js +0 -7
  106. package/packages/crouter-api/dist/clients/attach/session/keys.js +0 -1
  107. package/packages/crouter-api/dist/clients/attach/session/surface-host.js +0 -17
  108. package/packages/crouter-api/dist/clients/attach/viewer.js +0 -37
  109. package/packages/crouter-api/dist/clients/{inbox/review/roundtrip.js → editor-roundtrip.js} +1 -1
  110. package/packages/crouter-api/dist/clients/inbox/controller.js +12 -31
  111. package/packages/crouter-api/dist/clients/inbox/dto-adapt.js +1 -0
  112. package/packages/crouter-api/dist/clients/inbox/tui/page-body.js +0 -7
  113. package/packages/crouter-api/dist/clients/inbox/tui/render.js +0 -7
  114. package/packages/crouter-api/dist/clients/open-browser.js +6 -0
  115. package/packages/crouter-api/dist/commands/human/review.js +17 -18
  116. package/packages/crouter-api/dist/commands/sys/context/admin/shell.js +1 -1
  117. package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
  118. package/packages/crouter-api/dist/core/human/page-markdown.js +2 -6
  119. package/packages/crouter-api/dist/core/human/tickets.js +2 -11
  120. package/packages/crouter-api/dist/core/keybindings/attach-control.js +0 -1
  121. package/packages/crouter-api/dist/core/keybindings/catalog.js +1 -3
  122. package/packages/crouter-api/dist/core/review/anchors.js +91 -0
  123. package/packages/crouter-api/dist/core/review/comments.js +27 -46
  124. package/packages/crouter-api/dist/core/review/companion.js +5 -9
  125. package/packages/crouter-api/dist/core/review/document.js +17 -89
  126. package/packages/crouter-api/dist/core/review/project.js +2 -1
  127. package/packages/crouter-api/dist/core/review/types.js +2 -2
  128. package/packages/crouter-api/dist/core/runtime/tmux-bindings.js +0 -5
  129. package/packages/crouter-api/dist/daemon/api/map.js +2 -6
  130. package/packages/crouter-api/dist/daemon/broker-signals/bus.js +1 -1
  131. package/packages/crouter-api/dist/daemon/review/deliver.js +4 -3
  132. package/packages/crouter-api/dist/daemon/review/finish.js +26 -47
  133. package/packages/crouter-api/dist/shared/turn-replies.js +9 -14
  134. package/packages/crouter-api/package.json +1 -1
  135. package/packages/crouter-identity/package.json +1 -1
  136. package/packages/crouter-plugin/package.json +3 -3
  137. package/runtime.lock.json +1740 -505
  138. package/dist/clients/attach/overlays/file-review.d.ts +0 -10
  139. package/dist/clients/attach/overlays/file-review.js +0 -2
  140. package/dist/clients/inbox/review/anchors.d.ts +0 -41
  141. package/dist/clients/inbox/review/anchors.js +0 -1
  142. package/dist/clients/inbox/review/comments-client.d.ts +0 -74
  143. package/dist/clients/inbox/review/comments-client.js +0 -1
  144. package/dist/clients/inbox/review/companion-pane.d.ts +0 -47
  145. package/dist/clients/inbox/review/companion-pane.js +0 -1
  146. package/dist/clients/inbox/review/document-surface.d.ts +0 -212
  147. package/dist/clients/inbox/review/document-surface.js +0 -2
  148. package/dist/clients/inbox/review/frame.d.ts +0 -57
  149. package/dist/clients/inbox/review/frame.js +0 -1
  150. package/dist/clients/inbox/review/keys.d.ts +0 -69
  151. package/dist/clients/inbox/review/keys.js +0 -1
  152. package/dist/clients/inbox/review/launch.d.ts +0 -16
  153. package/dist/clients/inbox/review/launch.js +0 -1
  154. package/dist/clients/inbox/review/live-source.d.ts +0 -24
  155. package/dist/clients/inbox/review/live-source.js +0 -1
  156. package/dist/clients/inbox/review/nvim.d.ts +0 -15
  157. package/dist/clients/inbox/review/nvim.js +0 -1
  158. package/dist/clients/inbox/review/remap.d.ts +0 -51
  159. package/dist/clients/inbox/review/remap.js +0 -1
  160. package/dist/clients/inbox/review/review-client.d.ts +0 -43
  161. package/dist/clients/inbox/review/review-client.js +0 -1
  162. package/dist/clients/inbox/review/roundtrip.js +0 -3
  163. package/dist/clients/inbox/review/state.d.ts +0 -153
  164. package/dist/clients/inbox/review/state.js +0 -4
  165. package/dist/clients/inbox/review-adapter.d.ts +0 -17
  166. package/dist/clients/inbox/review-adapter.js +0 -1
  167. package/dist/core/review/remap.d.ts +0 -24
  168. package/dist/core/review/remap.js +0 -19
  169. package/dist/core/review/signal.d.ts +0 -5
  170. package/dist/core/review/signal.js +0 -1
  171. package/packages/crouter-api/dist/clients/attach/overlays/file-review.js +0 -146
  172. package/packages/crouter-api/dist/clients/inbox/review/anchors.js +0 -89
  173. package/packages/crouter-api/dist/clients/inbox/review/comments-client.js +0 -103
  174. package/packages/crouter-api/dist/clients/inbox/review/companion-pane.js +0 -109
  175. package/packages/crouter-api/dist/clients/inbox/review/document-surface.js +0 -1268
  176. package/packages/crouter-api/dist/clients/inbox/review/frame.js +0 -309
  177. package/packages/crouter-api/dist/clients/inbox/review/keys.js +0 -133
  178. package/packages/crouter-api/dist/clients/inbox/review/launch.js +0 -170
  179. package/packages/crouter-api/dist/clients/inbox/review/live-source.js +0 -160
  180. package/packages/crouter-api/dist/clients/inbox/review/nvim.js +0 -43
  181. package/packages/crouter-api/dist/clients/inbox/review/remap.js +0 -157
  182. package/packages/crouter-api/dist/clients/inbox/review/review-client.js +0 -125
  183. package/packages/crouter-api/dist/clients/inbox/review/state.js +0 -315
  184. package/packages/crouter-api/dist/clients/inbox/review-adapter.js +0 -43
  185. package/packages/crouter-api/dist/core/review/signal.js +0 -12
  186. package/packages/crouter-api/dist/core/termrender/code-doc.js +0 -92
  187. /package/dist/clients/{inbox/review/roundtrip.d.ts → editor-roundtrip.d.ts} +0 -0
@@ -63,8 +63,8 @@ function commentPreview(comment) {
63
63
  comment_id: comment.comment_id,
64
64
  status: comment.status,
65
65
  revision: comment.revision,
66
- anchor: { line: comment.anchor.line, end_line: comment.anchor.end_line },
67
- anchor_state: comment.anchor_state,
66
+ quote: comment.anchor.quote,
67
+ detached: comment.location === null,
68
68
  author: comment.author,
69
69
  updated_by: comment.updated_by,
70
70
  created_at: comment.created_at,
@@ -79,7 +79,7 @@ const humanReviewNew = defineLeaf({
79
79
  help: {
80
80
  name: 'human review new',
81
81
  summary: 'queue a live document review and return its ticket handle immediately',
82
- guide: 'The person reviews the document in the attach viewer alongside a collaborating companion agent. The daemon reads the document as you and snapshots its current revision into the review. When the person submits, their edits are saved as a new revision of the document and the approval is pushed to your inbox. If the document gets a new revision while the review is open, the save is refused as `stale_revision` and the review stays open; do not edit a document while it is under review.',
82
+ guide: 'The person reviews the document in the browser at the canvas host, with a companion agent that edits the document itself while they comment; there is no file or snapshot to review. Needs a cloud runtime with a canvas host, otherwise it fails with `no_canvas_host`. When the person approves, the approval, with the comments and their quotes, is pushed to your inbox.',
83
83
  params: [
84
84
  { kind: 'positional', name: 'document', type: 'string', required: true, constraint: 'The document to review: a name, `<owner>/<name>` or id, `[[ ]]` optional. It must have one head; merge several heads first.' },
85
85
  { kind: 'flag', name: 'subtitle', type: 'string', required: true, constraint: 'One plain-English sentence stating the review needed and why it matters.' },
@@ -87,14 +87,12 @@ const humanReviewNew = defineLeaf({
87
87
  output: [
88
88
  { name: 'review_id', type: 'string', required: true, constraint: 'Daemon-owned review id for the document, comments, and companion.' },
89
89
  { name: 'document', type: 'string', required: true, constraint: 'The reviewed document\'s `<owner>/<name>`.' },
90
- { name: 'review_dir', type: 'string', required: true, constraint: 'Directory containing the review\'s document.md snapshot and immutable result.json.' },
91
90
  { name: 'result_path', type: 'string', required: true, constraint: 'The immutable terminal result path: <review_dir>/result.json.' },
92
- { name: 'follow_up', type: 'string', required: true, constraint: 'The review remains live for the person and companion; approval is delivered to the origin inbox.' },
93
91
  ],
94
92
  outputKind: 'object',
95
93
  effects: [
96
- 'Records your read of the document and creates the durable review, its `document.md` snapshot, and the companion session fork.',
97
- 'On submit, a changed snapshot becomes a new revision authored by the person; this command does not submit an approval.',
94
+ 'Records your read of the document as the review base and creates the durable review and the companion session fork.',
95
+ 'This command does not submit an approval.',
98
96
  ],
99
97
  },
100
98
  run: async (input) => {
@@ -109,24 +107,23 @@ const humanReviewNew = defineLeaf({
109
107
  return {
110
108
  review_id: review.review_id,
111
109
  document: review.document ?? null,
112
- review_dir: review.review_dir,
113
110
  result_path: `${review.review_dir}/result.json`,
114
- follow_up: 'The review is live for the person in the attach viewer with its companion agent. Approval is pushed to the origin inbox when submitted.',
115
111
  };
116
112
  },
117
113
  });
118
114
  const humanReviewCommentCreate = defineLeaf({
119
115
  name: 'create',
120
116
  description: 'add an anchored review comment',
121
- whenToUse: 'recording a new finding or instruction against one or more document lines.',
117
+ whenToUse: 'recording a new finding or instruction against a passage of the document.',
122
118
  help: {
123
119
  name: 'human review comment create',
124
- summary: 'add a daemon-owned comment anchored to document lines',
125
- guide: 'Without --review, the daemon targets the calling companion node\'s open review. Comment text is supplied on stdin; agent comments use whole-line anchors.',
120
+ summary: 'add a daemon-owned comment anchored to quoted document text',
121
+ guide: 'Without --review, the daemon targets the calling companion node\'s open review. Comment text is supplied on stdin; the quote is matched against the document\'s rendered text, whitespace collapsed.',
126
122
  params: [
127
123
  { kind: 'flag', name: 'review', type: 'string', required: false, constraint: 'Review id. Omit only to target the calling companion node\'s open review.' },
128
- { kind: 'flag', name: 'line', type: 'int', required: true, constraint: 'First 1-based document line in the anchor.' },
129
- { kind: 'flag', name: 'end-line', type: 'int', required: false, constraint: 'Last 1-based document line in the anchor. Default: --line.' },
124
+ { kind: 'flag', name: 'quote', type: 'string', required: true, constraint: 'Text to anchor to; it must occur in the current rendered document. When it occurs more than once, the error lists each occurrence with its context: pass --prefix or --suffix.' },
125
+ { kind: 'flag', name: 'prefix', type: 'string', required: false, constraint: 'Up to 32 characters immediately before the quote.' },
126
+ { kind: 'flag', name: 'suffix', type: 'string', required: false, constraint: 'Up to 32 characters immediately after the quote.' },
130
127
  { kind: 'flag', name: 'deliver', type: 'enum', choices: ['wake', 'quiet'], required: false, constraint: 'wake interrupts the companion now; quiet leaves a durable message for its next turn. Default: wake unless the caller is the companion.' },
131
128
  { kind: 'stdin', name: 'text', required: true, constraint: 'Non-empty comment text.' },
132
129
  ],
@@ -144,11 +141,13 @@ const humanReviewCommentCreate = defineLeaf({
144
141
  },
145
142
  run: async (input, context) => {
146
143
  const reviewId = input['review'];
147
- const line = input['line'];
148
- const endLine = input['endLine'];
149
144
  const result = await cliClient().createReviewComment(reviewId, {
150
145
  text: requireCommentText(input['text'], 'create'),
151
- anchor: { line, end_line: endLine ?? line },
146
+ anchor: {
147
+ quote: input['quote'],
148
+ ...(typeof input['prefix'] === 'string' ? { prefix: input['prefix'] } : {}),
149
+ ...(typeof input['suffix'] === 'string' ? { suffix: input['suffix'] } : {}),
150
+ },
152
151
  actor_node_id: nodeActor(),
153
152
  ...(explicitDeliver(input, context) === undefined ? {} : { deliver: explicitDeliver(input, context) }),
154
153
  });
@@ -231,7 +230,7 @@ function commentMutationLeaf(verb) {
231
230
  { name: 'comment_id', type: 'string', required: true, constraint: 'Daemon-owned comment id.' },
232
231
  { name: 'status', type: 'string', required: true, constraint: 'Current comment status: open, resolved, or deleted.' },
233
232
  { name: 'revision', type: 'integer', required: true, constraint: 'Current per-comment revision.' },
234
- { name: 'anchor', type: 'object', required: true, constraint: 'Current whole-line anchor.' },
233
+ { name: 'anchor', type: 'object', required: true, constraint: 'Quoted text anchor.' },
235
234
  { name: 'author', type: 'object', required: true, constraint: 'Daemon-derived human or node attribution.' },
236
235
  { name: 'text', type: 'string', required: true, constraint: 'Stored full comment text.' },
237
236
  { name: 'changed', type: 'boolean', required: true, constraint: 'Whether this invocation changed the comment.' },
@@ -7,7 +7,7 @@ import { formatGesture, matchesPiTuiInput, } from '../../../../core/keybindings/
7
7
  import { writeClipboardTextEverywhere } from '../../../../core/clipboard-text.js';
8
8
  import { runTuiPage } from '../../../../core/tui/page-host.js';
9
9
  import { PAGE_CHROME_ROWS, columns, framed, pageFrame, theme, } from '../../../../core/tui/panel.js';
10
- import { editBufferInEditor } from '../../../../clients/inbox/review/roundtrip.js';
10
+ import { editBufferInEditor } from '../../../../clients/editor-roundtrip.js';
11
11
  import { PLANNED_EVENTS } from '../resolve.js';
12
12
  import { moveDoc, readBody, readOnlyReason, toggleUnlisted, writeBody, writePreview, writeRules, } from './actions.js';
13
13
  import { axesOf, cycleAxis, cycleFacet, facetsOf, payloadRowOf, railEnter, railRowKey, railRowsOf, renderRail, setTypedAxis, typedAxisValue, } from './rail-panel.js';
@@ -6,7 +6,7 @@
6
6
  /** The canvas schema version this build supports: the number of the highest delta in `schema-pg/` (the baseline
7
7
  * `schema-pg.sql` is version 1). `scripts/install-runtime.mjs` reads this module from a candidate generation to refuse
8
8
  * one below the live database's `schema_min_reader`. */
9
- export const CANVAS_SCHEMA_VERSION = 24;
9
+ export const CANVAS_SCHEMA_VERSION = 25;
10
10
  /** The Postgres schema holding the canvas tables: `CRTR_DATABASE_SCHEMA` (`crtr` in the cloud deploy). Unset or empty
11
11
  * means the role's own search_path (`public` on a Mac and on a VM). A name that is not a plain identifier is an error:
12
12
  * it is put in a `search_path` connection option. */
@@ -191,12 +191,8 @@ function block(node, context) {
191
191
  const contents = () => flow(node.children, context);
192
192
  switch (node.tag) {
193
193
  case 'Page': return contents();
194
- case 'Step': {
195
- const title = node.props['title'];
196
- const body = contents();
197
- const heading = typeof title === 'string' && title.trim() !== '' ? `## ${markdownText(title.trim())}` : '';
198
- return [heading, body].filter((part) => part !== '').join('\n\n');
199
- }
194
+ // A step's title is the question's own heading again, so only its body projects.
195
+ case 'Step': return contents();
200
196
  case 'p': return cleanInline(inline(node.children, context));
201
197
  case 'h1':
202
198
  case 'h2':
@@ -7,18 +7,9 @@ import { isBlobRequestPath, readRequestText } from './request-files.js';
7
7
  import { validatePageResponses, validatePartialPageResponses } from './page-schema.js';
8
8
  import { signalInboxActivity } from './root.js';
9
9
  import { createPageRequest, getRequestByDirectory, presentationDir, publishPageRevisionTo, revisePageRequest, writeProgress as writeRequestProgress } from './requests.js';
10
- const feedbackCommentSchema = z.object({ id: z.string().min(1), line: z.number().int().positive(), endLine: z.number().int().positive(), quote: z.string().optional(), colStart: z.number().int().nonnegative().optional(), colEnd: z.number().int().nonnegative().optional(), lineText: z.string(), comment: z.string().min(1), createdAt: z.string().min(1) }).strict();
10
+ const feedbackCommentSchema = z.object({ id: z.string().min(1), quote: z.string().default(''), comment: z.string().min(1), createdAt: z.string().min(1), resolved: z.boolean().default(false), detached: z.boolean().optional() }).passthrough();
11
11
  const iso = z.string().datetime({ offset: true });
12
- const feedbackSchema = z.object({ file: z.string().min(1).refine(isAbsolute, 'file must be absolute').refine((file) => resolve(file) === file, 'file must be canonical'), submitted: z.literal(true), approved: z.boolean(), comments: z.array(feedbackCommentSchema), submittedAt: iso, savedAt: iso, reviewId: z.string().optional(), changed: z.boolean().optional(), baselineSha256: z.string().optional(), approvedSha256: z.string().optional(), companionNodeId: z.string().optional(), commentsTotal: z.number().int().nonnegative().optional(), commentsUnresolved: z.number().int().nonnegative().optional() }).strict().superRefine((result, ctx) => {
13
- result.comments.forEach((comment, index) => {
14
- if (comment.endLine < comment.line)
15
- ctx.addIssue({ code: 'custom', message: 'endLine must be >= line', path: ['comments', index, 'endLine'] });
16
- if ((comment.colStart === undefined) !== (comment.colEnd === undefined))
17
- ctx.addIssue({ code: 'custom', message: 'columns must be supplied together', path: ['comments', index] });
18
- if (comment.line === comment.endLine && comment.colStart !== undefined && comment.colEnd !== undefined && comment.colEnd <= comment.colStart)
19
- ctx.addIssue({ code: 'custom', message: 'colEnd must exceed colStart', path: ['comments', index, 'colEnd'] });
20
- });
21
- });
12
+ const feedbackSchema = z.object({ file: z.string().min(1).refine(isAbsolute, 'file must be absolute').refine((file) => resolve(file) === file, 'file must be canonical'), submitted: z.literal(true), approved: z.boolean(), comments: z.array(feedbackCommentSchema), submittedAt: iso, savedAt: iso, document: z.object({ id: z.string(), name: z.string(), base_revision: z.string().nullable(), approved_revision: z.string().nullable() }).nullable().optional(), reviewId: z.string().optional(), changed: z.boolean().optional(), baselineSha256: z.string().optional(), approvedSha256: z.string().optional(), companionNodeId: z.string().optional(), commentsTotal: z.number().int().nonnegative().optional(), commentsUnresolved: z.number().int().nonnegative().optional() }).strict();
22
13
  const slotResponseSchema = z.record(z.string(), z.unknown());
23
14
  const pageResultSchema = z.object({ schema: z.literal('crtr.page-response/v1'), kind: z.literal('page'), responses: z.record(z.string(), slotResponseSchema), summary: z.string(), completedAt: iso, actor: z.string().optional() }).strict();
24
15
  const pageProgressSchema = z.object({ kind: z.literal('page'), responses: z.record(z.string(), slotResponseSchema), savedAt: iso }).strict();
@@ -8,7 +8,6 @@ export const ATTACH_CONTROL_BINDINGS = [
8
8
  { menuId: 'crtr.tmux.menu.attach.model-ladder.next', actionId: 'crtr.attach.model-ladder.next' },
9
9
  { menuId: 'crtr.tmux.menu.attach.model-ladder.previous', actionId: 'crtr.attach.model-ladder.previous' },
10
10
  { menuId: 'crtr.tmux.menu.attach.command.inspect', actionId: 'crtr.attach.command.inspect' },
11
- { menuId: 'crtr.tmux.menu.attach.file-review', actionId: 'crtr.attach.file-review' },
12
11
  { menuId: 'crtr.tmux.menu.attach.profile-files', actionId: 'crtr.attach.profile-files' },
13
12
  { menuId: 'crtr.tmux.menu.attach.search', actionId: 'crtr.attach.search' },
14
13
  { menuId: 'crtr.tmux.menu.attach.whip', actionId: 'crtr.attach.whip' },
@@ -22,7 +22,7 @@ function menuEntry(action, name, description, defaults, contexts, globalDefaults
22
22
  }
23
23
  function attachEntry(menuId, actionId, name, description,
24
24
  // Empty hides the row from the attach submenu while the action stays bindable
25
- // and reachable by its direct gesture — file review lives on the top-level menu.
25
+ // and reachable by its direct gesture.
26
26
  menuDefaults, directDefaults) {
27
27
  return [
28
28
  b(menuId, 'Attach', name, description, menuDefaults, 'tmux-menu-selector', ['tmux.menu.attach'], undefined, { field: 'menu', pairedId: actionId }),
@@ -48,7 +48,6 @@ export const BINDING_CATALOG = Object.freeze([
48
48
  ...menuEntry('detach', 'Demote and close viewer', 'Demote the focused node and close its viewer; its broker keeps running off-screen.', ['shift+d'], ['tmux.menu']),
49
49
  ...menuEntry('close-subtree', 'Close subtree', 'Close the focused node and its subtree.', ['x'], ['tmux.menu']),
50
50
  ...menuEntry('background-bash', 'Background running bash', 'Hand the focused node’s running bash command to its background job system.', ['b'], ['tmux.menu']),
51
- ...menuEntry('file-review', 'Review a file', 'Open a line-anchored review of a file named in the transcript.', ['v'], ['tmux.menu']),
52
51
  ...menuEntry('pin', 'Pin conversation', 'Pin or unpin this conversation in the canvas navigator.', ['p'], ['tmux.menu']),
53
52
  ...menuEntry('show', 'Inspect node', 'Open the focused node’s inspection menu.', ['i'], ['tmux.menu']),
54
53
  ...menuEntry('view-settings', 'Display settings', 'Open the viewer display-settings menu.', ['z'], ['tmux.menu']),
@@ -86,7 +85,6 @@ export const BINDING_CATALOG = Object.freeze([
86
85
  ...attachEntry('crtr.tmux.menu.attach.model-ladder.next', 'crtr.attach.model-ladder.next', 'Next model', 'Move to the next model ladder rung.', [']'], ['alt+m']),
87
86
  ...attachEntry('crtr.tmux.menu.attach.model-ladder.previous', 'crtr.attach.model-ladder.previous', 'Previous model', 'Move to the previous model ladder rung.', ['['], ['alt+shift+m']),
88
87
  ...attachEntry('crtr.tmux.menu.attach.command.inspect', 'crtr.attach.command.inspect', 'Inspect loaded command', 'Open the loaded slash command’s expanded prompt.', ['h'], ['alt+shift+h']),
89
- ...attachEntry('crtr.tmux.menu.attach.file-review', 'crtr.attach.file-review', 'Review a file', 'Open a line-anchored review of a file named in the transcript.', [], ['alt+shift+r']),
90
88
  ...attachEntry('crtr.tmux.menu.attach.profile-files', 'crtr.attach.profile-files', 'Search profile files', 'Fuzzy-match path segments across the node family’s working directories, their context directories (files), profile projects and the profile’s own directory; Ctrl+Y copies a selected path.', ['f'], ['ctrl+f']),
91
89
  ...attachEntry('crtr.tmux.menu.attach.search', 'crtr.attach.search', 'Search transcript', 'Search the transcript as it is currently displayed — folded tool output is not searched until it is unfolded.', ['/'], ['alt+/']),
92
90
  ...attachEntry('crtr.tmux.menu.attach.reload-viewer', 'crtr.attach.reload-viewer', 'Reload viewer', 'Restart this viewer in place on the installed release.', [], []),
@@ -0,0 +1,91 @@
1
+ import { unified } from 'unified';
2
+ import remarkParse from 'remark-parse';
3
+ import remarkGfm from 'remark-gfm';
4
+ import { ANCHOR_CONTEXT_MAX, COMMENT_QUOTE_MAX, ReviewOperationError } from './types.js';
5
+ const parser = unified().use(remarkParse).use(remarkGfm);
6
+ const BLOCK_JOIN = new Set(['root', 'blockquote', 'footnoteDefinition']);
7
+ const LINE_JOIN = new Set(['list', 'table', 'tableRow']);
8
+ function collapse(text) {
9
+ return text.replace(/\s+/g, ' ').trim();
10
+ }
11
+ function render(node) {
12
+ if (node.type === 'text' || node.type === 'inlineCode' || node.type === 'code')
13
+ return node.value ?? '';
14
+ if (node.type === 'break')
15
+ return '\n';
16
+ const kids = node.children ?? [];
17
+ const sep = BLOCK_JOIN.has(node.type) ? '\n\n' : LINE_JOIN.has(node.type) ? '\n' : '';
18
+ const parts = kids.map(render);
19
+ if (sep === '' && kids.some((kid) => kid.type === 'paragraph' || kid.type === 'list' || kid.type === 'listItem'))
20
+ return parts.join('\n');
21
+ return parts.join(sep);
22
+ }
23
+ /** The text a reader sees: markdown syntax removed, blocks separated, whitespace collapsed. */
24
+ export function renderedText(markdown) {
25
+ return collapse(render(parser.parse(markdown)));
26
+ }
27
+ export function normalizeAnchor(anchor) {
28
+ const quote = collapse(anchor.quote);
29
+ const violations = [];
30
+ if (quote === '')
31
+ violations.push('quote must not be empty');
32
+ if (quote.length > COMMENT_QUOTE_MAX)
33
+ violations.push(`quote exceeds ${COMMENT_QUOTE_MAX} characters`);
34
+ const offset = anchor.offset ?? 0;
35
+ if (!Number.isSafeInteger(offset) || offset < 0)
36
+ violations.push('offset must be a non-negative integer');
37
+ if (violations.length > 0)
38
+ throw new ReviewOperationError('invalid_anchor', 'comment anchor is invalid', { violations });
39
+ return {
40
+ quote,
41
+ prefix: collapse(anchor.prefix ?? '').slice(-ANCHOR_CONTEXT_MAX),
42
+ suffix: collapse(anchor.suffix ?? '').slice(0, ANCHOR_CONTEXT_MAX),
43
+ offset,
44
+ };
45
+ }
46
+ function commonSuffix(a, b) {
47
+ let n = 0;
48
+ while (n < a.length && n < b.length && a[a.length - 1 - n] === b[b.length - 1 - n])
49
+ n += 1;
50
+ return n;
51
+ }
52
+ function commonPrefix(a, b) {
53
+ let n = 0;
54
+ while (n < a.length && n < b.length && a[n] === b[n])
55
+ n += 1;
56
+ return n;
57
+ }
58
+ /** Find an anchor in the current rendered text: every exact quote match, best prefix+suffix agreement, then nearest offset. Null = detached. */
59
+ export function resolveAnchor(text, anchor) {
60
+ let best = null;
61
+ for (let at = text.indexOf(anchor.quote); at !== -1; at = text.indexOf(anchor.quote, at + 1)) {
62
+ const score = commonSuffix(text.slice(Math.max(0, at - anchor.prefix.length), at), anchor.prefix)
63
+ + commonPrefix(text.slice(at + anchor.quote.length, at + anchor.quote.length + anchor.suffix.length), anchor.suffix);
64
+ const distance = Math.abs(at - anchor.offset);
65
+ if (best === null || score > best.score || (score === best.score && distance < best.distance))
66
+ best = { start: at, score, distance };
67
+ }
68
+ return best === null ? null : { start: best.start, end: best.start + anchor.quote.length };
69
+ }
70
+ /** Occurrences of a quote with 32 characters of context each, for a caller that must disambiguate. */
71
+ export function quoteOccurrences(text, quote) {
72
+ const out = [];
73
+ for (let at = text.indexOf(quote); at !== -1; at = text.indexOf(quote, at + 1)) {
74
+ out.push({ offset: at, prefix: text.slice(Math.max(0, at - ANCHOR_CONTEXT_MAX), at), suffix: text.slice(at + quote.length, at + quote.length + ANCHOR_CONTEXT_MAX) });
75
+ }
76
+ return out;
77
+ }
78
+ /** Validate a new anchor against the current document and fill context the caller left out. */
79
+ export function anchorInDocument(markdown, input) {
80
+ const anchor = normalizeAnchor(input);
81
+ const text = renderedText(markdown);
82
+ const found = quoteOccurrences(text, anchor.quote);
83
+ if (found.length === 0)
84
+ throw new ReviewOperationError('quote_not_found', 'the quoted text does not occur in the current document', { quote: anchor.quote });
85
+ if (found.length > 1 && input.prefix === undefined && input.suffix === undefined && input.offset === undefined) {
86
+ throw new ReviewOperationError('invalid_anchor', 'the quoted text occurs more than once; pass prefix or suffix', { occurrences: found });
87
+ }
88
+ if (input.prefix === undefined && input.suffix === undefined)
89
+ return { ...anchor, prefix: found[0].prefix, suffix: found[0].suffix, offset: found[0].offset };
90
+ return anchor;
91
+ }
@@ -1,8 +1,8 @@
1
1
  import { randomBytes } from 'node:crypto';
2
- import { withCanvasWrite, openDb } from '../canvas/db.js';
2
+ import { afterCommit, withCanvasWrite, openDb } from '../canvas/db.js';
3
3
  import { nowIso } from '../fs-utils.js';
4
- import { signalReviewActivity } from './signal.js';
5
- import { COMMENT_EVENTS_PAGE_DEFAULT, COMMENT_EVENTS_PAGE_MAX, COMMENT_LINE_TEXT_MAX, COMMENT_TEXT_MAX, LIVE_COMMENTS_MAX, ReviewOperationError, } from './types.js';
4
+ import { brokerSignalBus } from '../../daemon/broker-signals/bus.js';
5
+ import { COMMENT_EVENTS_PAGE_DEFAULT, COMMENT_EVENTS_PAGE_MAX, COMMENT_TEXT_MAX, LIVE_COMMENTS_MAX, ReviewOperationError, } from './types.js';
6
6
  function commentFromRow(row) {
7
7
  return {
8
8
  comment_id: row.comment_id,
@@ -11,15 +11,11 @@ function commentFromRow(row) {
11
11
  revision: row.revision,
12
12
  text: row.text,
13
13
  anchor: {
14
- line: row.anchor_line,
15
- end_line: row.anchor_end_line,
16
- ...(row.anchor_col_start === null ? {} : { col_start: row.anchor_col_start }),
17
- ...(row.anchor_col_end === null ? {} : { col_end: row.anchor_col_end }),
18
- ...(row.anchor_quote === null ? {} : { quote: row.anchor_quote }),
14
+ quote: row.anchor_quote,
15
+ prefix: row.anchor_prefix,
16
+ suffix: row.anchor_suffix,
17
+ offset: Number(row.anchor_offset),
19
18
  },
20
- anchor_state: row.anchor_state,
21
- anchor_line_text: row.anchor_line_text,
22
- anchor_doc_hash: row.anchor_doc_hash,
23
19
  author: { kind: row.author_kind, node_id: row.author_node_id },
24
20
  updated_by: { kind: row.updated_by_kind, node_id: row.updated_by_node_id },
25
21
  created_at: row.created_at,
@@ -66,17 +62,6 @@ function trimText(text) {
66
62
  }
67
63
  return trimmed;
68
64
  }
69
- function truncateUtf8(text, maxBytes) {
70
- if (Buffer.byteLength(text, 'utf8') <= maxBytes)
71
- return text;
72
- const marker = '… [truncated]';
73
- const markerBytes = Buffer.byteLength(marker, 'utf8');
74
- const bytes = Buffer.from(text, 'utf8');
75
- let end = Math.max(0, maxBytes - markerBytes);
76
- while (end > 0 && (bytes[end] & 0xc0) === 0x80)
77
- end -= 1;
78
- return `${bytes.subarray(0, end).toString('utf8')}${marker}`;
79
- }
80
65
  async function getStoredComment(db, commentIdValue) {
81
66
  return await db.prepare('SELECT * FROM review_comments WHERE comment_id = ?').get(commentIdValue) ?? null;
82
67
  }
@@ -120,10 +105,10 @@ async function updateComment(db, row, fields, actor, at) {
120
105
  `).run(fields.status ?? row.status, revision, fields.text ?? row.text, actor.kind, actor.node_id, at, fields.resolved_at === undefined ? row.resolved_at : fields.resolved_at, fields.deleted_at === undefined ? row.deleted_at : fields.deleted_at, row.comment_id);
121
106
  return { ...row, ...fields, revision, updated_by_kind: actor.kind, updated_by_node_id: actor.node_id, updated_at: at };
122
107
  }
123
- function completeMutation(result) {
124
- if (result.changed)
125
- signalReviewActivity();
126
- return result;
108
+ /** Tell every process listening on `crtr_signal` (and this one, at commit) that a review changed. Call inside the mutating transaction: a rollback sends nothing. */
109
+ export async function signalReviewChange(db, reviewId) {
110
+ await db.prepare('SELECT pg_notify(?, ?)').get('crtr_signal', `review:${reviewId}`);
111
+ afterCommit(() => brokerSignalBus.markSignal('review', reviewId));
127
112
  }
128
113
  export async function createComment(args) {
129
114
  const result = await withCanvasWrite(async (db) => {
@@ -136,19 +121,17 @@ export async function createComment(args) {
136
121
  });
137
122
  }
138
123
  const text = trimText(args.text);
139
- const lineText = truncateUtf8(args.line_text, COMMENT_LINE_TEXT_MAX);
140
124
  const at = nowIso();
141
125
  let id = commentId();
142
126
  while (await getStoredComment(db, id) !== null)
143
127
  id = commentId();
144
128
  const inserted = await db.prepare(`
145
129
  INSERT INTO review_comments
146
- (comment_id, review_id, status, revision, text, anchor_line, anchor_end_line,
147
- anchor_col_start, anchor_col_end, anchor_quote, anchor_line_text, anchor_doc_hash, anchor_state,
130
+ (comment_id, review_id, status, revision, text, anchor_quote, anchor_prefix, anchor_suffix, anchor_offset,
148
131
  author_kind, author_node_id, updated_by_kind, updated_by_node_id, created_at,
149
132
  updated_at, resolved_at, deleted_at, created_seq)
150
- VALUES (?, ?, 'open', 1, ?, ?, ?, ?, ?, ?, ?, ?, 'live', ?, ?, ?, ?, ?, ?, NULL, NULL, 0)
151
- `).run(id, args.review_id, text, args.anchor.line, args.anchor.end_line, args.anchor.col_start ?? null, args.anchor.col_end ?? null, args.anchor.quote ?? null, lineText, args.doc_hash, args.actor.kind, args.actor.node_id, args.actor.kind, args.actor.node_id, at, at);
133
+ VALUES (?, ?, 'open', 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, NULL, 0)
134
+ `).run(id, args.review_id, text, args.anchor.quote, args.anchor.prefix, args.anchor.suffix, args.anchor.offset, args.actor.kind, args.actor.node_id, args.actor.kind, args.actor.node_id, at, at);
152
135
  if (inserted.changes !== 1)
153
136
  throw new Error('failed to insert review comment');
154
137
  const row = (await getStoredComment(db, id));
@@ -158,12 +141,12 @@ export async function createComment(args) {
158
141
  actor: args.actor,
159
142
  operation_id: args.operation_id,
160
143
  at,
161
- payload: { text, anchor: args.anchor, line_text: lineText, doc_hash: args.doc_hash },
144
+ payload: { text, anchor: args.anchor },
162
145
  });
163
146
  await db.prepare('UPDATE review_comments SET created_seq = ? WHERE comment_id = ?').run(seq, id);
147
+ await signalReviewChange(db, args.review_id);
164
148
  return { comment: commentFromRow({ ...row, created_seq: seq }), changed: true };
165
149
  });
166
- signalReviewActivity();
167
150
  return result;
168
151
  }
169
152
  export async function editComment(commentIdValue, args) {
@@ -191,9 +174,10 @@ export async function editComment(commentIdValue, args) {
191
174
  anchor: commentFromRow(updated).anchor,
192
175
  },
193
176
  });
177
+ await signalReviewChange(db, updated.review_id);
194
178
  return { comment: commentFromRow(updated), changed: true };
195
179
  });
196
- return completeMutation(result);
180
+ return result;
197
181
  }
198
182
  async function transitionComment(commentIdValue, args, target, kind) {
199
183
  const result = await withCanvasWrite(async (db) => {
@@ -227,9 +211,10 @@ async function transitionComment(commentIdValue, args, target, kind) {
227
211
  anchor: commentFromRow(updated).anchor,
228
212
  },
229
213
  });
214
+ await signalReviewChange(db, updated.review_id);
230
215
  return { comment: commentFromRow(updated), changed: true };
231
216
  });
232
- return completeMutation(result);
217
+ return result;
233
218
  }
234
219
  export async function resolveComment(commentIdValue, args) {
235
220
  return await transitionComment(commentIdValue, args, 'resolved', 'resolved');
@@ -244,10 +229,10 @@ export async function listComments(reviewId, opts) {
244
229
  const db = await openDb();
245
230
  const status = opts?.status;
246
231
  const rows = status === undefined
247
- ? await db.prepare("SELECT * FROM review_comments WHERE review_id = ? AND status != 'deleted' ORDER BY anchor_line, created_seq").all(reviewId)
232
+ ? await db.prepare("SELECT * FROM review_comments WHERE review_id = ? AND status != 'deleted' ORDER BY created_seq").all(reviewId)
248
233
  : status === 'all'
249
- ? await db.prepare('SELECT * FROM review_comments WHERE review_id = ? ORDER BY anchor_line, created_seq').all(reviewId)
250
- : await db.prepare('SELECT * FROM review_comments WHERE review_id = ? AND status = ? ORDER BY anchor_line, created_seq').all(reviewId, status);
234
+ ? await db.prepare('SELECT * FROM review_comments WHERE review_id = ? ORDER BY created_seq').all(reviewId)
235
+ : await db.prepare('SELECT * FROM review_comments WHERE review_id = ? AND status = ? ORDER BY created_seq').all(reviewId, status);
251
236
  return rows.map(commentFromRow);
252
237
  }
253
238
  export async function getComment(commentIdValue) {
@@ -266,17 +251,13 @@ export async function listReviewEvents(reviewId, opts) {
266
251
  return { events, next_since_seq: events.length === 0 ? since : events[events.length - 1].seq };
267
252
  }
268
253
  export async function snapshotCommentsLocked(db, reviewId) {
269
- const rows = await db.prepare("SELECT * FROM review_comments WHERE review_id = ? AND status != 'deleted' ORDER BY anchor_line, created_seq").all(reviewId);
254
+ const rows = await db.prepare("SELECT * FROM review_comments WHERE review_id = ? AND status != 'deleted' ORDER BY created_seq").all(reviewId);
270
255
  const comments = rows.map((row) => ({
271
256
  id: row.comment_id,
272
- line: row.anchor_line,
273
- endLine: row.anchor_end_line,
274
- ...(row.anchor_quote === null ? {} : { quote: row.anchor_quote }),
275
- ...(row.anchor_col_start === null ? {} : { colStart: row.anchor_col_start }),
276
- ...(row.anchor_col_end === null ? {} : { colEnd: row.anchor_col_end }),
277
- lineText: row.anchor_line_text,
257
+ quote: row.anchor_quote,
278
258
  comment: row.text,
279
259
  createdAt: row.created_at,
260
+ resolved: row.status === 'resolved',
280
261
  }));
281
262
  return { comments, total: rows.length, unresolved: rows.filter((row) => row.status === 'open').length };
282
263
  }
@@ -291,6 +272,6 @@ export async function appendDeliveryEvent(args) {
291
272
  (review_id, comment_id, kind, state_change, revision_after, actor_kind, actor_node_id, at, operation_id, payload)
292
273
  VALUES (?, ?, ?, 0, NULL, 'system', NULL, ?, ?, ?)
293
274
  `).run(args.review_id, args.comment_id, args.kind, nowIso(), args.operation_id, json(args.payload));
275
+ await signalReviewChange(db, args.review_id);
294
276
  });
295
- signalReviewActivity();
296
277
  }
@@ -1,6 +1,6 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { conversationIdFromPath, conversationStore, ConversationNotFoundError } from '../conversation-store/index.js';
3
- import { basename, isAbsolute } from 'node:path';
3
+ import { isAbsolute } from 'node:path';
4
4
  import { BrokerClient } from '../broker-client/index.js';
5
5
  import { deleteNode, getNode } from '../canvas/index.js';
6
6
  import { expandModelCandidates } from '../model-routes.js';
@@ -12,7 +12,6 @@ import { spawnNode } from '../runtime/nodes.js';
12
12
  import { SessionManager } from '../runtime/broker-sdk.js';
13
13
  import { isReviewBoundary } from '../runtime/session-visibility.js';
14
14
  import { forkNodeLedger } from '../runtime/ledger.js';
15
- import { isBlobRequestPath } from '../human/request-files.js';
16
15
  import { ReviewOperationError } from './types.js';
17
16
  const EXACT_MODEL_SPEC = /^[^/\s:]+\/[^/\s:]+:(?:off|minimal|low|medium|high|xhigh|max)$/;
18
17
  const BIND_POLL_MS = 100;
@@ -134,11 +133,8 @@ export async function captureOrigin(originNodeId, deps = {}) {
134
133
  }
135
134
  /** Create the ordinary, promptless companion node. Realization owns its launch. */
136
135
  export async function spawnReviewCompanion(spec) {
137
- // The branch is a conversation transcript path, always absolute. The target is a local file, or on a cloud role the
138
- // review's `requests/<id>/document.md` blob key, which is relative by construction.
139
- if (!isAbsolute(spec.branchFile) || !(isAbsolute(spec.targetFile) || isBlobRequestPath(spec.targetFile))) {
140
- throw new Error('review companion requires an absolute branch path and an absolute or request-blob target');
141
- }
136
+ if (!isAbsolute(spec.branchFile))
137
+ throw new Error('review companion requires an absolute branch path');
142
138
  if (!EXACT_MODEL_SPEC.test(spec.modelSpec)) {
143
139
  throw new Error('review companion requires an exact model spec');
144
140
  }
@@ -167,9 +163,9 @@ export async function spawnReviewCompanion(spec) {
167
163
  review_id: spec.reviewId,
168
164
  origin_node_id: spec.originNodeId,
169
165
  branch_file: spec.branchFile,
170
- target_file: spec.targetFile,
166
+ target_file: spec.documentName,
171
167
  },
172
- name: `review ${basename(spec.targetFile)}`,
168
+ name: `review ${spec.documentName}`,
173
169
  launch,
174
170
  });
175
171
  try {
@@ -2,7 +2,9 @@ import { createHash } from 'node:crypto';
2
2
  import { statSync } from 'node:fs';
3
3
  import { isBlobRequestPath, readRequestFileIfPresent } from '../human/request-files.js';
4
4
  import { documentLines } from '../document-lines.js';
5
- import { COMMENT_QUOTE_MAX, ReviewOperationError, } from './types.js';
5
+ import { ReviewOperationError } from './types.js';
6
+ import { get as getBody } from '../graph/bodies.js';
7
+ import { documentById, heads } from '../graph/documents.js';
6
8
  const REVIEW_SOURCE_MAX_BYTES = 2 * 1024 * 1024;
7
9
  function sourceUnreadable(file, phase, reason) {
8
10
  throw new ReviewOperationError('source_unreadable', 'review source is unreadable', { phase, reason, file });
@@ -49,95 +51,21 @@ export async function readReviewSource(file, phase = 'submit') {
49
51
  lines: documentLines(text),
50
52
  };
51
53
  }
52
- async function requireDocumentSource(review, expected_doc_hash) {
53
- const source = await readReviewSource(review.file, 'comment');
54
- if (source.sha256 !== expected_doc_hash) {
55
- throw new ReviewOperationError('stale_document', 'review document changed since it was rendered', {
56
- reason: 'document_changed',
57
- expected_sha256: expected_doc_hash,
58
- actual_sha256: source.sha256,
59
- });
54
+ /** The review's live text: a document review reads the document's current head, a file review its snapshot. */
55
+ export async function currentReviewText(db, review) {
56
+ if (review.document_id !== null) {
57
+ const head = (await heads(db, await documentById(db, review.document_id)))[0];
58
+ const body = head === undefined ? null : await getBody(db, head.body_hash);
59
+ if (body === null)
60
+ throw new ReviewOperationError('source_unreadable', 'review document has no body', { phase: 'comment', reason: 'missing', file: review.file });
61
+ return body;
60
62
  }
61
- if (source.sha256 !== review.anchor_base_sha256) {
62
- throw new ReviewOperationError('stale_document', 'review comment ranges have not been remapped to the current document', {
63
- reason: 'anchor_base_stale',
64
- expected_sha256: review.anchor_base_sha256,
65
- actual_sha256: source.sha256,
66
- });
67
- }
68
- return source;
69
- }
70
- /** Require both the caller's rendered source and the persisted range coordinate base to be current. */
71
- export async function requireCurrentDocument(review, expected_doc_hash) {
72
- return requireDocumentSource(review, expected_doc_hash);
63
+ return new TextDecoder().decode((await readReviewSource(review.file, 'comment')).bytes);
73
64
  }
74
- /** Verify a create-time source precondition from the review row held by the caller's canvas write transaction. */
75
- export async function requireCurrentDocumentLocked(db, review_id, expected_doc_hash) {
76
- const review = await db.prepare("SELECT file, anchor_base_sha256 FROM human_requests WHERE request_id = ? AND kind = 'review' AND state = 'open'").get(review_id);
77
- if (review === undefined) {
65
+ /** Same as {@link currentReviewText}, for the review row held by the caller's canvas write transaction. */
66
+ export async function currentReviewTextLocked(db, review_id) {
67
+ const review = await db.prepare("SELECT file, document_id FROM human_requests WHERE request_id = ? AND kind = 'review' AND state = 'open'").get(review_id);
68
+ if (review === undefined)
78
69
  throw new ReviewOperationError('unknown_review', 'review was not found', { received: review_id });
79
- }
80
- return requireDocumentSource(review, expected_doc_hash);
81
- }
82
- /** Reject malformed ranges rather than normalizing them into a different anchor. */
83
- export function validateAnchorShape(anchor) {
84
- const violations = [];
85
- const hasStart = anchor.col_start !== undefined;
86
- const hasEnd = anchor.col_end !== undefined;
87
- if (!Number.isSafeInteger(anchor.line) || anchor.line < 1)
88
- violations.push('line must be a positive integer');
89
- if (!Number.isSafeInteger(anchor.end_line) || anchor.end_line < 1)
90
- violations.push('end_line must be a positive integer');
91
- if (Number.isSafeInteger(anchor.line) && Number.isSafeInteger(anchor.end_line) && anchor.end_line < anchor.line) {
92
- violations.push('end_line must be greater than or equal to line');
93
- }
94
- if (hasStart !== hasEnd)
95
- violations.push('col_start and col_end must be provided together');
96
- if (hasStart && (!Number.isSafeInteger(anchor.col_start) || anchor.col_start < 0))
97
- violations.push('col_start must be a non-negative integer');
98
- if (hasEnd && (!Number.isSafeInteger(anchor.col_end) || anchor.col_end < 0))
99
- violations.push('col_end must be a non-negative integer');
100
- if (hasStart
101
- && hasEnd
102
- && anchor.line === anchor.end_line
103
- && Number.isSafeInteger(anchor.col_start)
104
- && Number.isSafeInteger(anchor.col_end)
105
- && anchor.col_end <= anchor.col_start) {
106
- violations.push('col_end must be greater than col_start for a single-line anchor');
107
- }
108
- if (anchor.quote !== undefined && typeof anchor.quote !== 'string')
109
- violations.push('quote must be a string');
110
- if (typeof anchor.quote === 'string' && Buffer.byteLength(anchor.quote, 'utf8') > COMMENT_QUOTE_MAX) {
111
- violations.push(`quote exceeds ${COMMENT_QUOTE_MAX} bytes`);
112
- }
113
- if (violations.length > 0) {
114
- throw new ReviewOperationError('invalid_anchor', 'comment anchor is invalid', { violations });
115
- }
116
- }
117
- function isUtf8Boundary(bytes, offset) {
118
- return offset === bytes.length || (bytes[offset] & 0xc0) !== 0x80;
119
- }
120
- /** Capture the full source range used to render an anchor, without silently clamping it. */
121
- export function captureAnchorText(lines, anchor) {
122
- validateAnchorShape(anchor);
123
- if (anchor.line > lines.length || anchor.end_line > lines.length) {
124
- throw new ReviewOperationError('anchor_out_of_range', 'comment anchor exceeds the reviewed document', {
125
- line_count: lines.length,
126
- requested: { line: anchor.line, end_line: anchor.end_line },
127
- });
128
- }
129
- if (anchor.col_start !== undefined && anchor.col_end !== undefined) {
130
- const startLine = Buffer.from(lines[anchor.line - 1], 'utf8');
131
- const endLine = Buffer.from(lines[anchor.end_line - 1], 'utf8');
132
- if (anchor.col_start > startLine.length
133
- || anchor.col_end > endLine.length
134
- || !isUtf8Boundary(startLine, anchor.col_start)
135
- || !isUtf8Boundary(endLine, anchor.col_end)) {
136
- throw new ReviewOperationError('anchor_out_of_range', 'comment anchor columns exceed the reviewed document', {
137
- line_count: lines.length,
138
- requested: { line: anchor.line, end_line: anchor.end_line },
139
- });
140
- }
141
- }
142
- return lines.slice(anchor.line - 1, anchor.end_line).join('\n');
70
+ return currentReviewText(db, review);
143
71
  }