@eliya-oss/agent-diff 0.1.0-alpha.187 → 0.1.0-alpha.189

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 (3) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/dist/main.js +223 -49
  3. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,31 @@
1
1
  # @eliya-oss/agent-diff
2
2
 
3
+ ## 0.1.0-alpha.189
4
+
5
+ ### Patch Changes
6
+
7
+ - perf(CLI): `adiff serve` answers a repeated question in half the time, by remembering for a moment what git already said.
8
+
9
+ <details><summary>Measured</summary>
10
+
11
+ On a 20-file branch, through one `adiff serve`: `comment list` 214ms to 104ms, `review progress` 216ms to 102ms, the four calls a review page makes at once 300ms to 147ms, and one whole file 240ms to 117ms. The first read of a branch, while nothing is remembered yet, fell from 1112ms to 627ms, because the default branch is now found by checking every candidate at once. Heads are never remembered, so a commit or a new branch shows on the next request.
12
+
13
+ </details>
14
+
15
+ ## 0.1.0-alpha.188
16
+
17
+ ### Patch Changes
18
+
19
+ - feat(CLI): `adiff serve` answers command after command over one pipe, and tells a client the moment a review it watches changes.
20
+
21
+ <details><summary>What it is for</summary>
22
+
23
+ A program that asks adiff often, such as a review page in the browser, keeps one adiff running instead of starting one per question, and redraws when a comment, an answer or a reviewed mark changes instead of asking every few seconds. On a 19-file branch, `comment list` took 546ms as a fresh process and 205ms through `serve`; a watched review reported a comment filed by another process before that process had exited.
24
+
25
+ </details>
26
+
27
+ perf(marks): an open review shows a file marked reviewed from another program without a reload.
28
+
3
29
  ## 0.1.0-alpha.187
4
30
 
5
31
  ### Patch Changes
package/dist/main.js CHANGED
@@ -3,11 +3,12 @@ import { appendFile, mkdir, readFile, realpath, rename, rm, stat, writeFile } fr
3
3
  import { text } from "node:stream/consumers";
4
4
  import { execFile, spawn } from "node:child_process";
5
5
  import { fileURLToPath } from "node:url";
6
+ import { existsSync, mkdirSync, watch } from "node:fs";
7
+ import { createInterface } from "node:readline";
6
8
  import { join, resolve } from "node:path";
7
9
  import { promisify } from "node:util";
8
10
  import { homedir, hostname, platform } from "node:os";
9
11
  import { ASCIIFontRenderable, BoxRenderable, CodeRenderable, KeyEvent, LineNumberRenderable, RGBA, StyledText, SyntaxStyle, TextRenderable, TextareaRenderable, addDefaultParsers, bg, bold, createCliRenderer, defaultTextareaKeyBindings, fg, fonts, getTreeSitterClient, pathToFiletype, stripAnsiSequences, t } from "@opentui/core";
10
- import { existsSync, mkdirSync, watch } from "node:fs";
11
12
  //#region \0rolldown/runtime.js
12
13
  var __defProp = Object.defineProperty;
