typeclaw 0.46.1 → 0.47.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/README.md +2 -1
  2. package/package.json +2 -2
  3. package/src/agent/tool-file-safety.ts +18 -9
  4. package/src/agent/tools/webfetch/strategies/jq.ts +1 -2
  5. package/src/agent/tools/webfetch/strategies/readability.ts +39 -16
  6. package/src/agent/tools/webfetch/strategies/selector.ts +4 -2
  7. package/src/agent/tools/webfetch/strategies/snapshot.ts +3 -2
  8. package/src/agent/tools/webfetch/tool.ts +3 -3
  9. package/src/bundled-plugins/backup/index.ts +21 -4
  10. package/src/bundled-plugins/backup/runner.ts +19 -5
  11. package/src/bundled-plugins/memory/dreaming.ts +2 -1
  12. package/src/bundled-plugins/memory/load-shards.ts +31 -3
  13. package/src/bundled-plugins/memory/memory-logger.ts +2 -1
  14. package/src/bundled-plugins/memory/memory-snapshot.ts +8 -0
  15. package/src/bundled-plugins/memory/vector/embedder.ts +28 -9
  16. package/src/bundled-plugins/memory/vector/hybrid.ts +10 -2
  17. package/src/bundled-plugins/memory/vector/store.ts +21 -9
  18. package/src/bundled-plugins/security/policies/git-exfil.ts +45 -27
  19. package/src/bundled-plugins/security/policies/outbound-secret-scan.ts +8 -3
  20. package/src/bundled-plugins/security/policies/private-surface-read.ts +6 -0
  21. package/src/channels/adapters/telegram-bot-classify.ts +29 -0
  22. package/src/channels/router.ts +98 -0
  23. package/src/channels/types.ts +7 -0
  24. package/src/cli/command-meta.ts +2 -0
  25. package/src/cli/compose-stats.ts +103 -0
  26. package/src/cli/compose.ts +13 -0
  27. package/src/cli/index.ts +1 -0
  28. package/src/cli/inspect.ts +16 -0
  29. package/src/cli/stats.ts +134 -0
  30. package/src/compose/index.ts +1 -0
  31. package/src/compose/stats.ts +51 -0
  32. package/src/config/config.ts +14 -0
  33. package/src/config/index.ts +4 -0
  34. package/src/container/controller.ts +6 -0
  35. package/src/container/index.ts +1 -0
  36. package/src/container/log-archive.ts +448 -0
  37. package/src/container/shared.ts +49 -19
  38. package/src/container/start.ts +78 -63
  39. package/src/container/stats.ts +86 -0
  40. package/src/container/stop.ts +63 -36
  41. package/src/init/checkpoint.ts +4 -4
  42. package/src/init/dockerfile.ts +87 -88
  43. package/src/init/gitignore.ts +5 -6
  44. package/src/init/restart-deps-preflight.ts +2 -2
  45. package/src/init/run-bun-install.ts +16 -2
  46. package/src/init/validate-api-key.ts +1 -0
  47. package/src/inspect/item-list.ts +12 -6
  48. package/src/permissions/permissions.ts +93 -2
  49. package/src/role-claim/code.ts +9 -5
  50. package/src/run/index.ts +50 -36
  51. package/src/run/resource-report.ts +226 -0
  52. package/src/sandbox/canonical-secrets.ts +7 -0
  53. package/src/sandbox/index.ts +1 -0
  54. package/src/sandbox/symlinks.ts +1 -1
  55. package/src/secrets/export-claude-credentials-file.ts +13 -22
  56. package/src/secrets/export-codex-auth-file.ts +12 -28
  57. package/typeclaw.schema.json +14 -0
@@ -32,10 +32,10 @@ import { linkWindowsDevTypeclaw, resolveBunLinkedPackage, type RunBunLink } from
32
32
  import { isWindows } from '@/shared'
33
33
  import { hostLocaleIsCjk } from '@/shared/host-locale'
34
34
 
35
+ import { archiveContainerLogs, type DockerLogArchiver } from './log-archive'
35
36
  import { CONTAINER_PORT, TUI_TOKEN_LABEL, findFreePort, isPortAllocatedError, resolveTuiToken } from './port'
