review-workspace 1.10.2 → 1.13.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.
@@ -1,28 +1,28 @@
1
1
  import { mkdirSync, writeFileSync } from 'node:fs';
2
2
  import { join } from 'node:path';
3
+ import { isOpenChangeRequest } from "../questions/questions-log.js";
3
4
  import { buildHandoffMarkdown } from "./build-handoff-markdown.js";
4
- import { ensureGitignoreExcludesHandoff } from "./ensure-gitignore.js";
5
- import { DEFAULT_REPO_PATH_CACHE_PATH, resolveRepoPath } from "./repo-path-cache.js";
5
+ import { ensureGitExcludesHandoff } from "./ensure-git-exclude.js";
6
6
  /**
7
7
  * Exports open change-request Comments as a self-describing hand-off
8
- * Markdown file into the target repo's local working tree, and ensures
9
- * `.review-feedback/` is gitignored there. A no-op when there are no open
10
- * change-requests — this is what makes it safe to call after every publish.
8
+ * Markdown file into the target repo's local working tree, and lists
9
+ * `.review-feedback/` in that repo's `.git/info/exclude`. A no-op when there
10
+ * are no open change-requests — this is what makes it safe to call after
11
+ * every publish. Never prompts: without a usable repo path it skips.
11
12
  */
12
13
  export async function exportHandoff(options) {
13
- const { bundlePath, comparison, round, comments, annotations, ask, repoPathCachePath } = options;
14
- const hasOpenChangeRequest = comments.some((c) => c.kind === 'change-request' && c.status === 'open' && !c.resolved);
14
+ const { bundlePath, comparison, round, comments, annotations, repoPath } = options;
15
+ const hasOpenChangeRequest = comments.some(isOpenChangeRequest);
15
16
  if (!hasOpenChangeRequest)
16
17
  return { written: false };
17
- if (!comparison.repository) {
18
- throw new Error('comparison.repository is required to export a hand-off file');
19
- }
20
- const repoPath = await resolveRepoPath(comparison.repository, ask, repoPathCachePath ?? DEFAULT_REPO_PATH_CACHE_PATH);
18
+ if (!repoPath)
19
+ return { written: false, skipped: 'no-repo-path' };
20
+ if (!ensureGitExcludesHandoff(repoPath))
21
+ return { written: false, skipped: 'not-a-git-repo' };
21
22
  const markdown = buildHandoffMarkdown({ bundlePath, comparison, round, comments, annotations });
22
23
  const feedbackDir = join(repoPath, '.review-feedback');
23
24
  mkdirSync(feedbackDir, { recursive: true });
24
25
  const filePath = join(feedbackDir, `${comparison.number}-round${round}.md`);
25
26
  writeFileSync(filePath, markdown);
26
- ensureGitignoreExcludesHandoff(repoPath);
27
27
  return { written: true, filePath, repoPath };
28
28
  }
@@ -2,7 +2,9 @@ import { PatchParseError } from "./types.js";
2
2
  const GIT_FILE_HEADER = /^diff --git a\/(.+) b\/(.+)$/;
3
3
  const OLD_FILE_MARKER = /^--- (.+)$/;
4
4
  const NEW_FILE_MARKER = /^\+\+\+ (.+)$/;
5
+ const NO_BASE_PATH = '/dev/null';
5
6
  const BINARY_MARKER = /^Binary files (?:a\/)?(.+) and (?:b\/)?(.+) differ$/;
7
+ const EXTENDED_HEADER = /^(?:index |new file mode |deleted file mode |old mode |new mode |similarity index |rename from |rename to )/;
6
8
  const HUNK_HEADER = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
