@bojackduy/opencode-learn 1.2.3 → 1.2.4

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.
package/dist/server.js CHANGED
@@ -531,26 +531,57 @@ function watchAndInject(client, directory, id, sessionID, buildText) {
531
531
  }
532
532
  const dir = pendingDir(directory);
533
533
  const respPath = path.join(dir, `response-${id}.json`);
534
- const fire = async () => {
535
- let data;
534
+ const claimPath = path.join(dir, `response-${id}.claim-${process.pid}.json`);
535
+ const pendingCandidates = [path.join(dir, `quiz-${id}.json`), path.join(dir, `quiz_batch-${id}.json`)];
536
+ const closeWatcher = () => {
537
+ const w = activeWatchers.get(id);
538
+ if (w) {
539
+ try {
540
+ w.close();
541
+ } catch {}
542
+ activeWatchers.delete(id);
543
+ }
544
+ };
545
+ const fire = async (attempt = 0) => {
536
546
  try {
537
- data = JSON.parse(fs.readFileSync(respPath, "utf8"));
547
+ fs.renameSync(respPath, claimPath);
538
548
  } catch {
549
+ closeWatcher();
539
550
  return;
540
551
  }
552
+ let data;
541
553
  try {
542
- fs.unlinkSync(respPath);
543
- } catch {}
544
- const w = activeWatchers.get(id);
545
- if (w) {
554
+ data = JSON.parse(fs.readFileSync(claimPath, "utf8"));
555
+ } catch (e) {
556
+ if (attempt < 5) {
557
+ await new Promise((r) => setTimeout(r, 120));
558
+ try {
559
+ fs.renameSync(claimPath, respPath);
560
+ } catch {}
561
+ await new Promise((r) => setTimeout(r, 60));
562
+ return fire(attempt + 1);
563
+ }
564
+ slog("watchAndInject UNREADABLE response, parked", id, String(e).slice(0, 160));
546
565
  try {
547
- w.close();
566
+ fs.renameSync(claimPath, path.join(dir, `response-${id}.poisoned-${Date.now()}.json`));
548
567
  } catch {}
549
- activeWatchers.delete(id);
568
+ closeWatcher();
569
+ return;
570
+ }
571
+ let text;
572
+ let effectiveSessionID;
573
+ try {
574
+ slog("watchAndInject fire", id, JSON.stringify(data).slice(0, 400));
575
+ effectiveSessionID = data?.sessionID || sessionID;
576
+ text = data?.cancelled ? `[cancelled] user dismissed the popup for ${id}` : buildText(data.result);
577
+ } catch (e) {
578
+ slog("watchAndInject buildText ERROR, parked", id, String(e).slice(0, 200));
579
+ try {
580
+ fs.renameSync(claimPath, path.join(dir, `response-${id}.poisoned-${Date.now()}.json`));
581
+ } catch {}
582
+ closeWatcher();
583
+ return;
550
584
  }
551
- slog("watchAndInject fire", id, JSON.stringify(data).slice(0, 400));
552
- const effectiveSessionID = data?.sessionID || sessionID;
553
- const text = data?.cancelled ? `[cancelled] user dismissed the popup for ${id}` : buildText(data.result);
554
585
  const sdkCall = async (method, ...argsList) => {
555
586
  let firstErr;
556
587
  for (const args of argsList) {
@@ -576,35 +607,60 @@ function watchAndInject(client, directory, id, sessionID, buildText) {
576
607
  ];
577
608
  slog("watchAndInject injecting", id, effectiveSessionID, text.slice(0, 300));
578
609
  let ok = false;
610
+ let firstErr;
579
611
  if (client?.session?.promptAsync) {
580
612
  try {
581
613
  await sdkCall(client.session.promptAsync.bind(client.session), ...shapes);
582
614
  ok = true;
583
- } catch {}
615
+ } catch (e) {
616
+ firstErr = e;
617
+ }
584
618
  }
585
619
  if (!ok && client?.session?.prompt) {
586
620
  try {
587
621
  await sdkCall(client.session.prompt.bind(client.session), ...shapes);
588
622
  ok = true;
623
+ } catch (e) {
624
+ firstErr = firstErr || e;
625
+ }
626
+ }
627
+ if (!ok) {
628
+ slog("watchAndInject inject FAILED, preserved", id, effectiveSessionID, String(firstErr).slice(0, 200));
629
+ try {
630
+ fs.renameSync(claimPath, path.join(dir, `response-${id}.failed-${Date.now()}.json`));
631
+ } catch {}
632
+ try {
633
+ await client.app.log({ body: { service: "learn", level: "error", message: `inject FAILED for ${effectiveSessionID} (orig ${sessionID})`, extra: { id } } });
589
634
  } catch {}
635
+ closeWatcher();
636
+ return;
590
637
  }
591
638
  try {
592
- await client.app.log({ body: { service: "learn", level: ok ? "info" : "error", message: ok ? `injected into ${effectiveSessionID}` : `inject FAILED for ${effectiveSessionID} (orig ${sessionID})`, extra: { id } } });
639
+ fs.unlinkSync(claimPath);
640
+ } catch {}
641
+ for (const p of pendingCandidates)
642
+ try {
643
+ fs.unlinkSync(p);
644
+ } catch {}
645
+ closeWatcher();
646
+ slog("watchAndInject consumed", id, effectiveSessionID);
647
+ try {
648
+ await client.app.log({ body: { service: "learn", level: "info", message: `injected into ${effectiveSessionID}`, extra: { id } } });
593
649
  } catch {}
594
650
  };
595
- if (fs.existsSync(respPath)) {
596
- slog("watchAndInject fast-path", id);
597
- fire();
598
- return;
599
- }
600
651
  try {
601
652
  const w = fs.watch(dir, (_e, filename) => {
602
- if (filename === `response-${id}.json` && fs.existsSync(respPath))
653
+ if (filename === `response-${id}.json`)
603
654
  fire();
604
655
  });
605
656
  w.on("error", () => {});
606
657
  activeWatchers.set(id, w);
607
658
  } catch {}
659
+ if (fs.existsSync(respPath)) {
660
+ slog("watchAndInject fast-path", id);
661
+ fire();
662
+ return;
663
+ }
608
664
  }
609
665
  var server = async ({ client, directory }) => {
610
666
  const markerPath = path.join(directory, ".opencode", "learn-md-log.json");
@@ -862,6 +918,20 @@ Return ONLY JSON: {"inferred":[2],"semanticCorrect":false,"reason":"...","isIDK"
862
918
  try {
863
919
  const dir = pendingDir(directory);
864
920
  if (fs.existsSync(dir)) {
921
+ for (const f of fs.readdirSync(dir).filter((x) => x.includes(".claim-") && x.endsWith(".json"))) {
922
+ try {
923
+ const m = f.match(/^response-(.+)\.claim-.*\.json$/);
924
+ if (!m)
925
+ continue;
926
+ const rid = m[1];
927
+ const target = path.join(dir, `response-${rid}.json`);
928
+ const age = Date.now() - fs.statSync(path.join(dir, f)).mtimeMs;
929
+ if (age > 30000 && !fs.existsSync(target)) {
930
+ fs.renameSync(path.join(dir, f), target);
931
+ slog("watchAndInject requeued stale claim", rid);
932
+ }
933
+ } catch {}
934
+ }
865
935
  for (const f of fs.readdirSync(dir).filter((x) => x.endsWith(".json") && !x.startsWith("response-") && !x.startsWith(".") && !x.startsWith("classify"))) {
866
936
  try {
867
937
  const j = JSON.parse(fs.readFileSync(path.join(dir, f), "utf8"));
@@ -918,6 +988,19 @@ Explanation: ${j.explanation}${note}`;
918
988
  }
919
989
  } catch {}
920
990
  }
991
+ for (const f of fs.readdirSync(dir).filter((x) => x.startsWith("response-") && x.endsWith(".json") && !x.includes(".claim-") && !x.includes(".poisoned") && !x.includes(".failed") && !x.includes(".orphaned"))) {
992
+ try {
993
+ const m = f.match(/^response-(.+)\.json$/);
994
+ if (!m)
995
+ continue;
996
+ const rid = m[1];
997
+ const hasPending = fs.existsSync(path.join(dir, `quiz-${rid}.json`)) || fs.existsSync(path.join(dir, `quiz_batch-${rid}.json`));
998
+ if (!hasPending) {
999
+ fs.renameSync(path.join(dir, f), path.join(dir, `response-${rid}.orphaned-${Date.now()}.json`));
1000
+ slog("watchAndInject orphaned response parked (no pending context)", rid);
1001
+ }
1002
+ } catch {}
1003
+ }
921
1004
  }
922
1005
  } catch {}
923
1006
  return {
package/dist/tui.js CHANGED
@@ -237,6 +237,17 @@ function ensureDir(dir) {
237
237
  });
238
238
  } catch {}
239
239
  }
240
+ function writeJsonAtomic(filePath, data) {
241
+ try {
242
+ const tmp = `${filePath}.tmp-${process.pid}-${Date.now()}-${Math.floor(Math.random() * 1e6)}`;
243
+ fs.writeFileSync(tmp, JSON.stringify(data), "utf8");
244
+ fs.renameSync(tmp, filePath);
245
+ } catch {
246
+ try {
247
+ fs.writeFileSync(filePath, JSON.stringify(data), "utf8");
248
+ } catch {}
249
+ }
250
+ }
240
251
  function decodeQuizText(s) {
241
252
  if (!s || typeof s !== "string")
242
253
  return s;
@@ -391,7 +402,7 @@ function QuizDialog(props) {
391
402
  timestamp: Date.now(),
392
403
  sessionID: props.request.sessionID || routeSessionID
393
404
  };
394
- fs.writeFileSync(path.join(pDir, `classify-${props.request.id}.json`), JSON.stringify(pendingClassify), "utf8");
405
+ writeJsonAtomic(path.join(pDir, `classify-${props.request.id}.json`), pendingClassify);
395
406
  tlog("QuizDialog classify request", props.request.id, note().trim().slice(0, 50));
396
407
  const respPath = path.join(pDir, `classify-response-${props.request.id}.json`);
397
408
  let attempts = 0;
@@ -1673,7 +1684,7 @@ function QuizBatchDialog(props) {
1673
1684
  timestamp: Date.now(),
1674
1685
  sessionID: props.request.sessionID || routeSessionID
1675
1686
  };
1676
- fs.writeFileSync(path.join(pDir, `classify-${cid}.json`), JSON.stringify(pendingClassify), "utf8");
1687
+ writeJsonAtomic(path.join(pDir, `classify-${cid}.json`), pendingClassify);
1677
1688
  tlog("QuizBatchDialog classify request", cid, note().trim().slice(0, 50));
1678
1689
  const respPath = path.join(pDir, `classify-response-${cid}.json`);
1679
1690
  let attempts = 0;
@@ -2642,7 +2653,13 @@ var tui = async (api) => {
2642
2653
  } catch {
2643
2654
  return null;
2644
2655
  }
2645
- }).filter(Boolean);
2656
+ }).filter(Boolean).filter((x) => {
2657
+ try {
2658
+ return !fs.existsSync(path.join(pendingDir, `response-${x.j.id}.json`));
2659
+ } catch {
2660
+ return true;
2661
+ }
2662
+ });
2646
2663
  const pick = matching.find((x) => x.j.sessionID === curSid) || matching.find((x) => !x.j.sessionID);
2647
2664
  if (!pick)
2648
2665
  return;
@@ -2682,15 +2699,15 @@ var tui = async (api) => {
2682
2699
  currentBySession.set(curSid, current);
2683
2700
  const done = async (result) => {
2684
2701
  const respPath = path.join(pendingDir, `response-${data.id}.json`);
2685
- try {
2686
- fs.writeFileSync(respPath, JSON.stringify({
2687
- id: data.id,
2688
- type: data.type,
2689
- result,
2690
- sessionID: data.sessionID,
2691
- at: Date.now()
2692
- }), "utf8");
2693
- } catch {}
2702
+ const answerId = data.id;
2703
+ tlog("learn-tui answered", data.type, answerId, JSON.stringify(result).slice(0, 160));
2704
+ writeJsonAtomic(respPath, {
2705
+ id: data.id,
2706
+ type: data.type,
2707
+ result,
2708
+ sessionID: data.sessionID,
2709
+ at: Date.now()
2710
+ });
2694
2711
  try {
2695
2712
  const sessionID = data.sessionID;
2696
2713
  let injectText = "";
@@ -2780,24 +2797,30 @@ var tui = async (api) => {
2780
2797
  }
2781
2798
  }
2782
2799
  } catch {}
2783
- try {
2784
- fs.unlinkSync(full);
2785
- } catch {}
2786
2800
  api.ui.dialog.clear();
2787
2801
  currentBySession.delete(curSid);
2788
2802
  setTimeout(processPending, 150);
2803
+ setTimeout(() => {
2804
+ try {
2805
+ if (fs.existsSync(respPath)) {
2806
+ tlog("learn-tui response NOT consumed, re-touching", answerId);
2807
+ try {
2808
+ writeJsonAtomic(respPath, JSON.parse(fs.readFileSync(respPath, "utf8")));
2809
+ } catch {}
2810
+ }
2811
+ } catch {}
2812
+ }, 8000);
2789
2813
  };
2790
2814
  const cancel = async () => {
2791
2815
  const respPath = path.join(pendingDir, `response-${data.id}.json`);
2792
- try {
2793
- fs.writeFileSync(respPath, JSON.stringify({
2794
- id: data.id,
2795
- type: data.type,
2796
- cancelled: true,
2797
- sessionID: data.sessionID,
2798
- at: Date.now()
2799
- }), "utf8");
2800
- } catch {}
2816
+ tlog("learn-tui cancelled", data.type, data.id);
2817
+ writeJsonAtomic(respPath, {
2818
+ id: data.id,
2819
+ type: data.type,
2820
+ cancelled: true,
2821
+ sessionID: data.sessionID,
2822
+ at: Date.now()
2823
+ });
2801
2824
  try {
2802
2825
  const sid = data.sessionID;
2803
2826
  if (sid) {
@@ -2833,9 +2856,6 @@ var tui = async (api) => {
2833
2856
  } catch {}
2834
2857
  }
2835
2858
  } catch {}
2836
- try {
2837
- fs.unlinkSync(full);
2838
- } catch {}
2839
2859
  api.ui.dialog.clear();
2840
2860
  currentBySession.delete(curSid);
2841
2861
  setTimeout(processPending, 150);
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package.json",
3
3
  "name": "@bojackduy/opencode-learn",
4
- "version": "1.2.3",
4
+ "version": "1.2.4",
5
5
  "description": "Pi learn system for OpenCode — Socratic teaching, graded quiz, Obsidian md_log, and visual makers. Port of amosblomqvist/learn (video: How I Use AI to Learn Things) to OpenCode.",
6
6
  "type": "module",
7
7
  "license": "AGPL-3.0-or-later",
@@ -53,6 +53,14 @@ import { tmpdir } from "node:os"
53
53
  const TUI_LOG = path.join(tmpdir(), "learn-tui.log")
54
54
  function tlog(...a: any[]) { try { fs.appendFileSync(TUI_LOG, `[${new Date().toISOString()}] ${a.map(x=> typeof x==="string"? x : JSON.stringify(x)).join(" ")}\n`) } catch {} }
55
55
  function ensureDir(dir: string) { try { fs.mkdirSync(dir, { recursive: true }) } catch {} }
56
+ function writeJsonAtomic(filePath: string, data: any) {
57
+ // Atomic handoff: readers never observe partial JSON (tmp + rename is atomic on POSIX)
58
+ try {
59
+ const tmp = `${filePath}.tmp-${process.pid}-${Date.now()}-${Math.floor(Math.random() * 1e6)}`
60
+ fs.writeFileSync(tmp, JSON.stringify(data), "utf8")
61
+ fs.renameSync(tmp, filePath)
62
+ } catch { try { fs.writeFileSync(filePath, JSON.stringify(data), "utf8") } catch {} }
63
+ }
56
64
  function decodeQuizText(s: string): string {
57
65
  if (!s || typeof s !== "string") return s
58
66
  if (!s.includes("\\")) return s
@@ -184,7 +192,7 @@ function QuizDialog(props: {
184
192
  const pDir = (globalThis as any).__learnPendingDir || ".opencode/learn-pending"
185
193
  const routeSessionID = (props.api.route as any)?.current?.params?.sessionID
186
194
  const pendingClassify = { id: props.request.id, type: "classify" as const, note: note().trim(), question: props.request.question, options: options().map((o: any, i: number) => ({ label: o.label, value: o.value, index: i + 1 })), multiSelect: isMulti(), timestamp: Date.now(), sessionID: props.request.sessionID || routeSessionID }
187
- fs.writeFileSync(path.join(pDir, `classify-${props.request.id}.json`), JSON.stringify(pendingClassify), "utf8")
195
+ writeJsonAtomic(path.join(pDir, `classify-${props.request.id}.json`), pendingClassify)
188
196
  tlog("QuizDialog classify request", props.request.id, note().trim().slice(0, 50))
189
197
  // Poll for classify-response
190
198
  const respPath = path.join(pDir, `classify-response-${props.request.id}.json`)
@@ -609,7 +617,7 @@ function QuizBatchDialog(props: {
609
617
  const cid = `${props.request.id}-${idx()}`
610
618
  const routeSessionID = (props.api.route as any)?.current?.params?.sessionID
611
619
  const pendingClassify = { id: cid, type: "classify" as const, note: note().trim(), question: cur().question, options: cur().options.map((o: any, i: number) => ({ label: o.label, value: o.value, index: i + 1 })), multiSelect: isMulti(), timestamp: Date.now(), sessionID: props.request.sessionID || routeSessionID }
612
- fs.writeFileSync(path.join(pDir, `classify-${cid}.json`), JSON.stringify(pendingClassify), "utf8")
620
+ writeJsonAtomic(path.join(pDir, `classify-${cid}.json`), pendingClassify)
613
621
  tlog("QuizBatchDialog classify request", cid, note().trim().slice(0, 50))
614
622
  const respPath = path.join(pDir, `classify-response-${cid}.json`)
615
623
  let attempts = 0
@@ -778,8 +786,11 @@ export const tui: TuiPlugin = async (api) => {
778
786
  if (api.ui.dialog.open) return
779
787
  let files: string[] = []
780
788
  try { files = fs.readdirSync(pendingDir).filter(f => f.endsWith(".json") && !f.startsWith("response-") && !f.startsWith(".") && !f.startsWith("classify")).sort() } catch { return }
781
- // Session-distinct: only show pending for current session
782
- const matching = files.map(f => { try { const j = JSON.parse(fs.readFileSync(path.join(pendingDir, f), "utf8")) as any; return { f, j } } catch { return null } }).filter(Boolean) as Array<{f: string, j: any}>
789
+ // Session-distinct: only show pending for current session.
790
+ // Skip answered-pending (a response file exists, server is consuming): prevents re-popup after answer.
791
+ const matching = files.map(f => { try { const j = JSON.parse(fs.readFileSync(path.join(pendingDir, f), "utf8")) as any; return { f, j } } catch { return null } }).filter(Boolean).filter(x => {
792
+ try { return !fs.existsSync(path.join(pendingDir, `response-${x!.j.id}.json`)) } catch { return true }
793
+ }) as Array<{f: string, j: any}>
783
794
  const pick = matching.find(x => x.j.sessionID === curSid) || matching.find(x => !x.j.sessionID)
784
795
  if (!pick) return
785
796
  const file = pick.f
@@ -803,7 +814,9 @@ export const tui: TuiPlugin = async (api) => {
803
814
  currentBySession.set(curSid, current)
804
815
  const done = async (result: any) => {
805
816
  const respPath = path.join(pendingDir, `response-${data!.id}.json`)
806
- try { fs.writeFileSync(respPath, JSON.stringify({ id: data!.id, type: data!.type, result, sessionID: (data as any).sessionID, at: Date.now() }), "utf8") } catch {}
817
+ const answerId = data!.id
818
+ tlog("learn-tui answered", (data as any).type, answerId, JSON.stringify(result).slice(0, 160))
819
+ writeJsonAtomic(respPath, { id: data!.id, type: data!.type, result, sessionID: (data as any).sessionID, at: Date.now() })
807
820
  // Non-blocking wake: inject answer as new user prompt so agent continues (no timeout, no polling waste)
808
821
  try {
809
822
  const sessionID = (data as any).sessionID
@@ -862,14 +875,26 @@ export const tui: TuiPlugin = async (api) => {
862
875
  }
863
876
  }
864
877
  } catch {}
865
- try { fs.unlinkSync(full) } catch {}
878
+ // Server owns lifecycle: it unlinks the pending file after successful inject.
879
+ // Do NOT delete pending here — deleting it destroys recovery context if the server hasn't consumed the response yet.
866
880
  api.ui.dialog.clear()
867
881
  currentBySession.delete(curSid)
868
882
  setTimeout(processPending, 150)
883
+ // Watchdog: if the response is still unconsumed after 8s, re-touch to retrigger the server watch + log loudly.
884
+ // Safe: server claims via atomic rename, so a rewrite can never cause double-inject.
885
+ setTimeout(() => {
886
+ try {
887
+ if (fs.existsSync(respPath)) {
888
+ tlog("learn-tui response NOT consumed, re-touching", answerId)
889
+ try { writeJsonAtomic(respPath, JSON.parse(fs.readFileSync(respPath, "utf8"))) } catch {}
890
+ }
891
+ } catch {}
892
+ }, 8000)
869
893
  }
870
894
  const cancel = async () => {
871
895
  const respPath = path.join(pendingDir, `response-${data!.id}.json`)
872
- try { fs.writeFileSync(respPath, JSON.stringify({ id: data!.id, type: data!.type, cancelled: true, sessionID: (data as any).sessionID, at: Date.now() }), "utf8") } catch {}
896
+ tlog("learn-tui cancelled", (data as any).type, data!.id)
897
+ writeJsonAtomic(respPath, { id: data!.id, type: data!.type, cancelled: true, sessionID: (data as any).sessionID, at: Date.now() })
873
898
  try {
874
899
  const sid = (data as any).sessionID
875
900
  if (sid) {
@@ -885,7 +910,7 @@ export const tui: TuiPlugin = async (api) => {
885
910
  } catch {}
886
911
  }
887
912
  } catch {}
888
- try { fs.unlinkSync(full) } catch {}
913
+ // Server owns lifecycle: it unlinks the pending file after consuming the cancelled response.
889
914
  api.ui.dialog.clear()
890
915
  currentBySession.delete(curSid)
891
916
  setTimeout(processPending, 150)
package/plugins/learn.ts CHANGED
@@ -482,14 +482,39 @@ function watchAndInject(client: any, directory: string, id: string, sessionID: s
482
482
  if (!sessionID) { slog("watchAndInject no sessionID", id); return }
483
483
  const dir = pendingDir(directory)
484
484
  const respPath = path.join(dir, `response-${id}.json`)
485
- const fire = async () => {
485
+ const claimPath = path.join(dir, `response-${id}.claim-${process.pid}.json`)
486
+ const pendingCandidates = [path.join(dir, `quiz-${id}.json`), path.join(dir, `quiz_batch-${id}.json`)]
487
+ const closeWatcher = () => { const w = activeWatchers.get(id); if (w) { try { w.close() } catch {}; activeWatchers.delete(id) } }
488
+ const fire = async (attempt = 0): Promise<void> => {
489
+ // Atomic single-consumer claim: exactly one process proceeds (fixes double-inject across processes)
490
+ try { fs.renameSync(respPath, claimPath) } catch { closeWatcher(); return } // already claimed/consumed → stand down
486
491
  let data: any
487
- try { data = JSON.parse(fs.readFileSync(respPath, "utf8")) } catch { return }
488
- try { fs.unlinkSync(respPath) } catch {}
489
- const w = activeWatchers.get(id); if (w) { try { w.close() } catch {}; activeWatchers.delete(id) }
490
- slog("watchAndInject fire", id, JSON.stringify(data).slice(0,400))
491
- const effectiveSessionID = (data as any)?.sessionID || sessionID
492
- const text = data?.cancelled ? `[cancelled] user dismissed the popup for ${id}` : buildText(data.result)
492
+ try {
493
+ data = JSON.parse(fs.readFileSync(claimPath, "utf8"))
494
+ } catch (e) {
495
+ if (attempt < 5) {
496
+ await new Promise(r => setTimeout(r, 120))
497
+ try { fs.renameSync(claimPath, respPath) } catch {}
498
+ await new Promise(r => setTimeout(r, 60))
499
+ return fire(attempt + 1)
500
+ }
501
+ slog("watchAndInject UNREADABLE response, parked", id, String(e).slice(0,160))
502
+ try { fs.renameSync(claimPath, path.join(dir, `response-${id}.poisoned-${Date.now()}.json`)) } catch {}
503
+ closeWatcher()
504
+ return
505
+ }
506
+ let text: string
507
+ let effectiveSessionID: string
508
+ try {
509
+ slog("watchAndInject fire", id, JSON.stringify(data).slice(0,400))
510
+ effectiveSessionID = (data as any)?.sessionID || sessionID
511
+ text = data?.cancelled ? `[cancelled] user dismissed the popup for ${id}` : buildText(data.result)
512
+ } catch (e) {
513
+ slog("watchAndInject buildText ERROR, parked", id, String(e).slice(0,200))
514
+ try { fs.renameSync(claimPath, path.join(dir, `response-${id}.poisoned-${Date.now()}.json`)) } catch {}
515
+ closeWatcher()
516
+ return
517
+ }
493
518
  // opencode-loop sdk.js:24 — SDK returns {data,error}, it does NOT throw. Must inspect .error.
494
519
  const sdkCall = async (method: any, ...argsList: any[]) => {
495
520
  let firstErr: any
@@ -512,23 +537,39 @@ function watchAndInject(client: any, directory: string, id: string, sessionID: s
512
537
  ]
513
538
  slog("watchAndInject injecting", id, effectiveSessionID, text.slice(0,300))
514
539
  let ok = false
540
+ let firstErr: any
515
541
  // loopd host-adapter.ts:100 — promptAsync wakes the session (fire-and-forget turn)
516
542
  if (client?.session?.promptAsync) {
517
- try { await sdkCall(client.session.promptAsync.bind(client.session), ...shapes); ok = true } catch {}
543
+ try { await sdkCall(client.session.promptAsync.bind(client.session), ...shapes); ok = true } catch (e) { firstErr = e }
518
544
  }
519
545
  if (!ok && client?.session?.prompt) {
520
- try { await sdkCall(client.session.prompt.bind(client.session), ...shapes); ok = true } catch {}
546
+ try { await sdkCall(client.session.prompt.bind(client.session), ...shapes); ok = true } catch (e) { firstErr = firstErr || e }
547
+ }
548
+ if (!ok) {
549
+ slog("watchAndInject inject FAILED, preserved", id, effectiveSessionID, String(firstErr).slice(0,200))
550
+ try { fs.renameSync(claimPath, path.join(dir, `response-${id}.failed-${Date.now()}.json`)) } catch {}
551
+ try {
552
+ await client.app.log({ body: { service: "learn", level: "error", message: `inject FAILED for ${effectiveSessionID} (orig ${sessionID})`, extra: { id } } })
553
+ } catch {}
554
+ closeWatcher()
555
+ return
521
556
  }
557
+ // Success: server owns lifecycle — consume claim + pending (TUI no longer deletes pending)
558
+ try { fs.unlinkSync(claimPath) } catch {}
559
+ for (const p of pendingCandidates) try { fs.unlinkSync(p) } catch {}
560
+ closeWatcher()
561
+ slog("watchAndInject consumed", id, effectiveSessionID)
522
562
  try {
523
- await client.app.log({ body: { service: "learn", level: ok ? "info" : "error", message: ok ? `injected into ${effectiveSessionID}` : `inject FAILED for ${effectiveSessionID} (orig ${sessionID})`, extra: { id } } })
563
+ await client.app.log({ body: { service: "learn", level: "info", message: `injected into ${effectiveSessionID}`, extra: { id } } })
524
564
  } catch {}
525
565
  }
526
- if (fs.existsSync(respPath)) { slog("watchAndInject fast-path", id); void fire(); return }
527
566
  try {
528
- const w = fs.watch(dir, (_e, filename) => { if (filename === `response-${id}.json` && fs.existsSync(respPath)) void fire() })
567
+ const w = fs.watch(dir, (_e, filename) => { if (filename === `response-${id}.json`) void fire() })
529
568
  w.on("error", () => {})
530
569
  activeWatchers.set(id, w)
531
570
  } catch {}
571
+ // Recheck after arming to close the event gap (claim makes double-fire safe)
572
+ if (fs.existsSync(respPath)) { slog("watchAndInject fast-path", id); void fire(); return }
532
573
  }
533
574
 
534
575
  // ────────────────────────────────────────────────────────────────────────────
@@ -780,6 +821,21 @@ Return ONLY JSON: {"inferred":[2],"semanticCorrect":false,"reason":"...","isIDK"
780
821
  try {
781
822
  const dir = pendingDir(directory)
782
823
  if (fs.existsSync(dir)) {
824
+ // 1) Requeue stale claims from consumers that died mid-flight (>30s old, no live response)
825
+ for (const f of fs.readdirSync(dir).filter(x => x.includes(".claim-") && x.endsWith(".json"))) {
826
+ try {
827
+ const m = f.match(/^response-(.+)\.claim-.*\.json$/)
828
+ if (!m) continue
829
+ const rid = m[1]!
830
+ const target = path.join(dir, `response-${rid}.json`)
831
+ const age = Date.now() - fs.statSync(path.join(dir, f)).mtimeMs
832
+ if (age > 30000 && !fs.existsSync(target)) {
833
+ fs.renameSync(path.join(dir, f), target)
834
+ slog("watchAndInject requeued stale claim", rid)
835
+ }
836
+ } catch {}
837
+ }
838
+ // 2) Re-arm pending quizzes (fast-path inside watchAndInject consumes any waiting response)
783
839
  for (const f of fs.readdirSync(dir).filter(x => x.endsWith(".json") && !x.startsWith("response-") && !x.startsWith(".") && !x.startsWith("classify"))) {
784
840
  try {
785
841
  const j = JSON.parse(fs.readFileSync(path.join(dir, f), "utf8"))
@@ -829,6 +885,19 @@ Return ONLY JSON: {"inferred":[2],"semanticCorrect":false,"reason":"...","isIDK"
829
885
  }
830
886
  } catch {}
831
887
  }
888
+ // 3) Park legacy orphans: response with no pending context (pre-fix leftovers) — can't rebuild inject text, park loudly instead of rotting silently
889
+ for (const f of fs.readdirSync(dir).filter(x => x.startsWith("response-") && x.endsWith(".json") && !x.includes(".claim-") && !x.includes(".poisoned") && !x.includes(".failed") && !x.includes(".orphaned"))) {
890
+ try {
891
+ const m = f.match(/^response-(.+)\.json$/)
892
+ if (!m) continue
893
+ const rid = m[1]!
894
+ const hasPending = fs.existsSync(path.join(dir, `quiz-${rid}.json`)) || fs.existsSync(path.join(dir, `quiz_batch-${rid}.json`))
895
+ if (!hasPending) {
896
+ fs.renameSync(path.join(dir, f), path.join(dir, `response-${rid}.orphaned-${Date.now()}.json`))
897
+ slog("watchAndInject orphaned response parked (no pending context)", rid)
898
+ }
899
+ } catch {}
900
+ }
832
901
  }
833
902
  } catch {}
834
903