13
14
  var __esmMin = (fn, res, err) => () => {
@@ -2684,7 +2685,7 @@ var init_references = __esmMin((() => {
2684
2685
  };
2685
2686
  };
2686
2687
  spanCleaner = /*#__PURE__*/ makeStackCleaner(3);
2687
- })), Interrupt, causeInterrupt, findFail, findError$1, findDefect, hasInterrupts, causeFilterInterruptors, hasInterruptsOnly$1, causeCombine, causeMap, causePartition, causeSquash, causePrettyErrors, causePrettyError, causePrettyMessage, locationRegExp, cleanErrorStack, addStackAnnotations, interruptCauseStack, currentStackTrace, causePretty, renderPrettyError, renderErrorCause, FiberTypeId, fiberVariance, fiberIdStore, getCurrentFiber, FiberImpl, deferredInterruptCont, fiberMiddleware, fiberStackAnnotations, fiberAwait, fiberAwaitAll, fiberJoin, fiberInterrupt, fiberInterruptAs, fiberInterruptAll, succeed$5, failCause$3, fail$2, sync$1, suspend$1, yieldNowWith, yieldNow, succeedNone$1, failCauseSync$1, die$1, failSync, void_$2, try_$1, promise$1, tryPromise$1, withFiberId, callbackOptions, asyncFinalizer, callback$2, never, gen$1, fnUntraced$1, defineFunctionLength, fnStackCleaner, fn$1, makeFn, fnUntracedEager$1, fromIteratorEagerUnsafe, fromIteratorUnsafe, as$1, asSome, andThen$1, tap$1, asVoid$1, raceAllFirst, raceFirst$1, flatMap$1, OnSuccessProto, effectIsExit, flatMapEager$1, map$3, mapEager$1, mapErrorEager$1, catchEager$1, exitInterrupt$1, exitIsSuccess, exitIsFailure, exitFilterCause, exitHasInterrupts, exitVoid, exitMap, exitMapError, exitAsVoidAll, updateContext, updateService, context$1, getContext, contextWith$1, provideContext, provideService, provideServiceImpl, when$1, forever$2, catchCause$1, OnFailureProto, catchCauseFilter, catch_, catchDefect$1, catchIf, catchFilter, catchTag$1, catchTags$1, mapError$1, orDie$1, orElseSucceed$1, ignore$1, option$3, result$1, matchCauseEffect, OnSuccessAndFailureProto, matchEffect$1, match, matchEager, exit$1, exitPrimitive, ScopeTypeId, ScopeCloseableTypeId, scopeTag, scopeClose, scopeCloseUnsafe, scopeCloseFinalizers, scopeForkUnsafe, scopeAddFinalizerExit, scopeAddFinalizer, scopeAddFinalizerUnsafe, scopeRemoveFinalizerUnsafe, scopeMakeUnsafe, constScopeEmpty, scope, provideScope, scoped$1, scopedWith, acquireRelease$1, addFinalizer$2, onExitPrimitive, onExit$1, ensuring$1, onExitFilter, onError$1, onErrorFilter, onInterrupt$1, acquireUseRelease$1, interrupt$1, uninterruptible$1, setInterruptible, setInterruptibleTrue, setInterruptibleFalse, setFiberInterruptible, interruptible, uninterruptibleMask$1, all$1, whileLoop$1, forEach$1, forEachSequential, iterateEagerImpl, iterateEager, forEachConcurrent, forkUnsafe$1, forkIn$1, forkScoped$1, runForkWith$1, runFork$1, runPromiseExitWith, runPromiseWith, runPromise$1, runSyncExitWith, runSyncExit$1, runSyncWith, runSync$1, succeedTrue, succeedFalse, Latch, makeLatchUnsafe, bigint0, NoopSpanProto, noopSpan, filterDisablePropagation, makeSpanUnsafe, provideSpanStackFrame, endSpan, useSpan, provideParentSpan, withParentSpan, withSpan$1, ClockRef, MAX_TIMER_MILLIS, ClockImpl, nanosPerMilli, monotonicNowNanos, wallTimeNanos, clockWith, sleep$1, AsyncFiberErrorTypeId, AsyncFiberError, UnknownErrorTypeId, UnknownError, ConsoleRef, logLevelToOrder, LogLevelOrder, isLogLevelGreaterThan, CurrentLoggers, LogToStderr, LoggerTypeId, LoggerProto, loggerMake, formatLabel, formatLogSpan, logWithLevel, colors, defaultDateFormat, defaultLogger, tracerLogger, init_effect = __esmMin((() => {
2688
+ })), Interrupt, causeInterrupt, findFail, findError$1, findDefect, hasInterrupts, causeFilterInterruptors, hasInterruptsOnly$1, causeCombine, causeMap, causePartition, causeSquash, causePrettyErrors, causePrettyError, causePrettyMessage, locationRegExp, cleanErrorStack, addStackAnnotations, interruptCauseStack, currentStackTrace, causePretty, renderPrettyError, renderErrorCause, FiberTypeId, fiberVariance, fiberIdStore, getCurrentFiber, FiberImpl, deferredInterruptCont, fiberMiddleware, fiberStackAnnotations, fiberAwait, fiberAwaitAll, fiberJoin, fiberInterrupt, fiberInterruptAs, fiberInterruptAll, succeed$5, failCause$3, fail$2, sync$1, suspend$1, yieldNowWith, yieldNow, succeedNone$1, failCauseSync$1, die$1, failSync, void_$2, try_$1, promise$1, tryPromise$1, withFiberId, callbackOptions, asyncFinalizer, callback$2, never, gen$1, fnUntraced$1, defineFunctionLength, fnStackCleaner, fn$1, makeFn, fnUntracedEager$1, fromIteratorEagerUnsafe, fromIteratorUnsafe, as$1, asSome, andThen$1, tap$1, asVoid$1, raceAllFirst, raceFirst$1, flatMap$1, OnSuccessProto, effectIsExit, flatMapEager$1, map$3, mapEager$1, mapErrorEager$1, catchEager$1, exitInterrupt$1, exitIsSuccess, exitIsFailure, exitFilterCause, exitHasInterrupts, exitVoid, exitMap, exitMapError, exitAsVoidAll, updateContext, updateService, context$1, getContext, contextWith$1, provideContext, provideService$1, provideServiceImpl, when$1, forever$2, catchCause$1, OnFailureProto, catchCauseFilter, catch_, catchDefect$1, catchIf, catchFilter, catchTag$1, catchTags$1, mapError$1, orDie$1, orElseSucceed$1, ignore$1, option$3, result$1, matchCauseEffect, OnSuccessAndFailureProto, matchEffect$1, match, matchEager, exit$1, exitPrimitive, ScopeTypeId, ScopeCloseableTypeId, scopeTag, scopeClose, scopeCloseUnsafe, scopeCloseFinalizers, scopeForkUnsafe, scopeAddFinalizerExit, scopeAddFinalizer, scopeAddFinalizerUnsafe, scopeRemoveFinalizerUnsafe, scopeMakeUnsafe, constScopeEmpty, scope, provideScope, scoped$1, scopedWith, acquireRelease$1, addFinalizer$2, onExitPrimitive, onExit$1, ensuring$1, onExitFilter, onError$1, onErrorFilter, onInterrupt$1, acquireUseRelease$1, interrupt$1, uninterruptible$1, setInterruptible, setInterruptibleTrue, setInterruptibleFalse, setFiberInterruptible, interruptible, uninterruptibleMask$1, all$1, whileLoop$1, forEach$1, forEachSequential, iterateEagerImpl, iterateEager, forEachConcurrent, forkUnsafe$1, forkIn$1, forkScoped$1, runForkWith$1, runFork$1, runPromiseExitWith, runPromiseWith, runPromise$1, runSyncExitWith, runSyncExit$1, runSyncWith, runSync$1, succeedTrue, succeedFalse, Latch, makeLatchUnsafe, bigint0, NoopSpanProto, noopSpan, filterDisablePropagation, makeSpanUnsafe, provideSpanStackFrame, endSpan, useSpan, provideParentSpan, withParentSpan, withSpan$1, ClockRef, MAX_TIMER_MILLIS, ClockImpl, nanosPerMilli, monotonicNowNanos, wallTimeNanos, clockWith, sleep$1, AsyncFiberErrorTypeId, AsyncFiberError, UnknownErrorTypeId, UnknownError, ConsoleRef, logLevelToOrder, LogLevelOrder, isLogLevelGreaterThan, CurrentLoggers, LogToStderr, LoggerTypeId, LoggerProto, loggerMake, formatLabel, formatLogSpan, logWithLevel, colors, defaultDateFormat, defaultLogger, tracerLogger, init_effect = __esmMin((() => {
2688
2689
  init_Array();
2689
2690
  init_Context();
2690
2691
  init_Duration();
@@ -3470,7 +3471,7 @@ var init_references = __esmMin((() => {
3470
3471
  if (effectIsExit(self)) return self;
3471
3472
  return updateContext(self, merge(context));
3472
3473
  });
3473
- provideService = function() {
3474
+ provideService$1 = function() {
3474
3475
  if (arguments.length === 1) return dual(2, (self, impl) => provideServiceImpl(self, arguments[0], impl));
3475
3476
  return dual(3, (self, service, impl) => provideServiceImpl(self, service, impl)).apply(this, arguments);
3476
3477
  };
@@ -3667,7 +3668,7 @@ var init_references = __esmMin((() => {
3667
3668
  });
3668
3669
  constScopeEmpty = { _tag: "Empty" };
3669
3670
  scope = scopeTag;
3670
- provideScope = /*#__PURE__*/ provideService(scopeTag);
3671
+ provideScope = /*#__PURE__*/ provideService$1(scopeTag);
3671
3672
  scoped$1 = (self) => withFiber$1((fiber) => {
3672
3673
  const prev = fiber.context;
3673
3674
  const scope = scopeMakeUnsafe();
@@ -4167,7 +4168,7 @@ var init_references = __esmMin((() => {
4167
4168
  return onExit$1(internalCall(() => evaluate(span)), (exit) => endSpan(span, exit, clock, timingEnabled));
4168
4169
  });
4169
4170
  };
4170
- provideParentSpan = /*#__PURE__*/ provideService(ParentSpan);
4171
+ provideParentSpan = /*#__PURE__*/ provideService$1(ParentSpan);
4171
4172
  withParentSpan = function() {
4172
4173
  const dataFirst = isEffect$1(arguments[0]);
4173
4174
  const span = dataFirst ? arguments[1] : arguments[0];
@@ -4546,7 +4547,7 @@ var succeed$4, failCause$2, fail$1, void_$1, isSuccess, isFailure, init_Exit = _
4546
4547
  return current ? forkMemoMapUnsafe(current) : makeMemoMapUnsafe();
4547
4548
  }
4548
4549
  };
4549
- buildWithMemoMap = /*#__PURE__*/ dual(3, (self, memoMap, scope) => provideService(map$3(self.build(memoMap, scope), add$2(CurrentMemoMap, memoMap)), CurrentMemoMap, memoMap));
4550
+ buildWithMemoMap = /*#__PURE__*/ dual(3, (self, memoMap, scope) => provideService$1(map$3(self.build(memoMap, scope), add$2(CurrentMemoMap, memoMap)), CurrentMemoMap, memoMap));
4550
4551
  buildWithScope = /*#__PURE__*/ dual(2, (self, scope) => withFiber$1((fiber) => buildWithMemoMap(self, CurrentMemoMap.forkOrCreate(fiber.context), scope)));
4551
4552
  succeed$2 = function() {
4552
4553
  if (arguments.length === 1) return (resource) => succeedContext(make$18(arguments[0], resource));
@@ -4751,14 +4752,14 @@ var repeatOrElse, retryOrElse, repeat$1, retry$1, passthroughForever, buildFromO
4751
4752
  init_effect();
4752
4753
  repeatOrElse = /*#__PURE__*/ dual(3, (self, schedule, orElse) => flatMap$1(toStepWithMetadata(schedule), (step) => {
4753
4754
  let meta = CurrentMetadata.defaultValue();
4754
- return catch_(forever$2(tap$1(flatMap$1(suspend$1(() => provideService(self, CurrentMetadata, meta)), step), (meta_) => sync$1(() => {
4755
+ return catch_(forever$2(tap$1(flatMap$1(suspend$1(() => provideService$1(self, CurrentMetadata, meta)), step), (meta_) => sync$1(() => {
4755
4756
  meta = meta_;
4756
4757
  })), { disableYield: true }), (error) => isDone$1(error) ? succeed$5(error.value) : orElse(error, meta.attempt === 0 ? none() : some(meta)));
4757
4758
  }));
4758
4759
  retryOrElse = /*#__PURE__*/ dual(3, (self, policy, orElse) => flatMap$1(toStepWithMetadata(policy), (step) => {
4759
4760
  let meta = CurrentMetadata.defaultValue();
4760
4761
  let lastError;
4761
- const loop = catch_(suspend$1(() => provideService(self, CurrentMetadata, meta)), (error) => {
4762
+ const loop = catch_(suspend$1(() => provideService$1(self, CurrentMetadata, meta)), (error) => {
4762
4763
  lastError = error;
4763
4764
  return flatMap$1(step(error), (meta_) => {
4764
4765
  meta = meta_;
@@ -4789,7 +4790,7 @@ var repeatOrElse, retryOrElse, repeat$1, retry$1, passthroughForever, buildFromO
4789
4790
  if (options.times !== void 0) schedule = while_(schedule, ({ attempt }) => succeed$5(attempt <= options.times));
4790
4791
  return schedule;
4791
4792
  };
4792
- })), isEffect, all, forEach, whileLoop, promise, tryPromise, succeed$1, succeedNone, suspend, sync, void_, callback$1, gen, fail, failCause, failCauseSync, die, try_, withFiber, flatMap, andThen, tap, result, option$2, exit, map$1, as, asVoid, catchTag, catchTags, catchCause, catchDefect, mapError, orDie, retry, ignore, orElseSucceed, sleep, raceFirst, when, context, contextWith, provide, scoped, acquireRelease, acquireUseRelease, addFinalizer, ensuring, onError, onExit, interrupt, onInterrupt, uninterruptible, uninterruptibleMask, forever, repeat, withSpan, forkIn, forkScoped, runFork, runForkWith, runPromise, runSync, runSyncExit, fnUntraced, fn, mapEager, mapErrorEager, flatMapEager, catchEager, fnUntracedEager;
4793
+ })), isEffect, all, forEach, whileLoop, promise, tryPromise, succeed$1, succeedNone, suspend, sync, void_, callback$1, gen, fail, failCause, failCauseSync, die, try_, withFiber, flatMap, andThen, tap, result, option$2, exit, map$1, as, asVoid, catchTag, catchTags, catchCause, catchDefect, mapError, orDie, retry, ignore, orElseSucceed, sleep, raceFirst, when, context, contextWith, provide, provideService, scoped, acquireRelease, acquireUseRelease, addFinalizer, ensuring, onError, onExit, interrupt, onInterrupt, uninterruptible, uninterruptibleMask, forever, repeat, withSpan, forkIn, forkScoped, runFork, runForkWith, runPromise, runSync, runSyncExit, fnUntraced, fn, mapEager, mapErrorEager, flatMapEager, catchEager, fnUntracedEager;
4793
4794
  var init_Effect = __esmMin((() => {
4794
4795
  init_Context();
4795
4796
  init_core();
@@ -4839,6 +4840,7 @@ var init_Effect = __esmMin((() => {
4839
4840
  context = context$1;
4840
4841
  contextWith = contextWith$1;
4841
4842
  provide = provide$1;
4843
+ provideService = provideService$1;
4842
4844
  scoped = scoped$1;
4843
4845
  acquireRelease = acquireRelease$1;
4844
4846
  acquireUseRelease = acquireUseRelease$1;
@@ -10042,10 +10044,10 @@ var init_config = __esmMin((() => {
10042
10044
  //#region package.json
10043
10045
  init_pane();
10044
10046
  init_config();
10045
- var version$1 = "0.1.0-alpha.187";
10047
+ var version$1 = "0.1.0-alpha.189";
10046
10048
  //#endregion
10047
10049
  //#region src/cli/error.ts
10048
- var UnknownCommand, MissingOption, UnknownField, UnknownOption, BadOption, RegistryUnanswered;
10050
+ var UnknownCommand, MissingOption, UnknownField, UnknownOption, BadOption, RegistryUnanswered, NotServed, BadRequest;
10049
10051
  var init_error$5 = __esmMin((() => {
10050
10052
  init_dist();
10051
10053
  UnknownCommand = class extends TaggedError("UnknownCommand") {};
@@ -10054,6 +10056,8 @@ var init_error$5 = __esmMin((() => {
10054
10056
  UnknownOption = class extends TaggedError("UnknownOption") {};
10055
10057
  BadOption = class extends TaggedError("BadOption") {};
10056
10058
  RegistryUnanswered = class extends TaggedError("RegistryUnanswered") {};
10059
+ NotServed = class extends TaggedError("NotServed") {};
10060
+ BadRequest = class extends TaggedError("BadRequest") {};
10057
10061
  }));
10058
10062
  //#endregion
10059
10063
  //#region src/cli/upgrade.ts
@@ -10924,6 +10928,16 @@ var init_catalog = __esmMin((() => {
10924
10928
  dataKey: "upgrade",
10925
10929
  example: "adiff upgrade --check --json --fields route,latest,current"
10926
10930
  },
10931
+ {
10932
+ name: "serve",
10933
+ about: "Answer commands one JSON line at a time on stdin and stdout, and report changes to the reviews a client watches. For a program that asks adiff often, such as a review page",
10934
+ group: SET_UP,
10935
+ addresses: "repo",
10936
+ safety: "read",
10937
+ options: [],
10938
+ dataKey: "",
10939
+ example: "echo '{\"id\":1,\"args\":[\"comment\",\"list\",\"--worktree\",\".\"]}' | adiff serve"
10940
+ },
10927
10941
  {
10928
10942
  name: "resume",
10929
10943
  about: "Open the review you left last in this repository. Opens the terminal, like `review open`, on the branch it was opened on most recently",
@@ -11199,6 +11213,16 @@ var init_report$1 = __esmMin((() => {
11199
11213
  suggestion: "That remark is already a comment on this review. `adiff comment list` reports it, and removing that comment frees the remark.",
11200
11214
  retriable: false
11201
11215
  },
11216
+ NotServed: {
11217
+ exit: 2,
11218
+ suggestion: "serve answers only commands that answer in JSON. Run the review terminal, review pane, resume and upgrade on their own.",
11219
+ retriable: false
11220
+ },
11221
+ BadRequest: {
11222
+ exit: 2,
11223
+ suggestion: "A request is one JSON object per line, such as {\"id\":1,\"args\":[\"comment\",\"list\",\"--worktree\",\".\"]} or {\"id\":2,\"watch\":[\"--worktree\",\".\"]}.",
11224
+ retriable: false
11225
+ },
11202
11226
  UnknownField: {
11203
11227
  exit: 2,
11204
11228
  suggestion: "That is not a field this answer carries. The ones it does are named above.",
@@ -11336,6 +11360,122 @@ var init_report$1 = __esmMin((() => {
11336
11360
  };
11337
11361
  }));
11338
11362
  //#endregion
11363
+ //#region src/cli/serve.ts
11364
+ var Replies, toStdout, NOT_SERVED, SETTLE_MS$1, refused, write, answering, settled$1, watching, unwatching, readRequest, handled, listen, serve;
11365
+ var init_serve = __esmMin((() => {
11366
+ init_dist();
11367
+ init_error$5();
11368
+ init_report$1();
11369
+ init_parse$1();
11370
+ init_catalog();
11371
+ Replies = class extends Service()("adiff/Replies") {};
11372
+ toStdout = succeed$2(Replies)({ say: (line) => sync(() => void process.stdout.write(`${line}\n`)) });
11373
+ NOT_SERVED = /* @__PURE__ */ new Set([
11374
+ "review open",
11375
+ "review pane",
11376
+ "resume",
11377
+ "upgrade",
11378
+ "serve"
11379
+ ]);
11380
+ SETTLE_MS$1 = 120;
11381
+ refused = (cause) => {
11382
+ const reported = failure(cause);
11383
+ return {
11384
+ exit: reported.exit,
11385
+ answer: JSON.parse(reported.line)
11386
+ };
11387
+ };
11388
+ write = (line) => {
11389
+ process.stdout.write(`${JSON.stringify(line)}\n`);
11390
+ };
11391
+ answering = (serving, args) => {
11392
+ const name = serving.nameOf(args);
11393
+ if (NOT_SERVED.has(name)) return succeed$1(refused(new NotServed({ command: name })));
11394
+ const heard = [];
11395
+ return serving.run(name, optionsFrom(args, valuedIn(name))).pipe(provideService(Replies, { say: (line) => sync(() => void heard.push(line)) }), map$1(() => ({
11396
+ exit: 0,
11397
+ answer: JSON.parse(heard.at(-1) ?? "{}")
11398
+ })), catchCause((cause) => succeed$1(refused(squash(cause)))));
11399
+ };
11400
+ settled$1 = (folder, tell) => {
11401
+ mkdirSync(folder, { recursive: true });
11402
+ let timer;
11403
+ const watcher = watch(folder, () => {
11404
+ if (timer !== void 0) clearTimeout(timer);
11405
+ timer = setTimeout(tell, SETTLE_MS$1);
11406
+ });
11407
+ watcher.on("error", () => void 0);
11408
+ return watcher;
11409
+ };
11410
+ watching = (serving, request, watchers) => serving.folderOf(optionsFrom(request.watch ?? [], valuedIn("comment list"))).pipe(map$1((folder) => {
11411
+ watchers.get(request.id)?.close();
11412
+ watchers.set(request.id, settled$1(folder, () => write({
11413
+ id: request.id,
11414
+ event: "changed"
11415
+ })));
11416
+ return {
11417
+ exit: 0,
11418
+ answer: {
11419
+ ok: true,
11420
+ watching: folder
11421
+ }
11422
+ };
11423
+ }), catchCause((cause) => succeed$1(refused(squash(cause)))));
11424
+ unwatching = (request, watchers) => {
11425
+ watchers.get(request.id)?.close();
11426
+ watchers.delete(request.id);
11427
+ return {
11428
+ exit: 0,
11429
+ answer: {
11430
+ ok: true,
11431
+ watching: false
11432
+ }
11433
+ };
11434
+ };
11435
+ readRequest = (line) => {
11436
+ try {
11437
+ const parsed = JSON.parse(line);
11438
+ if (typeof parsed !== "object" || parsed === null || !("id" in parsed)) return void 0;
11439
+ return parsed;
11440
+ } catch {
11441
+ return;
11442
+ }
11443
+ };
11444
+ handled = (serving, line, watchers) => {
11445
+ const request = readRequest(line);
11446
+ if (request === void 0) return sync(() => write(refused(new BadRequest({ line }))));
11447
+ const answer = request.unwatch === true ? succeed$1(unwatching(request, watchers)) : request.watch !== void 0 ? watching(serving, request, watchers) : answering(serving, request.args ?? []);
11448
+ return map$1(answer, (said) => write({
11449
+ id: request.id,
11450
+ ...said
11451
+ }));
11452
+ };
11453
+ listen = (serving, listening) => {
11454
+ const lines = createInterface({ input: process.stdin });
11455
+ const heard = (line) => {
11456
+ if (line.trim().length === 0) return;
11457
+ runForkWith(listening.context)(handled(serving, line, listening.watchers));
11458
+ };
11459
+ const closed = () => {
11460
+ for (const watcher of listening.watchers.values()) watcher.close();
11461
+ listening.done();
11462
+ };
11463
+ lines.on("line", heard);
11464
+ lines.on("close", closed);
11465
+ };
11466
+ serve = fn("Cli.serve")(function* (serving) {
11467
+ const context$2 = yield* context();
11468
+ const watchers = /* @__PURE__ */ new Map();
11469
+ yield* callback$1((resume) => {
11470
+ listen(serving, {
11471
+ context: context$2,
11472
+ watchers,
11473
+ done: () => resume(void_)
11474
+ });
11475
+ });
11476
+ });
11477
+ }));
11478
+ //#endregion
11339
11479
  //#region src/cli/index.ts
11340
11480
  var init_cli = __esmMin((() => {
11341
11481
  init_config();
@@ -11344,6 +11484,7 @@ var init_cli = __esmMin((() => {
11344
11484
  init_catalog();
11345
11485
  init_report$1();
11346
11486
  init_error$5();
11487
+ init_serve();
11347
11488
  }));
11348
11489
  //#endregion
11349
11490
  //#region src/domain/patch/model.ts
@@ -11841,7 +11982,7 @@ var init_run = __esmMin((() => {
11841
11982
  gitOrEmpty = fn("Git.runOrEmpty")(function* (cwd, args) {
11842
11983
  return yield* git(cwd, args).pipe(catchTag("GitCommandFailed", () => succeed$1("")));
11843
11984
  });
11844
- })), CACHE_SIZE, NAME_TTL, FRESH_TTL, SPLIT$1, DEFAULT_BRANCH_CANDIDATES, PLAIN_PATHS, STAT, Git, parseStat, readEntries, findDefaultBranch, partsOf$1, findMergeBase, toWorktree, branchTips, findParent, splitLines, absent, readText, settled, seenAs, listWorktrees, readDiff, readStat, readSource, readBlob, readGrep, GENERATED_SAID, markedGenerated, readGenerated, findRepo, LINKED_GIT_DIR, HEAD_REF, gitDirOf, findCommonDir, readHead, REFS_MOST, readCommits, readRefs, refResolves, sharedCommit, makeCaches, shapeWith, makeGit, GitLive;
11985
+ })), CACHE_SIZE, NAME_TTL, FRESH_TTL, SPLIT$1, DEFAULT_BRANCH_CANDIDATES, PLAIN_PATHS, STAT, Git, parseStat, readEntries, verifiedIn, findDefaultBranch, partsOf$1, findMergeBase, toWorktree, branchTips, findParent, splitLines, absent, readText, settled, seenAs, listWorktrees, readDiff, readStat, readSource, readBlob, readGrep, GENERATED_SAID, markedGenerated, readGenerated, askRepo, LINKED_GIT_DIR, HEAD_REF, gitDirOf, findCommonDir, readHead, REFS_MOST, readCommits, readRefs, refResolves, sharedCommit, makeCaches, shapeWith, makeGit, GitLive;
11845
11986
  var init_service$2 = __esmMin((() => {
11846
11987
  init_dist();
11847
11988
  init_error$4();
@@ -11884,15 +12025,15 @@ var init_service$2 = __esmMin((() => {
11884
12025
  }
11885
12026
  return entries;
11886
12027
  };
12028
+ verifiedIn = (repo, candidate) => map$1(gitOrEmpty(repo, [
12029
+ "rev-parse",
12030
+ "--verify",
12031
+ candidate
12032
+ ]), (said) => said.trim().length > 0);
11887
12033
  findDefaultBranch = fn("Git.findDefaultBranch")(function* (repo) {
11888
- const symbolic = yield* gitOrEmpty(repo, ["symbolic-ref", "refs/remotes/origin/HEAD"]);
12034
+ const [symbolic, verified] = yield* all([gitOrEmpty(repo, ["symbolic-ref", "refs/remotes/origin/HEAD"]), forEach(DEFAULT_BRANCH_CANDIDATES, (candidate) => verifiedIn(repo, candidate), { concurrency: "unbounded" })], { concurrency: 2 });
11889
12035
  if (symbolic.trim().length > 0) return symbolic.trim().replace("refs/remotes/", "");
11890
- for (const candidate of DEFAULT_BRANCH_CANDIDATES) if ((yield* gitOrEmpty(repo, [
11891
- "rev-parse",
11892
- "--verify",
11893
- candidate
11894
- ])).trim().length > 0) return candidate;
11895
- return "HEAD";
12036
+ return DEFAULT_BRANCH_CANDIDATES.find((_, at) => verified[at] === true) ?? "HEAD";
11896
12037
  });
11897
12038
  partsOf$1 = (key) => key.split(SPLIT$1);
11898
12039
  findMergeBase = fn("Git.mergeBase")(function* (key) {
@@ -12026,7 +12167,7 @@ var init_service$2 = __esmMin((() => {
12026
12167
  ]);
12027
12168
  return new Set(raw.split("\n").flatMap(markedGenerated));
12028
12169
  });
12029
- findRepo = fn("Git.repoOf")(function* (worktree) {
12170
+ askRepo = fn("Git.askRepo")(function* (worktree) {
12030
12171
  const trimmed = (yield* gitOrEmpty(worktree, [
12031
12172
  "rev-parse",
12032
12173
  "--path-format=absolute",
@@ -12081,14 +12222,16 @@ var init_service$2 = __esmMin((() => {
12081
12222
  "refs/remotes"
12082
12223
  ])).split("\n").map((line) => line.trim()).filter((line) => line.length > 0 && !line.endsWith("/HEAD"));
12083
12224
  });
12084
- refResolves = fn("Git.resolves")(function* (repo, ref) {
12225
+ refResolves = fn("Git.resolves")(function* (asked) {
12226
+ const [repo = "", ref = ""] = asked.split(SPLIT$1);
12085
12227
  return (yield* gitOrEmpty(repo, [
12086
12228
  "rev-parse",
12087
12229
  "--verify",
12088
12230
  `${ref}^{commit}`
12089
12231
  ])).trim().length > 0;
12090
12232
  });
12091
- sharedCommit = fn("Git.sharedWith")(function* (repo, branch, ref) {
12233
+ sharedCommit = fn("Git.sharedWith")(function* (asked) {
12234
+ const [repo = "", branch = "", ref = ""] = asked.split(SPLIT$1);
12092
12235
  return (yield* gitOrEmpty(repo, [
12093
12236
  "merge-base",
12094
12237
  branch,
@@ -12111,12 +12254,27 @@ var init_service$2 = __esmMin((() => {
12111
12254
  capacity: CACHE_SIZE,
12112
12255
  timeToLive: FRESH_TTL,
12113
12256
  lookup: findParent
12257
+ }),
12258
+ resolved: yield* make$11({
12259
+ capacity: CACHE_SIZE,
12260
+ timeToLive: FRESH_TTL,
12261
+ lookup: refResolves
12262
+ }),
12263
+ shared: yield* make$11({
12264
+ capacity: CACHE_SIZE,
12265
+ timeToLive: FRESH_TTL,
12266
+ lookup: sharedCommit
12267
+ }),
12268
+ repos: yield* make$11({
12269
+ capacity: CACHE_SIZE,
12270
+ timeToLive: NAME_TTL,
12271
+ lookup: askRepo
12114
12272
  })
12115
12273
  };
12116
12274
  });
12117
12275
  shapeWith = (caches) => ({
12118
12276
  worktrees: (repo) => listWorktrees(caches, repo),
12119
- repoOf: findRepo,
12277
+ repoOf: (worktree) => get(caches.repos, worktree),
12120
12278
  commonDirOf: findCommonDir,
12121
12279
  realPathOf: settled,
12122
12280
  headOf: readHead,
@@ -12130,8 +12288,8 @@ var init_service$2 = __esmMin((() => {
12130
12288
  stackParent: (repo, branch) => get(caches.baseName, repo).pipe(flatMap((fallback) => get(caches.parent, `${repo}${SPLIT$1}${branch}${SPLIT$1}${fallback}`))),
12131
12289
  refs: readRefs,
12132
12290
  commits: (repo, branch, most) => readCommits(repo, branch, most),
12133
- resolves: refResolves,
12134
- sharedWith: sharedCommit
12291
+ resolves: (repo, ref) => get(caches.resolved, `${repo}${SPLIT$1}${ref}`),
12292
+ sharedWith: (repo, branch, ref) => get(caches.shared, `${repo}${SPLIT$1}${branch}${SPLIT$1}${ref}`)
12135
12293
  });
12136
12294
  makeGit = fn("Git.make")(function* () {
12137
12295
  return shapeWith(yield* makeCaches());
@@ -12319,7 +12477,10 @@ var init_paths = __esmMin((() => {
12319
12477
  upgradePath = (root) => join(root, "upgrade.json");
12320
12478
  reportsDir = (root) => join(root, "reports");
12321
12479
  reportPath = (root, stamp) => join(reportsDir(root), `${stamp}.md`);
12322
- })), Store, ensureDir, readOptional, missing$2, damaged, jsonOf$2, decoded, unwritable, wrote, added$1, INDENT, DRAFTS_VERSION, encoded, writes, appends, writeSettings, writeUpgradeCheck, writeState, writeLayers, writeRemarks, writeDrafts, writeBatch, writeAnswer, asSettings, asUpgradeCheck, asBatch, asAnswer, asState, asLayers, asRemarks, asDrafts, asWatching, linesOf, readLines, parseSettings, parseUpgradeCheck, parseState, parseLayers, parseRemarks, idsIn$1, takes, cursorOps, settingsOps, upgradeOps, reportOps, branchKeyIn, wasKeyOf, there, moved, adopt, SPLIT, ADOPT_SIZE, adopting, keyIn, answerOps, layersOps, remarksOps, inboxOps, STATE_LOCK, DRAFTS_LOCK, held$2, stale$1, stolen, taken, freed, alone, watchOps, draftsOps, stateOps, makeStore, madeStore, storeAt;
12480
+ }));
12481
+ //#endregion
12482
+ //#region src/service/store/service.ts
12483
+ var Store, ensureDir, readOptional, missing$2, damaged, jsonOf$2, decoded, unwritable, wrote, added$1, INDENT, DRAFTS_VERSION, encoded, writes, appends, writeSettings, writeUpgradeCheck, writeState, writeLayers, writeRemarks, writeDrafts, writeBatch, writeAnswer, asSettings, asUpgradeCheck, asBatch, asAnswer, asState, asLayers, asRemarks, asDrafts, asWatching, linesOf, readLines, parseSettings, parseUpgradeCheck, parseState, parseLayers, parseRemarks, idsIn$1, takes, cursorOps, settingsOps, upgradeOps, reportOps, branchKeyIn, branchKeyOf, wasKeyOf, there, moved, adopt, SPLIT, ADOPT_SIZE, adopting, keyIn, answerOps, layersOps, remarksOps, inboxOps, STATE_LOCK, DRAFTS_LOCK, held$2, stale$1, stolen, taken, freed, alone, watchOps, draftsOps, stateOps, makeStore, madeStore, storeAt;
12323
12484
  var init_service$1 = __esmMin((() => {
12324
12485
  init_dist();
12325
12486
  init_git();
@@ -12499,7 +12660,7 @@ var init_service$1 = __esmMin((() => {
12499
12660
  const [repo, head] = yield* all([git.commonDirOf(worktreePath), git.headOf(worktreePath)], { concurrency: 2 });
12500
12661
  return `${repo}#${head}`;
12501
12662
  });
12502
- fn("Store.branchKeyOf")(function* (worktreePath) {
12663
+ branchKeyOf = fn("Store.branchKeyOf")(function* (worktreePath) {
12503
12664
  return yield* branchKeyIn(yield* Git, worktreePath);
12504
12665
  });
12505
12666
  wasKeyOf = fn("Store.wasKeyOf")(function* (git, worktreePath) {
@@ -13740,7 +13901,7 @@ var init_error$1 = __esmMin((() => {
13740
13901
  }));
13741
13902
  //#endregion
13742
13903
  //#region src/service/forge/service.ts
13743
- var Forge, LIMIT, TIMEOUT_MS, SEND_TIMEOUT_MS, MOST_OUTPUT, FIELDS$1, Author, Row, Viewer, readViewer, decode$1, SAID, stateOf$1, ended, ask$1, show$2, whoseOf, pullOf, read$2, viewerOf, pulls, openPull, NUMBER_FIELDS, Named, readNamed, gh, named$2, head, sideName, commentBody, bodyFor, Landed, readLanded, jsonOf$1, keyOf$2, counted$1, acknowledged, landedIn, THREADS, Said, Thread, Page, Held$1, Threads, readThreads, ANONYMOUS, heardFrom$1, someLine, hasNoLine, quotedIn, spanIn, remarkOf, ownerOf, HERE, asked, whereOf, threadsIn, unresolved, PAGES, everyThread, answer$2, remarks, review, address, ForgeLive;
13904
+ var Forge, LIMIT, TIMEOUT_MS, SEND_TIMEOUT_MS, MOST_OUTPUT, FIELDS$1, Author, Row, Viewer, readViewer, decode$1, SAID, stateOf$1, ended, ask$1, show$2, whoseOf, pullOf, read$2, viewerOf, pulls, openPull, NUMBER_FIELDS, Named, readNamed, gh, named$2, head, sideName, commentBody, bodyFor, Landed, readLanded, jsonOf$1, keyOf$2, counted$1, acknowledged, landedIn, THREADS, Said, Thread, Page, Held$1, Threads, readThreads, ANONYMOUS, heardFrom$1, someLine, hasNoLine, quotedIn, spanIn, remarkOf, ownerOf, HERE, asked$1, whereOf, threadsIn, unresolved, PAGES, everyThread, answer$2, remarks, review, address, ForgeLive;
13744
13905
  var init_service = __esmMin((() => {
13745
13906
  init_dist();
13746
13907
  init_error$1();
@@ -14066,7 +14227,7 @@ var init_service = __esmMin((() => {
14066
14227
  "-F",
14067
14228
  "name={repo}"
14068
14229
  ];
14069
- asked = (repo, branch, after) => gh(repo, [
14230
+ asked$1 = (repo, branch, after) => gh(repo, [
14070
14231
  "api",
14071
14232
  "graphql",
14072
14233
  "-f",
@@ -14107,7 +14268,7 @@ var init_service = __esmMin((() => {
14107
14268
  const held = [];
14108
14269
  let after;
14109
14270
  for (let page = 0; page < PAGES; page += 1) {
14110
- const raw = yield* asked(repo, branch, after);
14271
+ const raw = yield* asked$1(repo, branch, after);
14111
14272
  const found = yield* threadsIn(repo, raw);
14112
14273
  if (found === void 0) return held;
14113
14274
  held.push(...found.nodes);
@@ -22759,7 +22920,7 @@ var init_remarks = __esmMin((() => {
22759
22920
  }));
22760
22921
  //#endregion
22761
22922
  //#region src/tui/branches.ts
22762
- var openedPull, openedOn, resumeAt, openBranch, readBranch, fillBranches, reloadList, reloadBranch, goBack, loadPulls, loadHeld, showPull, openBases, basedOnRef, clearBaseHere, afterBase, setBaseHere, noticeAnswers, sameSent, noticeFiled, noticeOnList;
22923
+ var openedPull, openedOn, resumeAt, openBranch, readBranch, fillBranches, reloadList, reloadBranch, goBack, loadPulls, loadHeld, showPull, openBases, basedOnRef, clearBaseHere, afterBase, setBaseHere, noticeAnswers, sameSent, sameMarks, noticeFiled, noticeOnList;
22763
22924
  var init_branches = __esmMin((() => {
22764
22925
  init_dist();
22765
22926
  init_forge();
@@ -22815,14 +22976,14 @@ var init_branches = __esmMin((() => {
22815
22976
  const reading$1 = yield* reading(app.repo, name, app.base);
22816
22977
  app.reading = reading$1;
22817
22978
  yield* markOpened(reading$1.worktree, (/* @__PURE__ */ new Date()).toISOString());
22818
- const [progress$1, layers, sent, remarks, drafts] = yield* all([
22979
+ const [progress$2, layers, sent, remarks, drafts] = yield* all([
22819
22980
  progress(reading$1),
22820
22981
  read(reading$1),
22821
22982
  listSent(reading$1),
22822
22983
  app.state.remarksOn ? list$2(reading$1) : succeed$1([]),
22823
22984
  list(reading$1.worktree)
22824
22985
  ], { concurrency: "unbounded" });
22825
- const opened = withVouched(withPatches(app.state, reading$1.patches), progress$1.vouched);
22986
+ const opened = withVouched(withPatches(app.state, reading$1.patches), progress$2.vouched);
22826
22987
  const held = drafts.length > 0 || theirPull(app.state) ? heldOf(drafts) : app.state.held;
22827
22988
  return withRemarks(withLayers(withSent({
22828
22989
  ...opened,
@@ -22982,16 +23143,18 @@ var init_branches = __esmMin((() => {
22982
23143
  });
22983
23144
  };
22984
23145
  sameSent = (one, other) => JSON.stringify(one) === JSON.stringify(other);
23146
+ sameMarks = (state, progress) => JSON.stringify([state.vouched, state.partsRead]) === JSON.stringify([progress.vouched, progress.parts]);
22985
23147
  noticeFiled = (app) => {
22986
23148
  return gen(function* () {
22987
23149
  const branch = selectedBranch(app.state);
22988
23150
  if (branch === void 0) return;
22989
- const sent = yield* loadSent(app, branch.branch);
22990
- if (sameSent(app.state.sent, sent)) return;
22991
- app.commit({
23151
+ const reading = yield* readingOf(app, branch.branch);
23152
+ const [sent, progress$1] = yield* all([listSent(reading), progress(reading)]);
23153
+ if (sameSent(app.state.sent, sent) && sameMarks(app.state, progress$1)) return;
23154
+ app.commit(withVouched({
22992
23155
  ...app.state,
22993
23156
  sent
22994
- });
23157
+ }, progress$1.vouched, progress$1.parts));
22995
23158
  });
22996
23159
  };
22997
23160
  noticeOnList = (app) => {
@@ -25055,18 +25218,16 @@ init_git();
25055
25218
  init_forge();
25056
25219
  init_store();
25057
25220
  const WAIT_UNIT = 1e3;
25058
- const answer = (options, body) => {
25221
+ const answer = fn("Main.answer")(function* (options, body) {
25059
25222
  const fields = fieldsOf(options);
25060
25223
  const strange = strangeField(body, fields);
25061
- if (strange !== void 0) return fail(new UnknownField(strange));
25062
- return sync(() => {
25063
- const narrowed = Object.fromEntries(Object.entries(body).map(([key, value]) => [key, narrow(value, fields)]));
25064
- process.stdout.write(`${JSON.stringify({
25065
- ok: true,
25066
- ...narrowed
25067
- })}\n`);
25068
- });
25069
- };
25224
+ if (strange !== void 0) return yield* new UnknownField(strange);
25225
+ const narrowed = Object.fromEntries(Object.entries(body).map(([key, value]) => [key, narrow(value, fields)]));
25226
+ return yield* (yield* Replies).say(JSON.stringify({
25227
+ ok: true,
25228
+ ...narrowed
25229
+ }));
25230
+ });
25070
25231
  const worktreeIn = fn("Main.worktreeIn")(function* (options) {
25071
25232
  return yield* find(yield* required(options, "repo"), yield* required(options, "branch"));
25072
25233
  });
@@ -25467,6 +25628,17 @@ const nameOf = (argv) => {
25467
25628
  if (findCommand(pair) !== void 0) return pair;
25468
25629
  return words.length > 1 ? pair : words[0] ?? "";
25469
25630
  };
25631
+ const storeRoot = () => process.env["ADIFF_ROOT"] ?? defaultRoot();
25632
+ const folderOf = fn("Main.folderOf")(function* (given) {
25633
+ const options = yield* addressOf("comment list", given);
25634
+ const worktree = yield* find(yield* required(options, "repo"), yield* required(options, "branch"));
25635
+ return branchDir(storeRoot(), yield* branchKeyOf(worktree.path));
25636
+ });
25637
+ const serving = () => serve({
25638
+ nameOf,
25639
+ run,
25640
+ folderOf
25641
+ });
25470
25642
  const argv = process.argv.slice(2);
25471
25643
  const ASKS = {
25472
25644
  "--version": version,
@@ -25495,12 +25667,14 @@ if (said !== void 0) {
25495
25667
  process.stdout.write(`${said}\n`);
25496
25668
  process.exit(0);
25497
25669
  }
25498
- const layer = mergeAll(ForgeLive, storeAt(process.env["ADIFF_ROOT"] ?? defaultRoot())).pipe(provideMerge(GitLive));
25670
+ const layer = mergeAll(ForgeLive, toStdout, storeAt(storeRoot())).pipe(provideMerge(GitLive));
25499
25671
  const reportFailure = (cause) => sync(() => {
25500
25672
  const reported = failure(squash(cause));
25501
25673
  process.stderr.write(`${reported.line}\n`);
25502
25674
  process.exitCode = reported.exit;
25503
25675
  });
25504
- runFork(run(opening ? "review open" : nameOf(argv), opening ? { repo: "." } : optionsFrom(argv, valuedIn(nameOf(argv)))).pipe(provide(layer), catchCause(reportFailure)));
25676
+ const asked = opening ? "review open" : nameOf(argv);
25677
+ const started = asked === "serve" ? serving() : run(asked, opening ? { repo: "." } : optionsFrom(argv, valuedIn(asked)));
25678
+ runFork(started.pipe(provide(layer), catchCause(reportFailure)));
25505
25679
  //#endregion
25506
25680
  export {};
package/package.json CHANGED
@@ -23,7 +23,7 @@
23
23
  "bin": {
24
24
  "adiff": "./bin/adiff.js"
25
25
  },
26
- "version": "0.1.0-alpha.187",
26
+ "version": "0.1.0-alpha.189",
27
27
  "description": "Review the work an agent left you without losing the thread: comments live on the lines, the agent answers them, and each point stays open until you settle it.",
28
28
  "license": "MIT",
29
29
  "repository": {