7
9
  function stripPrefix(path) {
8
10
  if (path === '/dev/null')
@@ -55,8 +57,11 @@ export function parsePatch(text) {
55
57
  // Binary marker's own paths: for a bare-format deletion the marker line reads
56
58
  // "Binary files a/X and /dev/null differ", so deriving identity from its second
57
59
  // capture group would wrongly produce "/dev/null" instead of the real path X.
60
+ const added = binaryMatch[1] === NO_BASE_PATH;
58
61
  if (!pendingGitPaths && currentFile !== null && currentFile.hunks.length === 0 && !currentFile.binary) {
59
62
  currentFile.binary = true;
63
+ if (added)
64
+ currentFile.added = true;
60
65
  }
61
66
  else {
62
67
  const path = pendingGitPaths?.new ?? stripPrefix(binaryMatch[2]);
@@ -65,13 +70,14 @@ export function parsePatch(text) {
65
70
  oldPath: pendingGitPaths?.old ?? stripPrefix(binaryMatch[1]),
66
71
  binary: true,
67
72
  hunks: [],
73
+ ...(added && { added }),
68
74
  };
69
75
  files.push(currentFile);
70
76
  }
71
77
  pendingGitPaths = null;
72
78
  continue;
73
79
  }
74
- if (line.startsWith('index '))
80
+ if (EXTENDED_HEADER.test(line))
75
81
  continue;
76
82
  // A real file header only ever appears between hunks, never inside one — so once a
77
83
  // hunk is open and still expects more lines, a "--- "/"+++ "-prefixed line is content
@@ -0,0 +1,36 @@
1
+ const invalid = (detail) => ({ ok: false, error: `target is not valid: ${detail}` });
2
+ const isNonEmptyString = (value) => typeof value === 'string' && value !== '';
3
+ function isWholeNumber(value, min) {
4
+ return typeof value === 'number' && Number.isInteger(value) && value >= min;
5
+ }
6
+ export function parseCommentTarget(value) {
7
+ if (value === undefined)
8
+ return { ok: true, target: undefined };
9
+ if (typeof value !== 'object' || value === null)
10
+ return invalid('expected an object');
11
+ const raw = value;
12
+ if (raw.type === 'general')
13
+ return { ok: true, target: { type: 'general' } };
14
+ if (!isNonEmptyString(raw.path))
15
+ return invalid('path is required');
16
+ const path = raw.path;
17
+ switch (raw.type) {
18
+ case 'file':
19
+ case 'binary':
20
+ return { ok: true, target: { type: raw.type, path } };
21
+ case 'hunk':
22
+ return isWholeNumber(raw.hunkIndex, 0)
23
+ ? { ok: true, target: { type: 'hunk', path, hunkIndex: raw.hunkIndex } }
24
+ : invalid('hunkIndex must be a whole number of 0 or more');
25
+ case 'line':
26
+ if (raw.side !== 'base' && raw.side !== 'head')
27
+ return invalid('side must be base or head');
28
+ if (!isWholeNumber(raw.line, 1))
29
+ return invalid('line must be a whole number of 1 or more');
30
+ if (typeof raw.expectedText !== 'string')
31
+ return invalid('expectedText is required');
32
+ return { ok: true, target: { type: 'line', path, side: raw.side, line: raw.line, expectedText: raw.expectedText } };
33
+ default:
34
+ return invalid('unknown type');
35
+ }
36
+ }
@@ -41,6 +41,11 @@ export function raiseQuestion(bundlePath, body, target, kind = 'question') {
41
41
  resolved: false,
42
42
  };
43
43
  }
44
+ /** Withdraws a Comment without a replacement. Recorded as a new log entry, like any other change. */
45
+ export function withdrawQuestion(bundlePath, questionId) {
46
+ appendEntry(bundlePath, { type: 'withdrawn', id: randomUUID(), createdAt: new Date().toISOString(), questionId });
47
+ return { withdrawn: questionId };
48
+ }
44
49
  /**
45
50
  * Withdraws an existing question Comment and raises its replacement in one call —
46
51
  * a correction is recorded as new log entries, never as an edit to the original.
@@ -76,8 +81,9 @@ export function withdrawAndReplaceQuestion(bundlePath, questionId, replacementBo
76
81
  },
77
82
  };
78
83
  }
79
- function isOpenChangeRequest(comment) {
80
- return comment.kind === 'change-request' && comment.status === 'open' && !comment.resolved;
84
+ /** The one definition of "open change-request" — every caller must use this, not re-derive it. */
85
+ export function isOpenChangeRequest(comment) {
86
+ return comment.kind === 'change-request' && comment.status === 'open';
81
87
  }