36
37
  import {
37
38
  buildxAvailable,
38
- classifyRmStderr,
39
39
  cleanupRunCorpse,
40
40
  containerNameFromCwd,
41
41
  defaultDockerExec,
@@ -46,9 +46,9 @@ import {
46
46
  imageTagFromCwd,
47
47
  isContainerNameConflict,
48
48
  isMissingDockerCredentialHelper,
49
+ parseContainerInspectOutput,
49
50
  sanitizeDockerConfigJson,
50
51
  sanitizeDockerStderr,
51
- waitForRemoval,
52
52
  } from './shared'
53
53
  import { buildCrashReason, createVerifyRunning, type VerifyRunningFn } from './verify-running'
54
54
 
@@ -175,6 +175,7 @@ export type StartOptions = {
175
175
  hostIdentity?: { uid: number; gid: number } | null
176
176
  // Test seam for the host-stage writable-config preflight.
177
177
  assertConfigWritable?: (cwd: string) => void
178
+ archiveLogs?: DockerLogArchiver
178
179
  }
179
180
 
180
181
  export type HostDaemonStatus =
@@ -194,8 +195,8 @@ export type StartResult =
194
195
  // True when the container was already running and start() became a no-op.
195
196
  // Callers that want to distinguish "I just launched it" from "it was up
196
197
  // already" (CLI output, compose summaries) gate on this flag. False on
197
- // every fresh launch, including the post-stale-corpse `--rm` recovery
198
- // path — that one rebuilds the container from scratch.
198
+ // every fresh launch, including post-stale-corpse archival and ID-keyed
199
+ // non-force removal — that path rebuilds the container from scratch.
199
200
  alreadyRunning: boolean
200
201
  autoUpgrade: AutoUpgradeOutcome
201
202
  // npm plugins dropped this start because their package 404s in the
@@ -228,10 +229,17 @@ export async function start({
228
229
  platform = process.platform,
229
230
  hostIdentity = currentHostIdentity(),
230
231
  assertConfigWritable = assertAgentConfigWritable,
232
+ archiveLogs = archiveContainerLogs,
231
233
  }: StartOptions): Promise<StartResult> {
232
234
  try {
233
235
  const containerName = containerNameFromCwd(cwd)
234
236
  const imageTagValue = imageTagFromCwd(cwd)
237
+ const archiveBeforeRemove = async (containerId: string) =>
238
+ await archiveLogs({
239
+ agentDir: cwd,
240
+ containerId,
241
+ retentionDays: (await loadTypeclawConfig(cwd)).logs.retentionDays,
242
+ })
235
243
 
236
244
  // Probe container state BEFORE refreshing Dockerfile/.gitignore: when the
237
245
  // container is already running, start() is a no-op and must not produce
@@ -248,7 +256,14 @@ export async function start({
248
256
  // return — no surprise for `compose start` against a partially-up tree.
249
257
  await applyBoundGcConfig(cwd)
250
258
 
251
- if (state.exists && state.running) {
259
+ if (state.kind === 'malformed') {
260
+ return {
261
+ ok: false,
262
+ reason: `docker inspect returned malformed container identity/state (${state.reason}); preserving container ${containerName} and its logs.`,
263
+ }
264
+ }
265
+
266
+ if (state.kind === 'present' && state.running) {
252
267
  return await reportAlreadyRunning(exec, cwd, containerName)
253
268
  }
254
269
 
@@ -413,49 +428,29 @@ export async function start({
413
428
  const modelsReady = ensureModels()
414
429
  modelsReady.catch(() => {})
415
430
 
416
- if (state.exists) {
417
- // Container holds the name but is not running. Without `--rm`, this is
418
- // now the normal post-stop / post-crash state: the corpse stays around
419
- // for `docker logs` so users can debug a crashed agent. Force-remove
420
- // before `docker run --name <same>` so the new launch doesn't collide
421
- // on the name. See classifyRmStderr for the benign-failure contract:
422
- // 'gone' means the name is already free; 'in-progress' means Docker is
423
- // still draining a prior removal and we must wait it out before docker
424
- // run, or we'd hit `Conflict. The container name "/<name>" is already
425
- // in use` even though our rm "succeeded".
426
- //
427
- // Even when `docker rm -f` returns exit 0 we MUST wait for the inspect
428
- // probe to confirm the name is free. On OrbStack (and occasionally
429
- // Docker Desktop) under concurrent load — the canonical case being
430
- // `typeclaw compose restart`, which fires N parallel stop→start pairs
431
- // — `rm -f` acknowledges the request before the daemon has finished
432
- // draining the removal. The container is still listed by `docker ps -a`
433
- // (with the same ID Docker reports back in the "Conflict. The container
434
- // name … is already in use by container <ID>" error) for tens to
435
- // hundreds of milliseconds, and `docker run --name <same>` issued
436
- // inside that window deterministically loses the race. waitForRemoval
437
- // returns on the first inspect probe in the happy path (one extra
438
- // `docker inspect` per start when there was a corpse), so the cost
439
- // here is bounded and small.
440
- const rm = await exec(['rm', '-f', containerName])
441
- if (rm.exitCode !== 0) {
442
- const kind = classifyRmStderr(rm.stderr)
443
- if (kind === null) {
444
- return {
445
- ok: false,
446
- reason: `Container ${containerName} exists but is not running, and could not be removed: ${sanitizeDockerStderr(rm.stderr) || 'no stderr'}`,
447
- }
431
+ if (state.kind === 'present') {
432
+ // Setup above can take long enough for the historical stopped state to
433
+ // change. Re-probe immediately before archival/removal and route through
434
+ // the same ID-keyed, non-force cleanup used by failed docker-run paths.
435
+ // A container that became running is preserved, while a successful rm is
436
+ // still followed by waitForRemoval before reusing the name.
437
+ const cleanup = await cleanupRunCorpse(exec, containerName, archiveBeforeRemove)
438
+ if (typeof cleanup === 'object') {
439
+ return {
440
+ ok: false,
441
+ reason: `Could not archive logs for the stale container: ${cleanup.archiveFailed}. Preserving the Docker container as the source of truth.`,
448
442
  }
449
- if (kind === 'in-progress' && !(await waitForRemoval(exec, containerName))) {
450
- return {
451
- ok: false,
452
- reason: `Container ${containerName} is still being removed by docker after 10s; refusing to docker run --name to avoid a name conflict.`,
453
- }
443
+ }
444
+ if (cleanup === 'running') {
445
+ return {
446
+ ok: false,
447
+ reason: `Container ${containerName} became running during start preflight; preserving it and refusing to launch a replacement.`,
454
448
  }
455
- } else if (!(await waitForRemoval(exec, containerName))) {
449
+ }
450
+ if (cleanup === 'stuck') {
456
451
  return {
457
452
  ok: false,
458
- reason: `Container ${containerName} is still being removed by docker after 10s; refusing to docker run --name to avoid a name conflict.`,
453
+ reason: `Container ${containerName} could not be safely inspected or removed; preserving it and refusing to docker run --name to avoid a conflict.`,
459
454
  }
460
455
  }
461
456
  }
@@ -515,7 +510,7 @@ export async function start({
515
510
  }
516
511
  }
517
512
 
518
- let run = await execRunWithConflictRetry(exec, plan.runArgs, cwd, containerName)
513
+ let run = await execRunWithConflictRetry(exec, plan.runArgs, cwd, containerName, archiveBeforeRemove)
519
514
 
520
515
  // TOCTOU: another process may have grabbed the port between our probe and
521
516
  // `docker run`, or the kernel-assigned port may itself have been claimed.
@@ -529,10 +524,17 @@ export async function start({
529
524
  // start but leaves the corpse holding the name. The port-TOCTOU retry
530
525
  // would then re-run `docker run --name <same>` and hit a name conflict
531
526
  // against that corpse. Clean it up before the retry so the new run sees
532
- // a free name. cleanupRunCorpse is safe (only force-removes non-running
533
- // same-name containers) and a no-op when the name is already free.
527
+ // a free name. cleanupRunCorpse is safe: it only targets a freshly-inspected
528
+ // non-running ID and uses non-force removal, so Docker rejects a running race.
534
529
  if (run.exitCode !== 0 && isPortAllocatedError(run.stderr)) {
535
- const cleanup = await cleanupRunCorpse(exec, containerName)
530
+ const cleanup = await cleanupRunCorpse(exec, containerName, archiveBeforeRemove)
531
+ if (typeof cleanup === 'object') {
532
+ await cleanupHostDaemonRegistration(containerName, hostd)
533
+ return {
534
+ ok: false,
535
+ reason: `docker run failed (${sanitizeDockerStderr(run.stderr) || 'port bind'}) and its container logs could not be archived: ${cleanup.archiveFailed}. Preserving the failed-run container.`,
536
+ }
537
+ }
536
538
  if (cleanup === 'running') {
537
539
  await cleanupHostDaemonRegistration(containerName, hostd)
538
540
  return {
@@ -569,7 +571,7 @@ export async function start({
569
571
  tuiToken,
570
572
  platform,
571
573
  })
572
- run = await execRunWithConflictRetry(exec, plan.runArgs, cwd, containerName)
574
+ run = await execRunWithConflictRetry(exec, plan.runArgs, cwd, containerName, archiveBeforeRemove)
573
575
  }
574
576
 
575
577
  if (run.exitCode !== 0) {
@@ -659,11 +661,10 @@ export async function planStart({
659
661
  const cfg = await loadTypeclawConfig(cwd)
660
662
  const mounts = cfg.mounts
661
663
 
662
- // No `--rm`: a crashed container's logs MUST survive past exit so users can
663
- // debug the failure. `typeclaw stop` removes the container explicitly, and
664
- // the start() preflight force-removes any lingering corpse before the next
665
- // launch — so the only state Docker ever sees in `docker ps -a` is either
666
- // a running container or one the user has not started again yet.
664
+ // No `--rm`: a crashed container's logs MUST survive past exit. Lifecycle
665
+ // cleanup archives them under host-stage <agent>/.typeclaw/logs/ before
666
+ // removing the container, so restart preserves diagnostics without leaving
667
+ // a name-blocking corpse in Docker.
667
668
  //
668
669
  // `--shm-size=2g` is mandatory for the bundled Chrome (agent-browser) to
669
670
  // survive heavy pages. Docker's default /dev/shm is 64MB; Chrome uses
@@ -998,15 +999,20 @@ async function imageExists(exec: DockerExec, tag: string): Promise<boolean> {
998
999
  return result.exitCode === 0
999
1000
  }
1000
1001
 
1001
- type InspectedState = { exists: false } | { exists: true; running: boolean }
1002
+ type InspectedState =
1003
+ | { kind: 'missing' }
1004
+ | { kind: 'present'; running: boolean; containerId: string }
1005
+ | { kind: 'malformed'; reason: string }
1002
1006
 
1003
1007
  async function inspectContainer(exec: DockerExec, name: string): Promise<InspectedState> {
1004
- const result = await exec(['inspect', '--format', '{{.State.Running}}', name])
1005
- if (result.exitCode !== 0) return { exists: false }
1006
- return { exists: true, running: result.stdout.trim() === 'true' }
1008
+ const result = await exec(['inspect', '--format', '{{.Id}}|{{.State.Running}}', name])
1009
+ if (result.exitCode !== 0) return { kind: 'missing' }
1010
+ const parsed = parseContainerInspectOutput(result.stdout)
1011
+ if (!parsed.ok) return { kind: 'malformed', reason: parsed.reason }
1012
+ return { kind: 'present', running: parsed.running, containerId: parsed.containerId }
1007
1013
  }
1008
1014
 
1009
- // Retries `docker run` on name-conflict responses by FIRST force-removing
1015
+ // Retries `docker run` on name-conflict responses by first removing
1010
1016
  // the non-running same-name corpse that's blocking the name. Sleep-only
1011
1017
  // retries (PR #121's earlier approach) cannot recover when the corpse is
1012
1018
  // stable — see isContainerNameConflict's comment for why corpses survive
@@ -1014,12 +1020,13 @@ async function inspectContainer(exec: DockerExec, name: string): Promise<Inspect
1014
1020
  // container record behind, and start()'s own port-TOCTOU retry triggers
1015
1021
  // this path against that corpse).
1016
1022
  //
1017
- // cleanupRunCorpse refuses to touch a running container, so a concurrent
1023
+ // cleanupRunCorpse refuses to touch a running container and uses non-force rm,
1024
+ // so a container that starts after its inspect probe is also preserved. A concurrent
1018
1025
  // legitimate start of the same name (or a foreign-but-named container the
1019
1026
  // user wants alive) is surfaced as a hard failure rather than silently
1020
1027
  // killed. 'stuck' likewise surfaces — a wedged daemon that won't drain a
1021
- // removal needs the user to act (`docker rm -f <name>` manually, or restart
1022
- // Docker) instead of looping forever.
1028
+ // removal needs the user to inspect the container or restart Docker instead of
1029
+ // bypassing archive-before-remove safety or looping forever.
1023
1030
  //
1024
1031
  // A bounded backoff (100/200/400/800/1200ms) follows each cleanup before the
1025
1032
  // next `docker run`. waitForRemoval polls `docker inspect`, which can
@@ -1038,12 +1045,20 @@ async function execRunWithConflictRetry(
1038
1045
  runArgs: string[],
1039
1046
  cwd: string,
1040
1047
  containerName: string,
1048
+ beforeRemove: (containerId: string) => Promise<{ ok: true } | { ok: false; reason: string }>,
1041
1049
  ): Promise<DockerExecResult> {
1042
1050
  let last = await exec(runArgs, { cwd })
1043
1051
  for (const backoffMs of CONFLICT_RETRY_BACKOFFS_MS) {
1044
1052
  if (last.exitCode === 0) return last
1045
1053
  if (!isContainerNameConflict(last.stderr)) return last
1046
- const outcome = await cleanupRunCorpse(exec, containerName)
1054
+ const outcome = await cleanupRunCorpse(exec, containerName, beforeRemove)
1055
+ if (typeof outcome === 'object') {
1056
+ return {
1057
+ exitCode: 1,
1058
+ stdout: '',
1059
+ stderr: `Container logs could not be archived: ${outcome.archiveFailed}. Preserving the failed-run container.`,
1060
+ }
1061
+ }
1047
1062
  if (outcome === 'running' || outcome === 'stuck') return last
1048
1063
  await new Promise((resolve) => setTimeout(resolve, backoffMs))
1049
1064
  last = await exec(runArgs, { cwd })
@@ -0,0 +1,86 @@
1
+ import { containerNameFromCwd, defaultDockerExec, imageTagFromCwd, type DockerExec } from './shared'
2
+
3
+ export type ContainerStats =
4
+ | { kind: 'missing'; containerName: string; imageTag: string }
5
+ | { kind: 'stopped'; containerName: string; imageTag: string }
6
+ | {
7
+ kind: 'running'
8
+ containerName: string
9
+ imageTag: string
10
+ startedAt: string | null
11
+ cpuPercent: string
12
+ memUsage: string
13
+ memPercent: string
14
+ pids: string
15
+ }
16
+
17
+ export type StatsOptions = {
18
+ cwd: string
19
+ exec?: DockerExec
20
+ }
21
+
22
+ // `docker stats --no-stream` only emits a row for a RUNNING container; a stopped
23
+ // or absent one yields no line at all, so it cannot by itself distinguish the two.
24
+ // Probe `docker inspect` first to classify missing vs stopped vs running (and to
25
+ // pull StartedAt for an uptime line), then read the live resource snapshot from
26
+ // `docker stats` for the running case.
27
+ export async function stats({ cwd, exec = defaultDockerExec }: StatsOptions): Promise<ContainerStats> {
28
+ const containerName = containerNameFromCwd(cwd)
29
+ const imageTag = imageTagFromCwd(cwd)
30
+
31
+ const inspect = await exec(['inspect', '--format', '{{.State.Running}}|{{.State.StartedAt}}', containerName])
32
+ if (inspect.exitCode !== 0) {
33
+ return { kind: 'missing', containerName, imageTag }
34
+ }
35
+
36
+ const [runningRaw = '', startedAtRaw = ''] = inspect.stdout.trim().split('|')
37
+ if (runningRaw.trim() !== 'true') {
38
+ return { kind: 'stopped', containerName, imageTag }
39
+ }
40
+
41
+ const snapshot = await queryStats(exec, containerName)
42
+ return {
43
+ kind: 'running',
44
+ containerName,
45
+ imageTag,
46
+ startedAt: startedAtRaw.trim() === '' ? null : startedAtRaw.trim(),
47
+ cpuPercent: snapshot?.cpuPercent ?? '-',
48
+ memUsage: snapshot?.memUsage ?? '-',
49
+ memPercent: snapshot?.memPercent ?? '-',
50
+ pids: snapshot?.pids ?? '-',
51
+ }
52
+ }
53
+
54
+ export type StatsSnapshot = {
55
+ cpuPercent: string
56
+ memUsage: string
57
+ memPercent: string
58
+ pids: string
59
+ }
60
+
61
+ // Pipe-delimited so a mem-usage field like "919.8MiB / 15.65GiB" (which contains
62
+ // spaces and slashes) survives intact — a space or comma separator would split it.
63
+ const STATS_FORMAT = '{{.CPUPerc}}|{{.MemUsage}}|{{.MemPerc}}|{{.PIDs}}'
64
+
65
+ async function queryStats(exec: DockerExec, containerName: string): Promise<StatsSnapshot | null> {
66
+ const result = await exec(['stats', '--no-stream', '--format', STATS_FORMAT, containerName])
67
+ if (result.exitCode !== 0) return null
68
+ return parseStatsLine(result.stdout)
69
+ }
70
+
71
+ export function parseStatsLine(stdout: string): StatsSnapshot | null {
72
+ const line = stdout
73
+ .split('\n')
74
+ .map((l) => l.trim())
75
+ .find((l) => l.length > 0)
76
+ if (line === undefined) return null
77
+
78
+ const [cpuPercent = '', memUsage = '', memPercent = '', pids = ''] = line.split('|').map((f) => f.trim())
79
+ if (cpuPercent === '' && memUsage === '' && memPercent === '' && pids === '') return null
80
+ return {
81
+ cpuPercent: cpuPercent || '-',
82
+ memUsage: memUsage || '-',
83
+ memPercent: memPercent || '-',
84
+ pids: pids || '-',
85
+ }
86
+ }
@@ -1,10 +1,13 @@
1
+ import { DEFAULT_LOG_RETENTION_DAYS, loadConfigSync } from '@/config'
1
2
  import { isDaemonReachable, send as sendToDaemon } from '@/hostd/client'
2
3
 
4
+ import { archiveContainerLogs, type DockerLogArchiver } from './log-archive'
3
5
  import {
4
6
  classifyRmStderr,
5
7
  containerNameFromCwd,
6
8
  defaultDockerExec,
7
9
  type DockerExec,
10
+ parseContainerInspectOutput,
8
11
  sanitizeDockerStderr,
9
12
  waitForRemoval,
10
13
  } from './shared'
@@ -18,9 +21,14 @@ export type StopResult = { ok: true; containerName: string; running: boolean } |
18
21
  export type StopOptions = {
19
22
  cwd: string
20
23
  exec?: DockerExec
24
+ archiveLogs?: DockerLogArchiver
21
25
  }
22
26
 
23
- export async function stop({ cwd, exec = defaultDockerExec }: StopOptions): Promise<StopResult> {
27
+ export async function stop({
28
+ cwd,
29
+ exec = defaultDockerExec,
30
+ archiveLogs = archiveContainerLogs,
31
+ }: StopOptions): Promise<StopResult> {
24
32
  const { containerName } = planStop(cwd)
25
33
 
26
34
  if (await isDaemonReachable()) {
@@ -28,70 +36,74 @@ export async function stop({ cwd, exec = defaultDockerExec }: StopOptions): Prom
28
36
  }
29
37
 
30
38
  try {
31
- const inspect = await exec(['inspect', '--format', '{{.State.Running}}', containerName], { cwd })
39
+ const retentionDays = resolveLogRetentionDays(cwd)
40
+ const inspect = await exec(['inspect', '--format', '{{.Id}}|{{.State.Running}}', containerName], { cwd })
32
41
  if (inspect.exitCode !== 0) {
33
42
  // `docker inspect` exits non-zero both when the container does not
34
43
  // exist AND when it exists but is in a transient state docker cannot
35
44
  // inspect (Removal In Progress, Dead, daemon hiccup). Discriminate by
36
- // stderr — same approach used for `docker rm` below — and attempt a
37
- // force-remove in the latter case so a corpse holding the name does
38
- // not collide with the next `docker run --name <same>`.
39
45
  if (inspect.stderr.toLowerCase().includes('no such container')) {
40
46
  return { ok: true, containerName, running: false }
41
47
  }
42
- const recover = await exec(['rm', '-f', containerName], { cwd })
43
- if (recover.exitCode !== 0) {
44
- const kind = classifyRmStderr(recover.stderr)
45
- if (kind === null) {
46
- return {
47
- ok: false,
48
- reason: `docker inspect failed (${sanitizeDockerStderr(inspect.stderr) || 'no stderr'}) and docker rm -f could not recover: ${sanitizeDockerStderr(recover.stderr) || 'no stderr'}`,
49
- }
50
- }
51
- if (kind === 'in-progress' && !(await waitForRemoval(exec, containerName))) {
52
- return {
53
- ok: false,
54
- reason: `Container ${containerName} is still being removed by docker after 10s.`,
55
- }
56
- }
48
+ return {
49
+ ok: false,
50
+ reason: `docker inspect failed (${sanitizeDockerStderr(inspect.stderr) || 'no stderr'}); preserving container ${containerName} because its ID and logs could not be safely identified for archival.`,
51
+ }
52
+ }
53
+ const parsed = parseContainerInspectOutput(inspect.stdout)
54
+ if (!parsed.ok) {
55
+ return {
56
+ ok: false,
57
+ reason: `docker inspect returned malformed container identity/state (${parsed.reason}); preserving container ${containerName} and its logs.`,
57
58
  }
58
- return { ok: true, containerName, running: false }
59
59
  }
60
- const running = inspect.stdout.trim() === 'true'
60
+ const { containerId, running } = parsed
61
61
 
62
62
  // Only call `docker stop` when the container is actually running. A stopped
63
63
  // corpse from a prior crash is left around by design (no `--rm`), and
64
64
  // `docker stop` on an exited container would still succeed but emit a
65
65
  // noisy warning to stderr — skip it.
66
66
  if (running) {
67
- const stopResult = await exec(['stop', containerName], { cwd })
67
+ const stopResult = await exec(['stop', containerId], { cwd })
68
68
  if (stopResult.exitCode !== 0) {
69
69
  return { ok: false, reason: `docker stop failed: ${sanitizeDockerStderr(stopResult.stderr) || 'no stderr'}` }
70
70
  }
71
71
  }
72
72
 
73
- // Containers run without `--rm`, so `docker stop` only stops them — the
74
- // record stays in `docker ps -a` until we remove it explicitly. Remove now
75
- // so a subsequent `docker run --name <same>` (e.g. from `typeclaw restart`)
76
- // does not collide on the name. Use `-f` for symmetry with the start.ts
77
- // preflight and because `docker stop` occasionally returns exit 0 before
78
- // the container is fully out of `Running` state on OrbStack under load —
79
- // bare `docker rm` would then refuse a still-running container. See
80
- // classifyRmStderr for the benign-failure contract; when 'in-progress',
81
- // wait for the drain so stop()'s ok-return actually means "name is free"
82
- // (which compose's restart and any subsequent start() depend on).
73
+ const archive = await archiveLogs({ agentDir: cwd, containerId, retentionDays })
74
+ if (!archive.ok) {
75
+ return {
76
+ ok: false,
77
+ reason: `Could not archive logs for container ${containerId}: ${archive.reason}. Preserving the Docker container as the source of truth.`,
78
+ }
79
+ }
80
+
81
+ // Containers run without `--rm`, so `docker stop` only stops them. Remove
82
+ // the inspected ID without force after archival. If that same ID resumed,
83
+ // Docker refuses the removal and we preserve it rather than killing a live
84
+ // container whose post-archive output is no longer represented by the
85
+ // snapshot. See classifyRmStderr for the benign-failure contract; when
86
+ // 'in-progress', wait for the drain so stop()'s ok-return actually means
87
+ // "name is free" (which compose restart and subsequent start depend on).
83
88
  //
84
89
  // Same waitForRemoval call on the exit-0 path for the same reason as the
85
90
  // start.ts preflight: OrbStack and Docker Desktop under load acknowledge
86
- // `rm -f` before the daemon has finished draining the removal, so an
91
+ // `rm` before the daemon has finished draining the removal, so an
87
92
  // immediate `docker run --name <same>` (from `typeclaw compose restart`,
88
93
  // which fires stop→start sequentially per agent) races the drain and
89
94
  // fails with "Conflict. The container name … is already in use by
90
95
  // container <ID>". stop()'s contract is that the name is free on return,
91
96
  // and the only way to honor that against Docker's async removal is to
92
- // poll inspect until the container actually disappears.
93
- const rmResult = await exec(['rm', '-f', containerName], { cwd })
97
+ // poll inspect until the container actually disappears. Removal stays keyed
98
+ // by the inspected ID so a same-name replacement cannot be deleted.
99
+ const rmResult = await exec(['rm', containerId], { cwd })
94
100
  if (rmResult.exitCode !== 0) {
101
+ if (isRunningContainerRemovalError(rmResult.stderr)) {
102
+ return {
103
+ ok: false,
104
+ reason: `Docker refused to remove running container ${containerId} after archival; preserving it because it resumed during stop.`,
105
+ }
106
+ }
95
107
  const kind = classifyRmStderr(rmResult.stderr)
96
108
  if (kind === null) {
97
109
  return { ok: false, reason: `docker rm failed: ${sanitizeDockerStderr(rmResult.stderr) || 'no stderr'}` }
@@ -118,3 +130,18 @@ export async function stop({ cwd, exec = defaultDockerExec }: StopOptions): Prom
118
130
  export function planStop(cwd: string): StopPlan {
119
131
  return { containerName: containerNameFromCwd(cwd) }
120
132
  }
133
+
134
+ function resolveLogRetentionDays(cwd: string): number {
135
+ try {
136
+ return loadConfigSync(cwd).logs.retentionDays
137
+ } catch {
138
+ // Stop must remain a recovery path when unrelated config is broken. The
139
+ // schema default is the conservative host policy until config is repaired.
140
+ return DEFAULT_LOG_RETENTION_DAYS
141
+ }
142
+ }
143
+
144
+ function isRunningContainerRemovalError(stderr: string): boolean {
145
+ const lower = stderr.toLowerCase()
146
+ return lower.includes('cannot remove a running container') || lower.includes('container is running')
147
+ }
@@ -13,10 +13,10 @@ import {
13
13
 
14
14
  // In-folder scratch for an in-progress `typeclaw init`, co-located with the
15
15
  // agent it describes. Lives under the agent's `.typeclaw/` (the same gitignored
16
- // local-scratch dir as the persistent-$HOME overlay), so it self-cleans when
17
- // the half-init folder is deleted, survives a folder rename mid-init, and is
18
- // inspectable right next to the thing being resumed. Gitignored via
19
- // `TRULY_IGNORED_PATTERNS`; never committed.
16
+ // local-scratch dir that may contain orphaned legacy runtime-HOME credentials),
17
+ // so it self-cleans when the half-init folder is deleted, survives a folder
18
+ // rename mid-init, and is inspectable right next to the thing being resumed.
19
+ // Gitignored via `TRULY_IGNORED_PATTERNS`; never committed.
20
20
  export const INIT_CHECKPOINT_PATH = join('.typeclaw', 'init-progress.json')
21
21
 
22
22
  export const WIZARD_CHECKPOINT_VERSION = 1