@kelceyp/caw-server 1.0.279 → 1.0.281
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/main.js +433 -433
- package/dist/pty-wrapper.mjs +223 -8
- package/dist/teardownReasons.mjs +100 -0
- package/package.json +2 -2
package/dist/pty-wrapper.mjs
CHANGED
|
@@ -25,6 +25,7 @@ import { tmpdir, homedir } from 'os';
|
|
|
25
25
|
import { execSync } from 'child_process';
|
|
26
26
|
import { readSentinelPayload, hasPendingWork } from './pty-deferred-teardown.mjs';
|
|
27
27
|
import { emitResult as emitResultLine } from './pty-emit-result.mjs';
|
|
28
|
+
import { TEARDOWN_REASONS } from './teardownReasons.mjs';
|
|
28
29
|
|
|
29
30
|
// --- Arg parsing ---
|
|
30
31
|
|
|
@@ -386,25 +387,124 @@ let teardownReason = null;
|
|
|
386
387
|
let startedAt = null;
|
|
387
388
|
let endedAt = null;
|
|
388
389
|
|
|
390
|
+
// Module-scope armed timestamp for the watchdog observability channel (As1012
|
|
391
|
+
// Task 7). Written by `startOrResetWatchdog` on every call (initial arm and
|
|
392
|
+
// each subsequent reset) and read by both `teardown()` and the setTimeout
|
|
393
|
+
// expiry closure so `elapsedSinceArmMs` can be computed after the timer has
|
|
394
|
+
// released. On a `reset` call the elapsed value is captured BEFORE `armedAt`
|
|
395
|
+
// is overwritten so the emitted event carries the duration of the *previous*
|
|
396
|
+
// armed interval (see item 4's ordering invariant).
|
|
397
|
+
let armedAt = null;
|
|
398
|
+
|
|
399
|
+
// Module-scope snapshot of the sentinel counts observed at the most recent
|
|
400
|
+
// deferral, for the `WATCHDOG` observability channel (As1012 Task 13). Written
|
|
401
|
+
// in the SIGUSR1 handler's defer branch BEFORE `startOrResetWatchdog()` so the
|
|
402
|
+
// counts are in place if the watchdog subsequently fires; read from
|
|
403
|
+
// `teardown()` when `reason === TEARDOWN_REASONS.WATCHDOG`. Lifted for the
|
|
404
|
+
// same reason as `armedAt`: the SIGUSR1 handler's `bgCount` / `cronCount`
|
|
405
|
+
// locals are block-scoped and out of scope inside the `setTimeout` closure
|
|
406
|
+
// that eventually calls `teardown(TEARDOWN_REASONS.WATCHDOG)`. Overwritten on
|
|
407
|
+
// every deferral, so it always holds the LAST deferral's counts — that is the
|
|
408
|
+
// documented last-seen-snapshot semantic (design.md §Data on the wire).
|
|
409
|
+
//
|
|
410
|
+
// As1062 Task 9 extends the binding with a third property, `types` — a
|
|
411
|
+
// `Map<label,count>` histogram derived from the SAME `background_tasks` array
|
|
412
|
+
// the count was computed from. Normalisation collapses whitespace in friendly
|
|
413
|
+
// labels (`"MCP task"` → `MCP_task`) so the emitted `pendingBgTypes` token
|
|
414
|
+
// stays a single greppable word per label. Missing/empty types become
|
|
415
|
+
// `unknown`. Layered onto the same object rather than a parallel binding so
|
|
416
|
+
// the LAST-deferral-wins semantic covers types too.
|
|
417
|
+
let lastDeferredCounts = null;
|
|
418
|
+
|
|
419
|
+
// As1062 Task 9 — renders `lastDeferredCounts.types` (a `Map<label,count>`)
|
|
420
|
+
// into the single-token form emitted as `pendingBgTypes` on the WATCHDOG
|
|
421
|
+
// teardown line: sorted alphabetically by label for deterministic output,
|
|
422
|
+
// comma-joined `label:count` pairs, whitespace-free by construction. Returns
|
|
423
|
+
// the literal `'none'` on an empty histogram (crons-only deferral) so the
|
|
424
|
+
// rendered line reads `pendingBgTypes=none` — distinct from the splitter's
|
|
425
|
+
// `-` sentinel that flags non-watchdog reasons. Never returns `''` — the
|
|
426
|
+
// wrapper-side empty-string guard the design calls for.
|
|
427
|
+
const renderPendingBgTypes = (types) => {
|
|
428
|
+
if (!types || types.size === 0) return 'none';
|
|
429
|
+
const rendered = [...types.entries()]
|
|
430
|
+
.sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0))
|
|
431
|
+
.map(([label, count]) => `${label}:${count}`)
|
|
432
|
+
.join(',');
|
|
433
|
+
return rendered || 'none';
|
|
434
|
+
};
|
|
435
|
+
|
|
389
436
|
// Forward declarations (assigned after ptyProcess is created)
|
|
390
437
|
let ptyProcess = null;
|
|
391
438
|
|
|
439
|
+
// --- Tagged event channel (As1012 Task 7) ---
|
|
440
|
+
// Structured lifecycle events on stderr: `[caw:pty:event] <json>\n`. Consumed
|
|
441
|
+
// downstream by JobRunner's `createStderrSplitter` (Task 6), which routes
|
|
442
|
+
// matching lines through the operational tier (`caw:ops:pty:info`). Prose
|
|
443
|
+
// stderr (every `log()` line above) is untouched — the splitter forwards
|
|
444
|
+
// non-tagged bytes byte-identically to today's `stderrChunks` collector.
|
|
445
|
+
// EPIPE is swallowed so a closed downstream pipe cannot crash the wrapper
|
|
446
|
+
// (stderr is diagnostic; the tagged channel is best-effort).
|
|
447
|
+
const EVENT_TAG = '[caw:pty:event] ';
|
|
448
|
+
const emitEvent = (type, fields = {}) => {
|
|
449
|
+
const payload = {
|
|
450
|
+
type,
|
|
451
|
+
wrapperPid: process.pid,
|
|
452
|
+
claudePid: ptyProcess?.pid,
|
|
453
|
+
agentSessionId: effectiveSessionId,
|
|
454
|
+
...fields
|
|
455
|
+
};
|
|
456
|
+
try {
|
|
457
|
+
process.stderr.write(`${EVENT_TAG}${JSON.stringify(payload)}\n`);
|
|
458
|
+
} catch (err) {
|
|
459
|
+
if (err && err.code !== 'EPIPE') throw err;
|
|
460
|
+
}
|
|
461
|
+
};
|
|
462
|
+
|
|
392
463
|
const startOrResetWatchdog = () => {
|
|
393
|
-
|
|
394
|
-
|
|
464
|
+
const wasArmed = watchdogTimer !== null;
|
|
465
|
+
if (wasArmed) clearTimeout(watchdogTimer);
|
|
466
|
+
log(`Watchdog ${wasArmed ? 'reset' : 'armed'}: ${WATCHDOG_TIMEOUT_MS / 60000}m timeout`);
|
|
467
|
+
// Ordering invariant (item 4): capture elapsedSinceArmMs BEFORE `armedAt`
|
|
468
|
+
// is overwritten so the `reset` event carries the duration of the previous
|
|
469
|
+
// armed interval. `armed` (first call) carries no elapsed value.
|
|
470
|
+
if (wasArmed) {
|
|
471
|
+
emitEvent('reset', { elapsedSinceArmMs: Date.now() - armedAt });
|
|
472
|
+
} else {
|
|
473
|
+
emitEvent('armed');
|
|
474
|
+
}
|
|
475
|
+
armedAt = Date.now();
|
|
395
476
|
watchdogTimer = setTimeout(() => {
|
|
396
477
|
log(`Watchdog expired: ${WATCHDOG_TIMEOUT_MS / 60000}m elapsed since last deferred Stop, force-killing claude`);
|
|
397
|
-
|
|
478
|
+
emitEvent('expired', { elapsedSinceArmMs: Date.now() - armedAt });
|
|
479
|
+
teardown(TEARDOWN_REASONS.WATCHDOG);
|
|
398
480
|
}, WATCHDOG_TIMEOUT_MS);
|
|
399
481
|
};
|
|
400
482
|
|
|
401
|
-
const teardown = (reason =
|
|
483
|
+
const teardown = (reason = TEARDOWN_REASONS.STOP) => {
|
|
402
484
|
if (teardownInitiated) return;
|
|
403
485
|
teardownInitiated = true;
|
|
404
486
|
endedAt = Date.now();
|
|
405
487
|
teardownReason = reason;
|
|
406
488
|
log(`Teardown (reason=${reason}): killing claude`);
|
|
407
489
|
log(`Duration: ${startedAt !== null ? (endedAt - startedAt) : 'unknown'} ms (startedAt=${startedAt}, endedAt=${endedAt})`);
|
|
490
|
+
// As1012 Task 13 — `pendingBgCount` / `pendingCronCount` ride only on the
|
|
491
|
+
// `reason=watchdog` teardown, using the same conditional-spread idiom as
|
|
492
|
+
// `elapsedSinceArmMs`. No null-guard is needed: `startOrResetWatchdog()`
|
|
493
|
+
// has exactly one call site (the defer branch below), and that branch
|
|
494
|
+
// always writes `lastDeferredCounts` BEFORE arming the timer — so a
|
|
495
|
+
// `reason=watchdog` teardown is only reachable after at least one
|
|
496
|
+
// deferral, and at least one of the two counts is guaranteed ≥ 1.
|
|
497
|
+
emitEvent('teardown', {
|
|
498
|
+
reason,
|
|
499
|
+
...(armedAt !== null ? { elapsedSinceArmMs: Date.now() - armedAt } : {}),
|
|
500
|
+
...(reason === TEARDOWN_REASONS.WATCHDOG && lastDeferredCounts !== null
|
|
501
|
+
? {
|
|
502
|
+
pendingBgCount: lastDeferredCounts.bgCount,
|
|
503
|
+
pendingCronCount: lastDeferredCounts.cronCount,
|
|
504
|
+
pendingBgTypes: renderPendingBgTypes(lastDeferredCounts.types)
|
|
505
|
+
}
|
|
506
|
+
: {})
|
|
507
|
+
});
|
|
408
508
|
if (watchdogTimer) { clearTimeout(watchdogTimer); watchdogTimer = null; }
|
|
409
509
|
stopPolling();
|
|
410
510
|
if (ptyProcess) ptyProcess.kill('SIGINT');
|
|
@@ -419,12 +519,12 @@ process.on('SIGUSR1', () => {
|
|
|
419
519
|
const payload = readSentinelPayload(sentinelPath);
|
|
420
520
|
if (!payload) {
|
|
421
521
|
log(`Warning: failed to read sentinel, proceeding with teardown`);
|
|
422
|
-
teardown();
|
|
522
|
+
teardown(TEARDOWN_REASONS.SENTINEL_UNREADABLE);
|
|
423
523
|
return;
|
|
424
524
|
}
|
|
425
525
|
if (payload.error) {
|
|
426
526
|
log(`StopFailure received: error=${payload.error}`);
|
|
427
|
-
teardown();
|
|
527
|
+
teardown(TEARDOWN_REASONS.STOP_FAILURE);
|
|
428
528
|
return;
|
|
429
529
|
}
|
|
430
530
|
const bgCount = Array.isArray(payload.background_tasks) ? payload.background_tasks.length : 0;
|
|
@@ -432,10 +532,30 @@ process.on('SIGUSR1', () => {
|
|
|
432
532
|
log(`Sentinel: background_tasks=${bgCount}, session_crons=${cronCount}`);
|
|
433
533
|
if (hasPendingWork(payload)) {
|
|
434
534
|
log('Deferring teardown: pending background work');
|
|
535
|
+
// As1012 Task 13 — capture BEFORE arming so the counts are already in
|
|
536
|
+
// place if the timer subsequently fires. Members named to match the
|
|
537
|
+
// locals above; the lift is a zero-translation copy.
|
|
538
|
+
//
|
|
539
|
+
// As1062 Task 9 — extend the same capture with a normalised `type`
|
|
540
|
+
// histogram of `background_tasks` entries so the WATCHDOG line's
|
|
541
|
+
// `pendingBgTypes=` token can carry a per-label breakdown. Normalisation
|
|
542
|
+
// (`String(entry?.type ?? '').trim().replace(/\s+/g, '_') || 'unknown'`)
|
|
543
|
+
// collapses whitespace in friendly labels (`"MCP task"` → `MCP_task`,
|
|
544
|
+
// `"auto-mode scan"` → `auto-mode_scan`) so the emitted token stays
|
|
545
|
+
// greppable as one word per label, and rescues missing/empty types to
|
|
546
|
+
// `unknown` rather than dropping them silently.
|
|
547
|
+
const types = new Map();
|
|
548
|
+
if (Array.isArray(payload.background_tasks)) {
|
|
549
|
+
for (const entry of payload.background_tasks) {
|
|
550
|
+
const label = String(entry?.type ?? '').trim().replace(/\s+/g, '_') || 'unknown';
|
|
551
|
+
types.set(label, (types.get(label) ?? 0) + 1);
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
lastDeferredCounts = { bgCount, cronCount, types };
|
|
435
555
|
startOrResetWatchdog();
|
|
436
556
|
return;
|
|
437
557
|
}
|
|
438
|
-
teardown();
|
|
558
|
+
teardown(TEARDOWN_REASONS.STOP);
|
|
439
559
|
});
|
|
440
560
|
|
|
441
561
|
writeFileSync(wrapperPidPath, String(process.pid));
|
|
@@ -471,7 +591,7 @@ ptyProcess = pty.spawn(claudePath, claudeArgs, {
|
|
|
471
591
|
cols: 120,
|
|
472
592
|
rows: 40,
|
|
473
593
|
cwd: process.cwd(),
|
|
474
|
-
env: { ...process.env, CLAUBBIT: '1' }
|
|
594
|
+
env: { ...process.env, CLAUBBIT: '1', CLAUDE_CODE_MCP_AUTO_BACKGROUND_MS: '0' }
|
|
475
595
|
});
|
|
476
596
|
|
|
477
597
|
log(`PID: ${ptyProcess.pid}`);
|
|
@@ -483,6 +603,61 @@ writeFileSync(claudePidPath, String(ptyProcess.pid));
|
|
|
483
603
|
|
|
484
604
|
let ttyBuffer = '';
|
|
485
605
|
let permissionConfirmed = false;
|
|
606
|
+
|
|
607
|
+
// As1063 Task 3 item 5: streaming prompt-too-long detection (mechanism (d) fix).
|
|
608
|
+
//
|
|
609
|
+
// Named mechanism from Task 1 evidence ([Aj20482 trace](Ad84181)): Claude Code
|
|
610
|
+
// CLI treats "Prompt is too long" from the Anthropic API as an assistant-message
|
|
611
|
+
// response — it writes the text to the transcript, prints it to the tty, and
|
|
612
|
+
// awaits the next user input rather than exiting. No Stop hook fires (this is
|
|
613
|
+
// not a normal completion). The wrapper's onExit-side detection at :822 depends
|
|
614
|
+
// on the child exiting, so it never runs. This streaming detection catches the
|
|
615
|
+
// phrase during onData and forces the pty child to exit via SIGTERM, which then
|
|
616
|
+
// drives the existing onExit path (emitResult / prompt-too-long fallback /
|
|
617
|
+
// process exit) unchanged.
|
|
618
|
+
//
|
|
619
|
+
// Debounce (500 ms of tty silence after the phrase is seen) reduces the
|
|
620
|
+
// false-positive risk of a legitimate Claude response that mentions the
|
|
621
|
+
// phrase mid-stream — a real response keeps writing (streaming JSON events,
|
|
622
|
+
// further text) and pushes the timer out; only an idle tty — the observed
|
|
623
|
+
// prompt-too-long signature — lets the timer fire. `seenPromptTooLong` is
|
|
624
|
+
// persistent because `ttyBuffer` is trimmed to the last 5000 chars on
|
|
625
|
+
// overflow, and we do not want to lose the signal to a later burst of output.
|
|
626
|
+
// Budget rationale: the observed prod trace (Aj20482) had no post-phrase tty
|
|
627
|
+
// output for 5+ minutes; 500 ms is comfortably above any streaming inter-chunk
|
|
628
|
+
// gap for a real turn and well below any human-perceptible terminal-transition
|
|
629
|
+
// latency erosion (AC5).
|
|
630
|
+
//
|
|
631
|
+
// `CAW_PTY_PROMPT_TOO_LONG_DEBOUNCE_MS` overrides the default (test-only
|
|
632
|
+
// configuration knob per Task 3 item 17 — fault-injection for the pre-fix /
|
|
633
|
+
// post-fix pairing regression test; production leaves the default in place).
|
|
634
|
+
const PROMPT_TOO_LONG_DEBOUNCE_MS = (() => {
|
|
635
|
+
const raw = process.env.CAW_PTY_PROMPT_TOO_LONG_DEBOUNCE_MS;
|
|
636
|
+
if (!raw) return 500;
|
|
637
|
+
const parsed = parseInt(raw, 10);
|
|
638
|
+
return Number.isFinite(parsed) && parsed >= 0 ? parsed : 500;
|
|
639
|
+
})();
|
|
640
|
+
let seenPromptTooLong = false;
|
|
641
|
+
let streamingPromptTooLongEmitted = false;
|
|
642
|
+
let promptTooLongTimer = null;
|
|
643
|
+
const schedulePromptTooLongEmit = () => {
|
|
644
|
+
if (promptTooLongTimer) clearTimeout(promptTooLongTimer);
|
|
645
|
+
promptTooLongTimer = setTimeout(() => {
|
|
646
|
+
promptTooLongTimer = null;
|
|
647
|
+
if (resultEmitted || failureEmitted) return;
|
|
648
|
+
log('Prompt-too-long: detected in streaming path — emitting failure and killing pty');
|
|
649
|
+
process.stdout.write(JSON.stringify({
|
|
650
|
+
type: 'error',
|
|
651
|
+
error: 'prompt_too_long',
|
|
652
|
+
message: 'Prompt is too long'
|
|
653
|
+
}) + '\n');
|
|
654
|
+
failureEmitted = true;
|
|
655
|
+
streamingPromptTooLongEmitted = true;
|
|
656
|
+
// Kill the pty so onExit fires and the wrapper shuts down cleanly.
|
|
657
|
+
try { ptyProcess.kill('SIGTERM'); } catch { /* ignore */ }
|
|
658
|
+
}, PROMPT_TOO_LONG_DEBOUNCE_MS);
|
|
659
|
+
};
|
|
660
|
+
|
|
486
661
|
ptyProcess.onData((data) => {
|
|
487
662
|
ttyBuffer += data;
|
|
488
663
|
if (!permissionConfirmed && ttyBuffer.includes('Yes') && ttyBuffer.includes('No')) {
|
|
@@ -491,6 +666,16 @@ ptyProcess.onData((data) => {
|
|
|
491
666
|
setTimeout(() => ptyProcess.write('\r'), 200); // Enter
|
|
492
667
|
permissionConfirmed = true;
|
|
493
668
|
}
|
|
669
|
+
// As1063 Task 3: streaming prompt-too-long detection with debounce.
|
|
670
|
+
// Latch `seenPromptTooLong` on first observation, then reset the debounce
|
|
671
|
+
// on every subsequent onData chunk — the timer only fires after tty has
|
|
672
|
+
// been idle for PROMPT_TOO_LONG_DEBOUNCE_MS.
|
|
673
|
+
if (!seenPromptTooLong && ttyBuffer.includes('Prompt is too long')) {
|
|
674
|
+
seenPromptTooLong = true;
|
|
675
|
+
schedulePromptTooLongEmit();
|
|
676
|
+
} else if (seenPromptTooLong && !resultEmitted && !failureEmitted) {
|
|
677
|
+
schedulePromptTooLongEmit();
|
|
678
|
+
}
|
|
494
679
|
// Keep buffer bounded
|
|
495
680
|
if (ttyBuffer.length > 10000) ttyBuffer = ttyBuffer.slice(-5000);
|
|
496
681
|
});
|
|
@@ -704,6 +889,11 @@ ptyProcess.onExit(({ exitCode }) => {
|
|
|
704
889
|
|
|
705
890
|
// Clear watchdog and stop polling (sentinelPath still exists on disk at this point)
|
|
706
891
|
if (watchdogTimer) { clearTimeout(watchdogTimer); watchdogTimer = null; }
|
|
892
|
+
// As1063 Task 3: cancel any pending streaming-prompt-too-long debounce
|
|
893
|
+
// timer — the child has exited, so either the streaming detection already
|
|
894
|
+
// fired (failureEmitted is true and its guard would no-op) or a normal
|
|
895
|
+
// exit path is running (do not want a late stale emission).
|
|
896
|
+
if (promptTooLongTimer) { clearTimeout(promptTooLongTimer); promptTooLongTimer = null; }
|
|
707
897
|
stopPolling();
|
|
708
898
|
|
|
709
899
|
// Hoisted Stop-hook sentinel read at the onExit → pre-emitResult seam.
|
|
@@ -740,6 +930,10 @@ ptyProcess.onExit(({ exitCode }) => {
|
|
|
740
930
|
// teardown() never ran on this path (Stop hook did not fire), so `endedAt` is
|
|
741
931
|
// unset and `durationMs` is deliberately omitted from the emission — the
|
|
742
932
|
// service appends the pre-existing `'0'` duration sentinel (Decision D3).
|
|
933
|
+
// As1063 Task 1 item 9: track whether this branch was the one that set
|
|
934
|
+
// failureEmitted so the onExit-branch diagnostic below can distinguish
|
|
935
|
+
// `matched-prompt-too-long` from `emitted-failure` (both set the flag).
|
|
936
|
+
let matchedPromptTooLong = false;
|
|
743
937
|
if (!resultEmitted && !failureEmitted && ttyBuffer.includes('Prompt is too long')) {
|
|
744
938
|
log('Prompt-too-long: omitting durationMs (teardown() never ran, endedAt unset)');
|
|
745
939
|
process.stdout.write(JSON.stringify({
|
|
@@ -748,11 +942,32 @@ ptyProcess.onExit(({ exitCode }) => {
|
|
|
748
942
|
message: 'Prompt is too long'
|
|
749
943
|
}) + '\n');
|
|
750
944
|
failureEmitted = true;
|
|
945
|
+
matchedPromptTooLong = true;
|
|
751
946
|
}
|
|
752
947
|
|
|
753
948
|
// Clean up temp directory
|
|
754
949
|
try { rmSync(tempDir, { recursive: true, force: true }); } catch {}
|
|
755
950
|
|
|
951
|
+
// As1063 Task 1 item 9: emit which onExit branch was taken along with
|
|
952
|
+
// the wrapper exit reason (teardownReason) and a bounded ttyBuffer tail.
|
|
953
|
+
// Bounded per lifecycle event by the `exited` guard at the top of onExit
|
|
954
|
+
// (no unbounded per-turn accumulation). Written to stderr via log() so
|
|
955
|
+
// JobRunner's stderr splitter captures it into the outputTail without
|
|
956
|
+
// affecting the wrapper's stdout emission contract.
|
|
957
|
+
const branchTaken = resultEmitted
|
|
958
|
+
? 'emitted-result'
|
|
959
|
+
: streamingPromptTooLongEmitted
|
|
960
|
+
? 'streaming-prompt-too-long'
|
|
961
|
+
: matchedPromptTooLong
|
|
962
|
+
? 'matched-prompt-too-long'
|
|
963
|
+
: failureEmitted
|
|
964
|
+
? 'emitted-failure'
|
|
965
|
+
: 'no-emission';
|
|
966
|
+
// Cap the tty tail to 256 chars and escape newlines so the line stays on
|
|
967
|
+
// one log entry regardless of what claude last wrote.
|
|
968
|
+
const ttyTail = ttyBuffer.slice(-256).replace(/\n/g, '\\n').replace(/\r/g, '\\r');
|
|
969
|
+
log(`onExit-branch: ${branchTaken} exitCode=${exitCode} teardownReason=${teardownReason ?? 'unset'} ttyTail="${ttyTail}"`);
|
|
970
|
+
|
|
756
971
|
log(`Claude exited (code: ${exitCode})`);
|
|
757
972
|
|
|
758
973
|
if (failureEmitted) {
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* teardownReasons.mjs — closed enum for the pty-wrapper's `teardown()` reason,
|
|
3
|
+
* shared between the observability path (As1012) and the classification path
|
|
4
|
+
* (As1033).
|
|
5
|
+
*
|
|
6
|
+
* Authored under As1012 as part of the S2 workshop's Q4 outcome — imported by
|
|
7
|
+
* `pty-wrapper.mjs` (emit site) and by `JobRunner.js`'s watchdog gate + the
|
|
8
|
+
* stream-handler metadata plumbing on the As1033 side.
|
|
9
|
+
*
|
|
10
|
+
* Non-forced-path contract (joint As1012 × As1033)
|
|
11
|
+
* ------------------------------------------------
|
|
12
|
+
*
|
|
13
|
+
* 1. `teardown()` runs on every graceful exit path. Four call sites; four
|
|
14
|
+
* enum values: `WATCHDOG` (expiry), `SENTINEL_UNREADABLE`, `STOP_FAILURE`,
|
|
15
|
+
* `STOP` (normal completion via the Stop hook). Normal completion is NOT a
|
|
16
|
+
* no-teardown case — it is `teardown('stop')`. **`STOP` is a real value.**
|
|
17
|
+
*
|
|
18
|
+
* 2. `emitResult` always writes `metadata.teardownReason` when it runs, with
|
|
19
|
+
* a value from this enum. The field is NOT optional on the graceful path —
|
|
20
|
+
* consumers read it directly without an `undefined` check.
|
|
21
|
+
*
|
|
22
|
+
* 3. **`metadata.teardownReason` is omitted (not `null`) whenever the pty
|
|
23
|
+
* child exits without `teardown()` firing.** Absence is the signal — the
|
|
24
|
+
* enum does not carry a *no-teardown* value. Four non-teardown exit
|
|
25
|
+
* paths, listed exhaustively so a future debugger does not misread the
|
|
26
|
+
* gap:
|
|
27
|
+
*
|
|
28
|
+
* a. **Child self-exit** — `claude` returns of its own accord before
|
|
29
|
+
* the Stop hook fires (rare; e.g. an unhandled internal error).
|
|
30
|
+
* `onExit` runs with a non-zero code; `emitResult` runs; the field
|
|
31
|
+
* is omitted because `teardown()` never called `emitResult` with a
|
|
32
|
+
* reason. Classifier reads a distinct exit class from `exitCode`.
|
|
33
|
+
* b. **External signal to the wrapper** (SIGTERM/SIGINT delivered
|
|
34
|
+
* externally, not from the wrapper's own deadline path). Wrapper
|
|
35
|
+
* may or may not manage to emit anything depending on the signal
|
|
36
|
+
* and its handler set at the moment.
|
|
37
|
+
* c. **Prompt-too-long emission** — the wrapper's stdout emits its
|
|
38
|
+
* result branch directly without routing through `teardown()`
|
|
39
|
+
* (`pty-wrapper.mjs:733` and its neighbours; see
|
|
40
|
+
* Easy-to-Miss #5 in As1012's design). Field omitted.
|
|
41
|
+
* d. **As1006's F2 SIGKILL** — the wrapper-self-terminate path with a
|
|
42
|
+
* process-group SIGKILL of the PTY child under the wrapper's own
|
|
43
|
+
* deadline. SIGKILL is unmaskable; the wrapper is dead before it
|
|
44
|
+
* can emit; the entire `type:"result"` JSONL line is absent.
|
|
45
|
+
*
|
|
46
|
+
* **`As1006's F2 SIGKILL path is an OUT-OF-ENUM EXIT PATH`, as are the
|
|
47
|
+
* other three above.** Do not read this enum as enumerating every wrapper
|
|
48
|
+
* exit. An F2-killed job leaves NO wrapper-side breadcrumb via this
|
|
49
|
+
* enum — that gap is by design, not by omission. As1033's dissent from
|
|
50
|
+
* workshop round 3 is honoured by this note.
|
|
51
|
+
*
|
|
52
|
+
* The classifier's contract for any of the four non-teardown cases:
|
|
53
|
+
* `turnSignals.teardownReason === undefined` is a **distinct exit
|
|
54
|
+
* class** — spawn failure / SIGKILL / crash / prompt-too-long / external
|
|
55
|
+
* signal — not a teardown. Classification gate ordering (As1033):
|
|
56
|
+
* `WATCHDOG` gate first (positive match on `reason === WATCHDOG`); other
|
|
57
|
+
* reasons fall through unchanged; missing reason routes to the
|
|
58
|
+
* spawn-failure / no-result branch.
|
|
59
|
+
*
|
|
60
|
+
* 4. Lifecycle events (`armed`, `reset`, `expired`, `teardown`) share the
|
|
61
|
+
* enum only via the `teardown` event's `reason` field. `armed` / `reset`
|
|
62
|
+
* / `expired` observability events carry `type`, not `reason` — no enum
|
|
63
|
+
* value on those.
|
|
64
|
+
*
|
|
65
|
+
* 5. **The enum is closed at story-close.** Adding a value requires a
|
|
66
|
+
* coordinated change to both this module AND the classification gate in
|
|
67
|
+
* `JobRunner.js`. This is a maintenance rule, not a note — treat the set
|
|
68
|
+
* below as fixed.
|
|
69
|
+
*
|
|
70
|
+
* Consumers
|
|
71
|
+
* ---------
|
|
72
|
+
*
|
|
73
|
+
* - `pty-wrapper.mjs` — emit sites: `teardown(reason)` calls at the watchdog
|
|
74
|
+
* expiry closure (`WATCHDOG`), sentinel-read failure (`SENTINEL_UNREADABLE`),
|
|
75
|
+
* StopFailure hook (`STOP_FAILURE`), clean no-pending-work path (`STOP`).
|
|
76
|
+
* - `pty-emit-result.mjs` — writes `metadata.teardownReason` on the result
|
|
77
|
+
* JSONL line (As1033).
|
|
78
|
+
* - `claude-session.js` — `getMetadata()` propagates the value into
|
|
79
|
+
* `turnSignals.teardownReason` (As1033).
|
|
80
|
+
* - `JobRunner.js` — watchdog classification gate reads
|
|
81
|
+
* `turnSignals.teardownReason` and compares against `TEARDOWN_REASONS.WATCHDOG`
|
|
82
|
+
* (As1033).
|
|
83
|
+
* - `Log.js` observability — the `WATCHDOG event=teardown reason=<value>`
|
|
84
|
+
* line format (As1012) references the enum values verbatim.
|
|
85
|
+
*
|
|
86
|
+
* Packaging
|
|
87
|
+
* ---------
|
|
88
|
+
*
|
|
89
|
+
* Copied verbatim into `dist/` by `server/package.json`'s `build:all` script,
|
|
90
|
+
* alongside `pty-wrapper.mjs`, `pty-emit-result.mjs`, and
|
|
91
|
+
* `pty-deferred-teardown.mjs`. Not bundled — the wrapper is executed as a
|
|
92
|
+
* standalone node process and imports this module by relative path.
|
|
93
|
+
*/
|
|
94
|
+
|
|
95
|
+
export const TEARDOWN_REASONS = Object.freeze({
|
|
96
|
+
WATCHDOG: 'watchdog',
|
|
97
|
+
STOP: 'stop',
|
|
98
|
+
SENTINEL_UNREADABLE: 'sentinel-unreadable',
|
|
99
|
+
STOP_FAILURE: 'stop-failure',
|
|
100
|
+
});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kelceyp/caw-server",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.281",
|
|
4
4
|
"description": "CAW server - REST API, MCP server and core features",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/main.js",
|
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
"build": "bash scripts/bun-build.sh",
|
|
20
20
|
"build:client": "cd ../client && bun run build",
|
|
21
21
|
"build:cli": "cd ../cli && bun run build && cp dist/cli.js ../server/dist/",
|
|
22
|
-
"build:all": "bun run clean && bun run generate:applyPojo && bun run build:client && bun run build && cp src/core/services/embedding-worker.js dist/embedding-worker.js && cp src/core/agents/pty-wrapper.mjs dist/pty-wrapper.mjs && cp src/core/agents/pty-deferred-teardown.mjs dist/pty-deferred-teardown.mjs && cp src/core/agents/pty-emit-result.mjs dist/pty-emit-result.mjs && bun run build:cli",
|
|
22
|
+
"build:all": "bun run clean && bun run generate:applyPojo && bun run build:client && bun run build && cp src/core/services/embedding-worker.js dist/embedding-worker.js && cp src/core/agents/pty-wrapper.mjs dist/pty-wrapper.mjs && cp src/core/agents/pty-deferred-teardown.mjs dist/pty-deferred-teardown.mjs && cp src/core/agents/pty-emit-result.mjs dist/pty-emit-result.mjs && cp src/core/agents/teardownReasons.mjs dist/teardownReasons.mjs && bun run build:cli",
|
|
23
23
|
"dev": "STATIC_PATH=../client/src bun --define __BUILTIN_POSTHOG_KEY__=null run src/main.js",
|
|
24
24
|
"start": "node dist/main.js",
|
|
25
25
|
"test": "bun test --define __BUILTIN_POSTHOG_KEY__=null test/unit test/integration test/component test/cli test/investigation && (cd ../client && bun test)",
|