82
88
  /**
83
89
  * Marks an open change-request Comment resolved. This is a human-only, reviewer-triggered
@@ -124,7 +130,7 @@ export function carryForwardComment(bundlePath, comment) {
124
130
  kind: comment.kind,
125
131
  });
126
132
  }
127
- /** Reduces the append-only log into the current set of Comments. */
133
+ /** Reduces the append-only log into the current set of Comments. This is the only place a Comment's `status` is derived. */
128
134
  export function readQuestions(bundlePath) {
129
135
  const comments = new Map();
130
136
  for (const entry of readLog(bundlePath)) {
@@ -151,6 +157,8 @@ export function readQuestions(bundlePath) {
151
157
  if (comment && comment.kind === 'change-request') {
152
158
  comment.resolved = true;
153
159
  comment.resolvedAt = entry.createdAt;
160
+ if (comment.status === 'open')
161
+ comment.status = 'resolved';
154
162
  }
155
163
  }
156
164
  }
@@ -0,0 +1,13 @@
1
+ export function isOpenGapAnnotation(annotation) {
2
+ return annotation.verdict !== 'intended';
3
+ }
4
+ export function countOpenGaps(files, generalAnnotations) {
5
+ const gapIds = new Set();
6
+ for (const file of files) {
7
+ for (const item of file.verification) {
8
+ if (item.status === 'gap')
9
+ gapIds.add(item.id);
10
+ }
11
+ }
12
+ return gapIds.size + generalAnnotations.filter(isOpenGapAnnotation).length;
13
+ }
@@ -1,6 +1,8 @@
1
1
  import { resolve } from 'node:path';
2
+ import { findProofLinks } from "../bundle/proof-links.js";
2
3
  import { collectCarriedReviewContent, createCaches, readChain } from "../bundle/carry-forward.js";
3
4
  import { ALLOWED_ASSET_EXTENSIONS } from "../security/asset-path.js";
5
+ import { countOpenGaps } from "./open-gaps.js";
4
6
  /**
5
7
  * The app never launches a Generator itself (per framework.md) — this only
6
8
  * builds text for the Reviewer to copy and run themselves.
@@ -78,10 +80,35 @@ function toRenderedAnnotation(annotation, evidenceById, verificationByTargetId)
78
80
  }));
79
81
  return { ...annotation, evidence, verification };
80
82
  }
81
- function renderFile(patchFile, document, fileDiagnostics, evidenceById, verificationByTargetId) {
83
+ function toRenderedProofs(links, evidenceById) {
84
+ return links.flatMap((link) => {
85
+ const evidence = evidenceById.get(link.evidenceId);
86
+ if (!evidence?.assetPath)
87
+ return [];
88
+ return [
89
+ {
90
+ evidenceId: evidence.id,
91
+ caption: evidence.description,
92
+ imagePath: link.imagePath,
93
+ assetPath: evidence.assetPath,
94
+ ...(evidence.baseAssetPath ? { baseAssetPath: evidence.baseAssetPath } : {}),
95
+ },
96
+ ];
97
+ });
98
+ }
99
+ function isCodeAnnotation(annotation) {
100
+ return annotation.target.type !== 'general';
101
+ }
102
+ function isGeneralAnnotation(annotation) {
103
+ return annotation.target.type === 'general';
104
+ }
105
+ function renderFile(patchFile, document, fileDiagnostics, evidenceById, verificationByTargetId, proofLinks) {
82
106
  const fileAnnotations = (document.annotations ?? [])
83
- .filter((a) => targetPath(a.target) === patchFile.path)
84
- .map((a) => toRenderedAnnotation(a, evidenceById, verificationByTargetId));
107
+ .filter((a) => a.target.type !== 'general' && targetPath(a.target) === patchFile.path)
108
+ .map((a) => toRenderedAnnotation(a, evidenceById, verificationByTargetId))
109
+ .filter(isCodeAnnotation);
110
+ const codeProofLinks = proofLinks.filter((l) => l.code.path === patchFile.path);
111
+ const proofEvidenceIds = new Set(proofLinks.map((l) => l.evidenceId));
85
112
  const hunks = patchFile.hunks.map((hunk, hunkIndex) => ({
86
113
  oldStart: hunk.oldStart,
87
114
  oldLines: hunk.oldLines,
@@ -103,11 +130,13 @@ function renderFile(patchFile, document, fileDiagnostics, evidenceById, verifica
103
130
  diagnostics: lineDiagnostics,
104
131
  };
105
132
  }),
133
+ proofs: toRenderedProofs(codeProofLinks.filter((l) => l.code.hunkIndex === hunkIndex), evidenceById),
106
134
  }));
107
135
  const attachedLineDiagnosticKeys = new Set(hunks.flatMap((h) => h.lines.flatMap((l) => l.diagnostics)));
108
136
  const fileLevelDiagnostics = fileDiagnostics.filter((d) => !attachedLineDiagnosticKeys.has(d));
109
137
  const imageEvidence = (document.evidence ?? [])
110
138
  .filter((e) => e.assetPath && ALLOWED_ASSET_EXTENSIONS.some((ext) => e.assetPath.toLowerCase().endsWith(ext)))
139
+ .filter((e) => patchFile.binary || !proofEvidenceIds.has(e.id))
111
140
  .filter((e) => (e.targetIds ?? []).includes(patchFile.path) || fileAnnotations.some((a) => (e.targetIds ?? []).includes(a.id)))
112
141
  .map((e) => ({
113
142
  id: e.id,
@@ -147,6 +176,10 @@ function renderFile(patchFile, document, fileDiagnostics, evidenceById, verifica
147
176
  annotations: fileAnnotations,
148
177
  imageEvidence,
149
178
  pipelineEvidence,
179
+ proofs: toRenderedProofs(codeProofLinks.filter((l) => l.code.hunkIndex === undefined), evidenceById),
180
+ proofFor: proofLinks
181
+ .filter((l) => l.imagePath === patchFile.path)
182
+ .map((l) => ({ evidenceId: l.evidenceId, ...l.code })),
150
183
  verification: fileVerification,
151
184
  diagnostics: fileLevelDiagnostics,
152
185
  };
@@ -212,11 +245,16 @@ export function render(document, patch, diagnostics, bundlePath) {
212
245
  }
213
246
  const evidenceById = new Map((effectiveDocument.evidence ?? []).map((e) => [e.id, e]));
214
247
  const verificationByTargetId = buildVerificationByTargetId(effectiveDocument.verification ?? []);
248
+ const proofLinks = findProofLinks(effectiveDocument, patch).links;
215
249
  const patchFileByPath = new Map(patch.files.map((f) => [f.path, f]));
216
250
  const files = orderedPaths
217
251
  .map((path) => patchFileByPath.get(path))
218
252
  .filter((f) => f !== undefined)
219
- .map((f) => renderFile(f, effectiveDocument, diagnosticsByPath.get(f.path) ?? [], evidenceById, verificationByTargetId));
253
+ .map((f) => renderFile(f, effectiveDocument, diagnosticsByPath.get(f.path) ?? [], evidenceById, verificationByTargetId, proofLinks));
254
+ const generalAnnotations = (effectiveDocument.annotations ?? [])
255
+ .filter((a) => a.target.type === 'general')
256
+ .map((a) => toRenderedAnnotation(a, evidenceById, verificationByTargetId))
257
+ .filter(isGeneralAnnotation);
220
258
  const attachedPaths = new Set(patch.files.map((f) => f.path));
221
259
  const bundleLevelDiagnostics = diagnostics.filter((d) => {
222
260
  const path = diagnosticPath(d);
@@ -230,6 +268,9 @@ export function render(document, patch, diagnostics, bundlePath) {
230
268
  diagnostics: bundleLevelDiagnostics,
231
269
  generatorPrompt: buildGeneratorPrompt(bundlePath),
232
270
  answers: document.answers ?? [],
271
+ intent: document.intent,
272
+ generalAnnotations,
273
+ openGaps: countOpenGaps(files, generalAnnotations),
233
274
  summary: renderSummary(effectiveDocument, attachedPaths, evidenceById, verificationByTargetId),
234
275
  };
235
276
  }
@@ -243,7 +284,8 @@ function renderSummary(document, attachedPaths, evidenceById, verificationByTarg
243
284
  highlightAnnotations: (document.summary.highlightAnnotationIds ?? [])
244
285
  .map((id) => annotationsById.get(id))
245
286
  .filter((a) => a !== undefined)
246
- .map((a) => toRenderedAnnotation(a, evidenceById, verificationByTargetId)),
287
+ .map((a) => toRenderedAnnotation(a, evidenceById, verificationByTargetId))
288
+ .filter(isCodeAnnotation),
247
289
  highlightPaths: (document.summary.highlightPaths ?? []).filter((path) => attachedPaths.has(path)),
248
290
  };
249
291
  }
@@ -1 +1,2 @@
1
- export {};
1
+ export const ANNOTATION_VERDICTS = ['intended', 'missing', 'wrong', 'extra', 'unclear'];
2
+ export const ANNOTATION_SOURCES = ['issue', 'mr-text', 'repo-rule', 'nobody'];
@@ -11,4 +11,4 @@ export function validateReviewDocumentSchema(input) {
11
11
  }
12
12
  return { valid: true, document: input };
13
13
  }
14
- export const CURRENT_SCHEMA_VERSION = 1;
14
+ export const CURRENT_SCHEMA_VERSION = 2;
@@ -0,0 +1,45 @@
1
+ import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs';
2
+ import { isAbsolute, resolve, sep } from 'node:path';
3
+ export const MAX_REPO_FILE_BYTES = 256 * 1024;
4
+ const DEFAULT_LINES = 40;
5
+ const MAX_LINES = 200;
6
+ function clampLines(lines) {
7
+ if (!Number.isFinite(lines) || lines < 1)
8
+ return DEFAULT_LINES;
9
+ return Math.min(Math.floor(lines), MAX_LINES);
10
+ }
11
+ function isUnsafeRelativePath(relativePath) {
12
+ if (relativePath === '' || relativePath.includes('\0'))
13
+ return true;
14
+ if (isAbsolute(relativePath))
15
+ return true;
16
+ return relativePath.split(/[\\/]/).includes('..');
17
+ }
18
+ function isInside(root, candidate) {
19
+ return candidate === root || candidate.startsWith(root + sep);
20
+ }
21
+ /** Reads the top lines of one text file inside the repo checkout. Read-only; refuses anything that leaves the repo, also through symlinks. */
22
+ export function readRepoFileTop(repoPath, relativePath, lines) {
23
+ if (!repoPath)
24
+ return { ok: false, reason: 'no-repo' };
25
+ if (isUnsafeRelativePath(relativePath))
26
+ return { ok: false, reason: 'unsafe-path' };
27
+ const candidate = resolve(repoPath, relativePath);
28
+ if (!existsSync(candidate))
29
+ return { ok: false, reason: 'not-found' };
30
+ const realRoot = realpathSync(repoPath);
31
+ const realFile = realpathSync(candidate);
32
+ if (!isInside(realRoot, realFile))
33
+ return { ok: false, reason: 'unsafe-path' };
34
+ const stats = statSync(realFile);
35
+ if (!stats.isFile())
36
+ return { ok: false, reason: 'not-a-file' };
37
+ if (stats.size > MAX_REPO_FILE_BYTES)
38
+ return { ok: false, reason: 'too-large' };
39
+ const buffer = readFileSync(realFile);
40
+ if (buffer.includes(0))
41
+ return { ok: false, reason: 'not-text' };
42
+ const allLines = buffer.toString('utf-8').replace(/\r\n/g, '\n').replace(/\n$/, '').split('\n');
43
+ const wanted = clampLines(lines);
44
+ return { ok: true, path: relativePath, content: allLines.slice(0, wanted).join('\n'), truncated: allLines.length > wanted };
45
+ }
@@ -1,20 +1,22 @@
1
1
  import { createServer } from 'node:http';
2
- import { randomBytes } from 'node:crypto';
3
2
  import { createReadStream, existsSync, statSync } from 'node:fs';
4
3
  import { join } from 'node:path';
5
4
  import { validateBundle } from "../bundle/validate-bundle.js";
6
5
  import { publishBundleAndExportHandoff } from "../bundle/publish-with-handoff.js";
7
6
  import { watchBundle } from "./watch-bundle.js";
8
- import { raiseQuestion, resolveComment, withdrawAndReplaceQuestion } from "../questions/questions-log.js";
9
- import { askForRepoPathOnStdin } from "../handoff/ask-repo-path.js";
10
- import { carryForwardChain, listComments } from "../bundle/carry-forward.js";
7
+ import { raiseQuestion, resolveComment, withdrawAndReplaceQuestion, withdrawQuestion } from "../questions/questions-log.js";
8
+ import { buildLiveHeadStatus, readLiveHead } from "../bundle/live-head.js";
9
+ import { parseCommentTarget } from "../questions/comment-target.js";
10
+ import { readWatcher } from "../bundle/watcher.js";
11
+ import { carryForwardChain, listComments, readChain } from "../bundle/carry-forward.js";
11
12
  import { readReviewState, writeReviewState } from "../review-state/review-state.js";
12
13
  import { render } from "../renderer/render.js";
13
14
  import { buildReport } from "../export/report.js";
14
15
  import { resolveAssetPath } from "../security/asset-path.js";
15
- export function generateWriteToken() {
16
- return randomBytes(24).toString('hex');
17
- }
16
+ import { readRepoFileTop } from "../security/repo-file.js";
17
+ import { backupOrWarn, backupPathFor } from "../bundle/backup.js";
18
+ import { loadWriteToken } from "./write-token.js";
19
+ const FILE_EXTENSION = /\.[a-zA-Z0-9]+$/;
18
20
  const WRITE_TOKEN_HEADER = 'x-write-token';
19
21
  const WITHDRAW_PATH = /^\/questions\/([^/]+)\/withdraw$/;
20
22
  const RESOLVE_PATH = /^\/questions\/([^/]+)\/resolve$/;
@@ -39,12 +41,17 @@ const UI_CONTENT_TYPES = {
39
41
  '.json': 'application/json',
40
42
  ...ASSET_CONTENT_TYPES,
41
43
  };
44
+ function isStaticUiRequest(method, pathname) {
45
+ if (method !== 'GET' || pathname.startsWith('/assets/'))
46
+ return false;
47
+ return pathname === '/' || FILE_EXTENSION.test(pathname);
48
+ }
42
49
  function serveUiStatic(pathname, res) {
43
50
  if (!existsSync(UI_DIST_DIR))
44
51
  return false;
45
52
  // SPA fallback: any path without a recognized static-file extension is a client-side
46
53
  // route (e.g. a deep link) — serve index.html and let the app's own router take over.
47
- const hasExtension = /\.[a-zA-Z0-9]+$/.test(pathname);
54
+ const hasExtension = FILE_EXTENSION.test(pathname);
48
55
  const candidate = join(UI_DIST_DIR, hasExtension ? pathname : 'index.html');
49
56
  const resolved = hasExtension && existsSync(candidate) && statSync(candidate).isFile() ? candidate : join(UI_DIST_DIR, 'index.html');
50
57
  if (!existsSync(resolved))
@@ -72,8 +79,7 @@ function readJsonBody(req) {
72
79
  });
73
80
  }
74
81
  export function startReviewServer(bundlePath, opts = {}) {
75
- const writeToken = opts.writeToken ?? generateWriteToken();
76
- const askForRepoPath = opts.askForRepoPath ?? askForRepoPathOnStdin;
82
+ const writeToken = opts.writeToken ?? loadWriteToken(bundlePath, { rotate: opts.rotateToken });
77
83
  // A round-N bundle (has chain.json) carries forward every still-open change-request
78
84
  // from the previous round into its own log the moment it's opened — idempotent, so
79
85
  // safe to repeat on every subsequent change below too.
@@ -83,10 +89,30 @@ export function startReviewServer(bundlePath, opts = {}) {
83
89
  // this is what makes file watching load-bearing rather than a no-op wrapper
84
90
  // around a stateless re-read-per-request design.
85
91
  let latest = validateBundle(bundlePath);
86
- const watcher = watchBundle(bundlePath);
87
- watcher.emitter.on('change', () => {
92
+ backupOrWarn(bundlePath, opts.backupRoot);
93
+ const backupCopyPath = backupPathFor(bundlePath, opts.backupRoot);
94
+ const lastBackup = () => (existsSync(backupCopyPath) ? backupCopyPath : null);
95
+ const reload = () => {
88
96
  carryForwardChain(bundlePath);
89
97
  latest = validateBundle(bundlePath);
98
+ };
99
+ let folderGone = false;
100
+ const folderIsPresent = () => {
101
+ if (existsSync(bundlePath)) {
102
+ folderGone = false;
103
+ return true;
104
+ }
105
+ if (!folderGone) {
106
+ folderGone = true;
107
+ const last = lastBackup();
108
+ process.stderr.write(`Bundle folder is gone: ${bundlePath}. ${last ? `Last backup: ${last}` : 'No backup found.'}\n`);
109
+ }
110
+ return false;
111
+ };
112
+ const watcher = watchBundle(bundlePath);
113
+ watcher.emitter.on('change', () => {
114
+ if (folderIsPresent())
115
+ reload();
90
116
  });
91
117
  const server = createServer((req, res) => {
92
118
  const url = new URL(req.url ?? '/', 'http://localhost');
@@ -99,6 +125,22 @@ export function startReviewServer(bundlePath, opts = {}) {
99
125
  res.writeHead(status, { 'content-type': 'application/json' });
100
126
  res.end(JSON.stringify(body));
101
127
  };
128
+ const isApiRequest = req.url?.startsWith('/api/') || !isStaticUiRequest(req.method, url.pathname);
129
+ if (isApiRequest) {
130
+ const wasGone = folderGone;
131
+ if (!folderIsPresent()) {
132
+ respond(503, { error: 'bundle folder is gone', backupPath: lastBackup() });
133
+ return;
134
+ }
135
+ if (wasGone)
136
+ reload();
137
+ }
138
+ if (req.method !== 'GET' && url.pathname !== '/publish') {
139
+ res.on('finish', () => {
140
+ if (res.statusCode < 300)
141
+ backupOrWarn(bundlePath, opts.backupRoot);
142
+ });
143
+ }
102
144
  if (req.method === 'GET' && url.pathname === '/document') {
103
145
  respond(200, latest);
104
146
  return;
@@ -111,6 +153,19 @@ export function startReviewServer(bundlePath, opts = {}) {
111
153
  respond(200, render(latest.document, latest.patch, latest.diagnostics ?? [], bundlePath));
112
154
  return;
113
155
  }
156
+ if (req.method === 'GET' && url.pathname === '/live-head') {
157
+ if (!latest.valid) {
158
+ respond(422, { error: 'bundle is not valid', blockingReason: latest.blockingReason });
159
+ return;
160
+ }
161
+ const { comparison } = latest.document;
162
+ respond(200, buildLiveHeadStatus(readLiveHead(bundlePath), comparison.head, readChain(bundlePath)?.round ?? 1));
163
+ return;
164
+ }
165
+ if (req.method === 'GET' && url.pathname === '/watcher') {
166
+ respond(200, readWatcher(bundlePath));
167
+ return;
168
+ }
114
169
  if (req.method === 'GET' && url.pathname === '/questions') {
115
170
  respond(200, listComments(bundlePath));
116
171
  return;
@@ -140,14 +195,27 @@ export function startReviewServer(bundlePath, opts = {}) {
140
195
  createReadStream(resolution.absolutePath).pipe(res);
141
196
  return;
142
197
  }
198
+ if (req.method === 'GET' && url.pathname === '/repo-file') {
199
+ if (!opts.repoPath) {
200
+ respond(404, { error: 'file preview needs the server to run with --repo' });
201
+ return;
202
+ }
203
+ const result = readRepoFileTop(opts.repoPath, url.searchParams.get('path') ?? '', Number(url.searchParams.get('lines') ?? 40));
204
+ if (!result.ok) {
205
+ respond(404, { error: `file cannot be read: ${result.reason}` });
206
+ return;
207
+ }
208
+ respond(200, result);
209
+ return;
210
+ }
143
211
  if (req.method !== 'GET') {
144
212
  if (req.headers[WRITE_TOKEN_HEADER] !== writeToken) {
145
- respond(401, { error: 'invalid write token' });
213
+ respond(401, { error: 'invalid write token for this server' });
146
214
  return;
147
215
  }
148
216
  }
149
217
  if (req.method === 'POST' && url.pathname === '/publish') {
150
- publishBundleAndExportHandoff(bundlePath, { ask: askForRepoPath, repoPathCachePath: opts.repoPathCachePath })
218
+ publishBundleAndExportHandoff(bundlePath, { repoPath: opts.repoPath, backupRoot: opts.backupRoot })
151
219
  .then((result) => respond(result.ok ? 200 : 422, result))
152
220
  .catch((err) => respond(500, { error: err instanceof Error ? err.message : 'publish failed' }));
153
221
  return;
@@ -164,7 +232,12 @@ export function startReviewServer(bundlePath, opts = {}) {
164
232
  respond(400, { error: `kind must be one of ${COMMENT_KINDS.join(', ')}` });
165
233
  return;
166
234
  }
167
- respond(201, raiseQuestion(bundlePath, text, target, kind ?? 'question'));
235
+ const parsedTarget = parseCommentTarget(target);
236
+ if (!parsedTarget.ok) {
237
+ respond(400, { error: parsedTarget.error });
238
+ return;
239
+ }
240
+ respond(201, raiseQuestion(bundlePath, text, parsedTarget.target, kind ?? 'question'));
168
241
  })
169
242
  .catch(() => respond(400, { error: 'invalid JSON body' }));
170
243
  return;
@@ -174,11 +247,20 @@ export function startReviewServer(bundlePath, opts = {}) {
174
247
  readJsonBody(req)
175
248
  .then((body) => {
176
249
  const { body: text, target } = body;
250
+ if (text === undefined) {
251
+ respond(200, withdrawQuestion(bundlePath, withdrawMatch[1]));
252
+ return;
253
+ }
177
254
  if (typeof text !== 'string' || text.trim() === '') {
178
- respond(400, { error: 'body is required for the replacement Question' });
255
+ respond(400, { error: 'body must be a non-empty string when a replacement Question is given' });
256
+ return;
257
+ }
258
+ const parsedTarget = parseCommentTarget(target);
259
+ if (!parsedTarget.ok) {
260
+ respond(400, { error: parsedTarget.error });
179
261
  return;
180
262
  }
181
- respond(201, withdrawAndReplaceQuestion(bundlePath, withdrawMatch[1], text, target));
263
+ respond(201, withdrawAndReplaceQuestion(bundlePath, withdrawMatch[1], text, parsedTarget.target));
182
264
  })
183
265
  .catch(() => respond(400, { error: 'invalid JSON body' }));
184
266
  return;
@@ -0,0 +1,27 @@
1
+ import { chmodSync, existsSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { randomBytes } from 'node:crypto';
3
+ import { join } from 'node:path';
4
+ export const WRITE_TOKEN_FILE = '.write-token';
5
+ export function generateWriteToken() {
6
+ return randomBytes(24).toString('hex');
7
+ }
8
+ /**
9
+ * Returns the bundle's write token, minting and saving one on first use. The token
10
+ * lives in the bundle so a restart keeps every link and token already handed out
11
+ * valid. The file is local to this machine: .gitignore and the package `files`
12
+ * list keep it out of git and out of a published package.
13
+ */
14
+ export function loadWriteToken(bundlePath, options = {}) {
15
+ const path = join(bundlePath, WRITE_TOKEN_FILE);
16
+ if (!options.rotate && existsSync(path)) {
17
+ const saved = readFileSync(path, 'utf-8').trim();
18
+ if (saved !== '') {
19
+ chmodSync(path, 0o600);
20
+ return saved;
21
+ }
22
+ }
23
+ const token = generateWriteToken();
24
+ writeFileSync(path, token + '\n', { mode: 0o600 });
25
+ chmodSync(path, 0o600);
26
+ return token;
27
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "review-workspace",
3
- "version": "1.10.2",
3
+ "version": "1.13.0",
4
4
  "description": "A local, offline decision surface for reviewing a code Comparison — evidence-linked map of intent, behavior, risk, and observable effects.",
5
5
  "license": "MIT",
6
6
  "author": "Salih Sayer",
@@ -44,9 +44,36 @@
44
44
  "type": "array",
45
45
  "items": { "$ref": "#/$defs/answer" }
46
46
  },
47
- "summary": { "$ref": "#/$defs/summary" }
47
+ "summary": { "$ref": "#/$defs/summary" },
48
+ "intent": { "$ref": "#/$defs/intent" }
48
49
  },
49
50
  "$defs": {
51
+ "intent": {
52
+ "type": "object",
53
+ "required": ["does", "why", "sources"],
54
+ "additionalProperties": false,
55
+ "properties": {
56
+ "does": { "type": "string", "minLength": 1 },
57
+ "why": { "type": "string", "minLength": 1 },
58
+ "doesNot": { "type": "array", "items": { "type": "string", "minLength": 1 } },
59
+ "sources": { "type": "array", "minItems": 1, "items": { "type": "string", "minLength": 1 } },
60
+ "weakDescription": { "type": "string", "minLength": 1 },
61
+ "visuals": { "type": "array", "items": { "$ref": "#/$defs/intentVisual" } }
62
+ }
63
+ },
64
+ "intentVisual": {
65
+ "type": "object",
66
+ "required": ["assetPath", "caption", "source"],
67
+ "additionalProperties": false,
68
+ "properties": {
69
+ "assetPath": { "type": "string", "minLength": 1 },
70
+ "baseAssetPath": { "type": "string", "minLength": 1 },
71
+ "caption": { "type": "string", "minLength": 1 },
72
+ "source": { "enum": ["mr-text", "snapshot"] }
73
+ },
74
+ "if": { "properties": { "source": { "const": "mr-text" } }, "required": ["source"] },
75
+ "then": { "not": { "required": ["baseAssetPath"] } }
76
+ },
50
77
  "summary": {
51
78
  "type": "object",
52
79
  "required": ["text"],
@@ -85,6 +112,15 @@
85
112
  }
86
113
  ]
87
114
  },
115
+ "generalTarget": {
116
+ "type": "object",
117
+ "required": ["type"],
118
+ "additionalProperties": false,
119
+ "properties": { "type": { "const": "general" } }
120
+ },
121
+ "annotationTarget": {
122
+ "oneOf": [{ "$ref": "#/$defs/target" }, { "$ref": "#/$defs/generalTarget" }]
123
+ },
88
124
  "behavioralGroup": {
89
125
  "type": "object",
90
126
  "required": ["id", "title", "order"],
@@ -104,9 +140,13 @@
104
140
  "additionalProperties": false,
105
141
  "properties": {
106
142
  "id": { "type": "string", "minLength": 1 },
107
- "target": { "$ref": "#/$defs/target" },
143
+ "target": { "$ref": "#/$defs/annotationTarget" },
108
144
  "summary": { "type": "string", "minLength": 1 },
109
145
  "kind": { "enum": ["intent", "behavior", "risk"] },
146
+ "verdict": { "enum": ["intended", "missing", "wrong", "extra", "unclear"] },
147
+ "severity": { "enum": ["low", "medium", "high"] },
148
+ "source": { "enum": ["issue", "mr-text", "repo-rule", "nobody"] },
149
+ "suggestion": { "type": "string", "minLength": 1 },
110
150
  "evidenceIds": { "type": "array", "items": { "type": "string" } },
111
151
  "relatedTargets": {
112
152
  "type": "array",