harnessed 5.0.11 → 5.0.13

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 (84) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/README-en.md +1 -0
  3. package/README-zh.md +1 -0
  4. package/README.md +1 -0
  5. package/bin/harnessed-check-docs.mjs +15 -0
  6. package/bin/harnessed-update-reminder-worker.mjs +2598 -134
  7. package/bin/harnessed-update-reminder.mjs +636 -61
  8. package/dist/cli.mjs +1597 -546
  9. package/dist/cli.mjs.map +1 -1
  10. package/dist/index.mjs +1 -1
  11. package/dist/index.mjs.map +1 -1
  12. package/messages/en.json +15 -1
  13. package/messages/zh-Hans.json +15 -1
  14. package/package.json +1 -1
  15. package/workflows/auto/SKILL.md +10 -18
  16. package/workflows/auto/SKILL.zh-Hans.md +8 -18
  17. package/workflows/discuss/auto/SKILL.md +4 -7
  18. package/workflows/discuss/auto/SKILL.zh-Hans.md +2 -7
  19. package/workflows/discuss/phase/SKILL.md +4 -7
  20. package/workflows/discuss/phase/SKILL.zh-Hans.md +2 -7
  21. package/workflows/discuss/strategic/SKILL.md +4 -8
  22. package/workflows/discuss/strategic/SKILL.zh-Hans.md +2 -8
  23. package/workflows/discuss/subtask/SKILL.md +4 -7
  24. package/workflows/discuss/subtask/SKILL.zh-Hans.md +2 -7
  25. package/workflows/harnessed-update/SKILL.md +9 -8
  26. package/workflows/harnessed-update/SKILL.zh-Hans.md +7 -8
  27. package/workflows/host-primitives.yaml +8 -8
  28. package/workflows/host-primitives.zh-Hans.yaml +8 -8
  29. package/workflows/plan/ai-integration/SKILL.md +7 -7
  30. package/workflows/plan/ai-integration/SKILL.zh-Hans.md +7 -7
  31. package/workflows/plan/architecture/SKILL.md +7 -13
  32. package/workflows/plan/architecture/SKILL.zh-Hans.md +7 -13
  33. package/workflows/plan/auto/SKILL.md +8 -14
  34. package/workflows/plan/auto/SKILL.zh-Hans.md +8 -14
  35. package/workflows/plan/phase/SKILL.md +7 -13
  36. package/workflows/plan/phase/SKILL.zh-Hans.md +7 -13
  37. package/workflows/plan/secure/SKILL.md +7 -7
  38. package/workflows/plan/secure/SKILL.zh-Hans.md +7 -7
  39. package/workflows/plan/spec/SKILL.md +7 -7
  40. package/workflows/plan/spec/SKILL.zh-Hans.md +7 -7
  41. package/workflows/plan/ui/SKILL.md +7 -7
  42. package/workflows/plan/ui/SKILL.zh-Hans.md +7 -7
  43. package/workflows/research/SKILL.md +7 -7
  44. package/workflows/research/SKILL.zh-Hans.md +7 -7
  45. package/workflows/retro/SKILL.md +8 -15
  46. package/workflows/retro/SKILL.zh-Hans.md +7 -15
  47. package/workflows/ship/auto/SKILL.md +8 -14
  48. package/workflows/ship/auto/SKILL.zh-Hans.md +8 -14
  49. package/workflows/ship/preflight/SKILL.md +7 -9
  50. package/workflows/ship/preflight/SKILL.zh-Hans.md +7 -9
  51. package/workflows/task/auto/SKILL.md +8 -15
  52. package/workflows/task/auto/SKILL.zh-Hans.md +8 -15
  53. package/workflows/task/clarify/SKILL.md +2 -10
  54. package/workflows/task/clarify/SKILL.zh-Hans.md +2 -10
  55. package/workflows/task/code/SKILL.md +7 -15
  56. package/workflows/task/code/SKILL.zh-Hans.md +7 -15
  57. package/workflows/task/deliver/SKILL.md +7 -17
  58. package/workflows/task/deliver/SKILL.zh-Hans.md +7 -17
  59. package/workflows/task/test/SKILL.md +7 -14
  60. package/workflows/task/test/SKILL.zh-Hans.md +7 -14
  61. package/workflows/verify/auto/SKILL.md +9 -14
  62. package/workflows/verify/auto/SKILL.zh-Hans.md +9 -14
  63. package/workflows/verify/code-review/SKILL.md +8 -13
  64. package/workflows/verify/code-review/SKILL.zh-Hans.md +8 -13
  65. package/workflows/verify/design/SKILL.md +8 -12
  66. package/workflows/verify/design/SKILL.zh-Hans.md +7 -12
  67. package/workflows/verify/eval-review/SKILL.md +8 -12
  68. package/workflows/verify/eval-review/SKILL.zh-Hans.md +7 -12
  69. package/workflows/verify/multispec/SKILL.md +8 -15
  70. package/workflows/verify/multispec/SKILL.zh-Hans.md +7 -15
  71. package/workflows/verify/paranoid/SKILL.md +7 -14
  72. package/workflows/verify/paranoid/SKILL.zh-Hans.md +7 -14
  73. package/workflows/verify/progress/SKILL.md +8 -13
  74. package/workflows/verify/progress/SKILL.zh-Hans.md +8 -13
  75. package/workflows/verify/qa/SKILL.md +7 -13
  76. package/workflows/verify/qa/SKILL.zh-Hans.md +7 -13
  77. package/workflows/verify/second-opinion/SKILL.md +8 -12
  78. package/workflows/verify/second-opinion/SKILL.zh-Hans.md +7 -12
  79. package/workflows/verify/security/SKILL.md +8 -12
  80. package/workflows/verify/security/SKILL.zh-Hans.md +7 -12
  81. package/workflows/verify/simplify/SKILL.md +8 -12
  82. package/workflows/verify/simplify/SKILL.zh-Hans.md +7 -12
  83. package/workflows/verify/validate-phase/SKILL.md +8 -12
  84. package/workflows/verify/validate-phase/SKILL.zh-Hans.md +7 -12
@@ -65,7 +65,7 @@ var init_package = __esm({
65
65
  'package.json'() {
66
66
  package_default = {
67
67
  name: 'harnessed',
68
- version: '5.0.11',
68
+ version: '5.0.13',
69
69
  description: 'AI coding harness package manager + composition orchestrator',
70
70
  type: 'module',
71
71
  license: 'Apache-2.0',
@@ -178,6 +178,571 @@ var init_package = __esm({
178
178
  },
179
179
  })
180
180
 
181
+ // src/cli/lib/autoUpdateStatus.ts
182
+ import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
183
+ import { dirname, join } from 'node:path'
184
+ function autoUpdateStatusPath(stateRoot) {
185
+ return join(stateRoot, AUTO_UPDATE_STATUS_FILE)
186
+ }
187
+ function isFiniteNumber(value) {
188
+ return typeof value === 'number' && Number.isFinite(value)
189
+ }
190
+ function isPlainObject(value) {
191
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
192
+ }
193
+ function isValidDateMs(value) {
194
+ return isFiniteNumber(value) && !Number.isNaN(new Date(value).getTime())
195
+ }
196
+ function parseProgress(value) {
197
+ if (!isPlainObject(value)) return null
198
+ const { received, total, updatedAt } = value
199
+ if (!isFiniteNumber(received) || received < 0) return null
200
+ if (!isFiniteNumber(total) || total < 0) return null
201
+ if (!isValidDateMs(updatedAt)) return null
202
+ return { received, total, updatedAt }
203
+ }
204
+ function parseResult(value) {
205
+ if (!isPlainObject(value)) return null
206
+ const { version, status, reason, message, at } = value
207
+ if (typeof version !== 'string') return null
208
+ if (typeof status !== 'string' || !RESULT_STATUSES.includes(status)) return null
209
+ if (reason !== void 0 && typeof reason !== 'string') return null
210
+ if (message !== void 0 && typeof message !== 'string') return null
211
+ if (!isValidDateMs(at)) return null
212
+ const result = { version, status, at }
213
+ if (typeof reason === 'string') result.reason = reason
214
+ if (typeof message === 'string') result.message = message
215
+ return result
216
+ }
217
+ function parseNotice(value) {
218
+ if (!isPlainObject(value)) return null
219
+ const { from, to, changelog, restart, at } = value
220
+ if (typeof from !== 'string' || typeof to !== 'string') return null
221
+ if (typeof changelog !== 'string' || typeof restart !== 'string') return null
222
+ if (!isValidDateMs(at)) return null
223
+ const consumedAt =
224
+ typeof value.consumedAt === 'number' &&
225
+ Number.isFinite(value.consumedAt) &&
226
+ value.consumedAt >= 0
227
+ ? value.consumedAt
228
+ : 0
229
+ return { from, to, changelog, restart, at, consumedAt }
230
+ }
231
+ function parseStatus(value) {
232
+ if (!isPlainObject(value)) return null
233
+ if (value.schemaVersion !== 1) return null
234
+ const consent = value.consent
235
+ if (!isPlainObject(consent)) return null
236
+ if (typeof consent.autoUpdate !== 'boolean' || typeof consent.enabled !== 'boolean') return null
237
+ if (typeof value.channel !== 'string' || !CHANNELS.includes(value.channel)) return null
238
+ if (typeof value.installed !== 'string') return null
239
+ if (value.latest !== null && typeof value.latest !== 'string') return null
240
+ if (typeof value.state !== 'string' || !AUTO_UPDATE_STATES.includes(value.state)) return null
241
+ const progress = parseProgress(value.progress)
242
+ if (!progress) return null
243
+ const lastResult = value.lastResult === null ? null : parseResult(value.lastResult)
244
+ if (value.lastResult !== null && !lastResult) return null
245
+ if (!Array.isArray(value.history)) return null
246
+ const history = []
247
+ for (const entry of value.history) {
248
+ const parsed = parseResult(entry)
249
+ if (!parsed) return null
250
+ history.push(parsed)
251
+ }
252
+ const notice = value.notice === null ? null : parseNotice(value.notice)
253
+ if (value.notice !== null && !notice) return null
254
+ return {
255
+ schemaVersion: 1,
256
+ consent: { autoUpdate: consent.autoUpdate, enabled: consent.enabled },
257
+ channel: value.channel,
258
+ installed: value.installed,
259
+ latest: value.latest,
260
+ state: value.state,
261
+ progress,
262
+ lastResult,
263
+ history,
264
+ notice,
265
+ }
266
+ }
267
+ function readAutoUpdateStatus(path) {
268
+ let text
269
+ try {
270
+ text = readFileSync(path, 'utf8')
271
+ } catch {
272
+ return null
273
+ }
274
+ let parsed
275
+ try {
276
+ parsed = JSON.parse(text)
277
+ } catch {
278
+ return null
279
+ }
280
+ return parseStatus(parsed)
281
+ }
282
+ function writeAutoUpdateStatus(path, status) {
283
+ const dir = dirname(path)
284
+ mkdirSync(dir, { recursive: true })
285
+ const tmp = `${path}.${process.pid}.${++tmpCounter}.tmp`
286
+ try {
287
+ writeFileSync(
288
+ tmp,
289
+ `${JSON.stringify(status, null, 2)}
290
+ `,
291
+ 'utf8',
292
+ )
293
+ renameSync(tmp, path)
294
+ } catch (error) {
295
+ try {
296
+ rmSync(tmp, { force: true })
297
+ } catch {}
298
+ throw error
299
+ }
300
+ }
301
+ function appendAutoUpdateHistory(status, entry) {
302
+ const history = [...status.history, entry]
303
+ const kept =
304
+ history.length > AUTO_UPDATE_HISTORY_LIMIT
305
+ ? history.slice(history.length - AUTO_UPDATE_HISTORY_LIMIT)
306
+ : history
307
+ return { ...status, lastResult: entry, history: kept }
308
+ }
309
+ var AUTO_UPDATE_STATUS_FILE,
310
+ AUTO_UPDATE_STATUS_PATH_ENV,
311
+ AUTO_UPDATE_RESUMABLE_MARKER,
312
+ AUTO_UPDATE_HISTORY_LIMIT,
313
+ AUTO_UPDATE_STATES,
314
+ CHANNELS,
315
+ RESULT_STATUSES,
316
+ tmpCounter
317
+ var init_autoUpdateStatus = __esm({
318
+ 'src/cli/lib/autoUpdateStatus.ts'() {
319
+ 'use strict'
320
+ AUTO_UPDATE_STATUS_FILE = 'auto-update-status.json'
321
+ AUTO_UPDATE_STATUS_PATH_ENV = 'HARNESSED_AUTO_UPDATE_STATUS_PATH'
322
+ AUTO_UPDATE_RESUMABLE_MARKER = '[resumable]'
323
+ AUTO_UPDATE_HISTORY_LIMIT = 10
324
+ AUTO_UPDATE_STATES = [
325
+ 'idle',
326
+ 'downloading',
327
+ 'verifying',
328
+ 'swapping',
329
+ 'handover',
330
+ 'updated',
331
+ 'failed',
332
+ 'skipped',
333
+ ]
334
+ CHANNELS = ['binary', 'npm', 'bun', 'node']
335
+ RESULT_STATUSES = ['updated', 'failed', 'skipped']
336
+ tmpCounter = 0
337
+ },
338
+ })
339
+
340
+ // src/cli/lib/updateReminderPreferences.ts
341
+ import { closeSync, constants, fstatSync, openSync, readSync } from 'node:fs'
342
+ function readRaw(path) {
343
+ let descriptor
344
+ try {
345
+ descriptor = openSync(path, constants.O_RDONLY | constants.O_NONBLOCK)
346
+ const info = fstatSync(descriptor)
347
+ if (!info.isFile() || info.size > MAX_PREFERENCES_BYTES) return { kind: 'unreadable' }
348
+ const buffer = Buffer.alloc(info.size)
349
+ const bytes = readSync(descriptor, buffer, 0, buffer.length, 0)
350
+ return { kind: 'parsed', value: JSON.parse(buffer.toString('utf8', 0, bytes)) }
351
+ } catch (error) {
352
+ if (error.code === 'ENOENT') return { kind: 'missing' }
353
+ return { kind: 'unreadable' }
354
+ } finally {
355
+ if (descriptor !== void 0) {
356
+ try {
357
+ closeSync(descriptor)
358
+ } catch {}
359
+ }
360
+ }
361
+ }
362
+ function readUpdateReminderPreferencesFile(path) {
363
+ const raw = readRaw(path)
364
+ if (raw.kind === 'missing') {
365
+ return {
366
+ preferences: { enabled: true, autoUpdate: false, unreadable: false },
367
+ missing: true,
368
+ document: null,
369
+ }
370
+ }
371
+ if (raw.kind === 'unreadable') {
372
+ return {
373
+ preferences: { enabled: false, autoUpdate: false, unreadable: true },
374
+ missing: false,
375
+ document: null,
376
+ }
377
+ }
378
+ const value = raw.value
379
+ const record = typeof value === 'object' && value !== null ? value : {}
380
+ return {
381
+ preferences: {
382
+ enabled: record.enabled === true,
383
+ // `autoUpdate` is INDEPENDENT of `enabled` — two separate consents.
384
+ // Only a strict `true` counts; anything else is off.
385
+ autoUpdate: record.autoUpdate === true,
386
+ unreadable: false,
387
+ },
388
+ missing: false,
389
+ document: typeof value === 'object' && value !== null ? record : null,
390
+ }
391
+ }
392
+ var MAX_PREFERENCES_BYTES
393
+ var init_updateReminderPreferences = __esm({
394
+ 'src/cli/lib/updateReminderPreferences.ts'() {
395
+ 'use strict'
396
+ MAX_PREFERENCES_BYTES = 64 * 1024
397
+ },
398
+ })
399
+
400
+ // messages/en.json
401
+ var en_default
402
+ var init_en = __esm({
403
+ 'messages/en.json'() {
404
+ en_default = {
405
+ 'setup.workflows_not_found': 'error: workflows directory not found at {{path}}',
406
+ 'setup.nothing_to_install':
407
+ 'setup: no workflow directories with SKILL.md found \u2014 nothing to install',
408
+ 'setup.dry_run.header': '[dry-run] setup would install {{count}} workflow(s) to {{path}}:',
409
+ 'setup.dry_run.run_hint': ' run without --dry-run to execute',
410
+ 'setup.copy_failed': ' error: failed to copy {{name}}: {{message}}',
411
+ 'setup.step_a_complete': 'Step A: {{count}} workflows installed to {{path}}',
412
+ 'setup.step_a_render.complete': ' generated {{count}}/{{total}} command files',
413
+ 'setup.step_a_render.warnings_header':
414
+ ' [A.5] warnings \u2014 some capability cmds could not be fully resolved:',
415
+ 'setup.command_warning': ' [A.6] {{message}}',
416
+ 'setup.step_c.created': ' [C] created {{path}} + enabled Agent Teams',
417
+ 'setup.step_c.already_enabled': ' [C] Agent Teams already enabled ({{path}})',
418
+ 'setup.step_c.enabled_backup':
419
+ ' [C] enabled Agent Teams in {{path}} (backup saved \u2192 {{backupPath}})',
420
+ 'setup.step_c.skipped': ' [C] Agent Teams enable skipped: {{message}}',
421
+ 'setup.step_d.created': ' [D] created {{path}} + wrote env.HARNESSED_USER_LANG={{lang}}',
422
+ 'setup.step_d.already_set':
423
+ ' [D] env.HARNESSED_USER_LANG={{lang}} already set in {{path}} \u2014 respecting user override',
424
+ 'setup.step_d.enabled_backup':
425
+ ' [D] wrote env.HARNESSED_USER_LANG={{lang}} in {{path}} (backup saved \u2192 {{backupPath}})',
426
+ 'setup.step_d.skipped': ' [D] User language write skipped: {{message}}',
427
+ 'setup.step_b_complete':
428
+ 'Upstream components: {{installed}} installed / {{already}} already-installed / {{skipped}} skipped / {{failed}} failed [{{seconds}}s]',
429
+ 'setup.complete':
430
+ 'setup complete \u2014 {{skills}} workflows + {{manifests}} base manifests configured',
431
+ 'setup.mcp_hint': 'Run /mcp in Claude Code to verify MCP server connections.',
432
+ 'setup.mcp_hint_codex': 'Run codex mcp list to verify MCP server connections.',
433
+ 'setup.search_key_hint.header':
434
+ '\n\u26A0 Search MCP API keys missing \u2014 the server(s) below are installed but will fail at query time until the key is configured:',
435
+ 'setup.search_key_hint.header_codex':
436
+ '\n\u26A0 Search MCP API keys not visible to this check: Codex checks only process env. Verify the tools first; if authentication fails, set the key in your shell environment.',
437
+ 'setup.search_key_hint.line':
438
+ ' {{server}}: set {{envVar}} \u2014 add it to the ~/.claude/settings.json "env" block (e.g. {"env": {"{{envVar}}": "<your-key>"}}) or export {{envVar}} in your shell',
439
+ 'setup.search_key_hint.line_codex':
440
+ ' {{server}}: set {{envVar}} in your shell environment (export {{envVar}}="<your-key>")',
441
+ 'setup.optional_offer.ecc_note':
442
+ " ecc (bonus tier): installing it unlocks finer-grained scenario orchestration (per-language review/build expert routing etc.); the trade-off is ~20k+ tokens/session of static listing overhead \u2014 inherent to ECC's own scale (281 skills / 94 commands / 67 agents), not introduced by harnessed.",
443
+ 'setup.bundled_summary':
444
+ '\nharnessed workflows bundled at <packageRoot>/workflows/ (share-only, read-only)',
445
+ 'setup.bundled_location': '',
446
+ 'setup.doctor_hint': '\nRun harnessed doctor to verify your environment.',
447
+ 'agent_teams.missing_header':
448
+ '\n\u26A0\uFE0F Agent Teams not enabled \u2014 parallelism upgrade path unavailable',
449
+ 'agent_teams.missing_fix':
450
+ ' fix: claude config set env.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS 1',
451
+ 'agent_teams.missing_explanation':
452
+ ' harnessed task parallelism uses Subagent or Agent Teams (CC 2.1.178+)',
453
+ 'agent_teams.missing_nonblocking':
454
+ ' non-blocking \u2014 auto-degrades to subagent fan-out\n',
455
+ 'install.manifest_not_found': "error: manifest '{{name}}' not found",
456
+ 'install.manifest_not_found.fix':
457
+ ' fix: ensure manifests/tools/{{name}}.yaml, manifests/skill-packs/{{name}}.yaml, or manifests/optional/{{name}}.yaml exists',
458
+ 'install.audit_hint': " fix: run 'harnessed audit' to inspect manifest issues",
459
+ 'install.success': 'installed {{name}}',
460
+ 'install.success_with_version': 'installed {{name}}@{{version}}',
461
+ 'install.already_installed':
462
+ 'already-installed {{name}} (idempotent check hit; nothing to do)',
463
+ 'install.already_installed_with_version':
464
+ 'already-installed {{name}}@{{version}} (idempotent check hit; nothing to do)',
465
+ 'install.aborted': 'aborted: {{reason}}',
466
+ 'uninstall.dry_run.preview': "[dry-run] would uninstall '{{name}}' via method '{{method}}'",
467
+ 'uninstall.dry_run.run_hint': ' run without --dry-run to execute',
468
+ 'uninstall.confirm.prompt': "Uninstall '{{name}}'? This cannot be undone.",
469
+ 'uninstall.cancelled': 'aborted: user cancelled',
470
+ 'uninstall.completed': 'uninstalled {{name}}',
471
+ 'uninstall.unified.nothing': 'nothing to do \u2014 no harnessed artifacts found',
472
+ 'uninstall.unified.header': 'harnessed uninstall will remove the following:',
473
+ 'uninstall.unified.commands':
474
+ ' Commands: {{count}} harnessed-generated slash command file(s) in ~/.claude/commands/',
475
+ 'uninstall.unified.agent_roles':
476
+ ' Agent roles: {{count}} harnessed-generated codex agent role file(s) in ~/.codex/agents/',
477
+ 'uninstall.unified.skills':
478
+ ' Skills: {{count}} workflow skill directory(ies) in ~/.claude/skills/',
479
+ 'uninstall.unified.settings':
480
+ ' Settings: harnessed env vars (CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS, HARNESSED_USER_LANG) from ~/.claude/settings.json',
481
+ 'uninstall.unified.hooks':
482
+ ' Hooks: {{count}} harnessed Stop/UserPromptSubmit hook(s) in ~/.claude/settings.json',
483
+ 'uninstall.unified.state_dir':
484
+ ' State directory: ~/.claude/harnessed/ (includes backups, audit log, state, lock)',
485
+ 'uninstall.unified.upstream_note':
486
+ '\nUpstream components (npm packages, MCP servers, CC plugins, git-cloned repos, npx skills) are NOT affected.',
487
+ 'uninstall.unified.dry_run_hint':
488
+ '\n(dry-run \u2014 re-run without --dry-run to actually remove)',
489
+ 'uninstall.unified.confirm':
490
+ "Remove harnessed's own files? Upstream components (npm packages, MCP servers, CC plugins, etc.) will NOT be affected. This cannot be undone.",
491
+ 'uninstall.unified.removing': 'removing harnessed files...',
492
+ 'uninstall.unified.removed_commands': ' removed {{count}} command file(s)',
493
+ 'uninstall.unified.removed_agent_roles': ' removed {{count}} codex agent role file(s)',
494
+ 'uninstall.unified.removed_skills': ' removed {{count}} skill directory(ies)',
495
+ 'uninstall.unified.removed_settings':
496
+ ' removed harnessed env vars from ~/.claude/settings.json',
497
+ 'uninstall.unified.removed_hooks':
498
+ ' removed {{count}} harnessed hook(s) from ~/.claude/settings.json',
499
+ 'uninstall.unified.removed_state_dir': ' removed ~/.claude/harnessed/',
500
+ 'uninstall.unified.partial_failure':
501
+ '\n{{count}} item(s) could not be removed (permission denied or already gone):',
502
+ 'uninstall.unified.complete':
503
+ "uninstall complete \u2014 harnessed's own files have been removed",
504
+ 'uninstall.unified.cli_hint_header':
505
+ '\nto remove the harnessed CLI itself (the step above did not \u2014 it only cleared setup files):',
506
+ 'uninstall.unified.cli_hint_binary':
507
+ ' binary: delete {{path}}\n then remove {{dir}} from your PATH',
508
+ 'uninstall.unified.cli_hint_npm': ' npm: npm uninstall -g harnessed',
509
+ 'uninstall.unified.cli_hint_other':
510
+ " installed both ways? remove the other too \u2014 npm: 'npm uninstall -g harnessed' / binary: delete the exe + its bin dir from PATH",
511
+ 'gc.invalid_duration': "error: invalid --older-than '{{value}}'",
512
+ 'gc.invalid_duration.fix': ' fix: use format <N>{d|h|m|w} e.g. 30d / 24h / 60m / 4w',
513
+ 'gc.no_backups': 'no backups found ({{root}} absent) \u2014 nothing to gc',
514
+ 'gc.no_old_snapshots': 'no snapshots older than {{cutoff}} (kept {{keptCount}} most-recent)',
515
+ 'gc.summary_will_delete': 'would delete {{count}} snapshot(s), ~{{sizeKb}} KB total:',
516
+ 'gc.summary_deleting': 'deleting {{count}} snapshot(s), ~{{sizeKb}} KB total:',
517
+ 'gc.dry_run_rerun_hint': '\n(dry-run \u2014 re-run without --dry-run to actually delete)',
518
+ 'gc.ledger_will_prune':
519
+ 'would prune {{count}} stale workflow slot(s) from the ledger (kept {{kept}}):',
520
+ 'gc.ledger_pruned':
521
+ 'pruned {{count}} stale workflow slot(s) from the ledger (kept {{kept}}):',
522
+ 'doctor.summary.fail': '\nsome checks failed (see fix hints above)',
523
+ 'doctor.summary.warn': '\nall checks ok (with warnings \u2014 see hints above)',
524
+ 'doctor.summary.pass': '\nall checks passed',
525
+ 'doctor.host_scope': 'host: {{host}} \u2014 {{applied}} of {{total}} checks apply\n',
526
+ 'doctor.matrix.legend':
527
+ '\nn/a = the check is not declared for that host in the registry, so it was not run',
528
+ 'check_docs.clean': 'documentation discipline: no violations',
529
+ 'check_docs.state_line_limit':
530
+ 'STATE.md is {{lines}} lines > the {{limit}}-line digest limit \u2014 archive older phase narrative to RETROSPECTIVE.md (override for one run: HARNESSED_ALLOW_LONG_STATE=1)',
531
+ 'check_docs.state_key_decisions':
532
+ "{{count}} '\u5173\u952E\u51B3\u8BAE ship \u603B\u7ED3' section(s) > {{limit}} \u2014 keep only the current one; move the rest to RETROSPECTIVE.md",
533
+ 'check_docs.state_errata':
534
+ "historical commentary '{{excerpt}}' belongs in RETROSPECTIVE.md, not in the STATE digest",
535
+ 'check_docs.roadmap_narrative':
536
+ 'closing narrative inlined in an overview doc ({{signals}}) \u2014 ROADMAP carries one line + a pointer per phase; narrative goes to SUMMARY / VERIFICATION',
537
+ 'check_docs.summary_halt':
538
+ '\ndocumentation discipline: {{halt}} blocking + {{warn}} advisory violation(s)',
539
+ 'check_docs.summary_warn':
540
+ '\ndocumentation discipline: {{warn}} advisory violation(s) (non-blocking)',
541
+ 'backup.no_backups': 'no backups found ({{root}} absent)',
542
+ 'backup.no_backups_empty': 'no backups found ({{root}} empty)',
543
+ 'backup.total_snapshots': '\n{{count}} snapshot(s) total',
544
+ 'rollback.metadata_unreadable': 'error: cannot read {{path}}: {{message}}',
545
+ 'rollback.metadata_unreadable.fix':
546
+ " fix: run 'harnessed backup list' to see available timestamps",
547
+ 'rollback.checksum_mismatch':
548
+ 'error: backup checksum mismatch for {{target}} (expected {{expected}}, got {{actual}})',
549
+ 'rollback.restored': 'restored {{count}} file(s) from {{timestamp}}',
550
+ 'status.no_installs': 'no installs recorded ({{path}} absent or empty)',
551
+ 'status.summary_installs': '\n{{count}} install(s) recorded',
552
+ 'status.lock_held': '\nlock: held (since {{since}}){{staleSuffix}}',
553
+ 'status.lock_held.stale_suffix': ' \u2014 STALE',
554
+ 'status.lock_release_hint': ' to release: wait for process to finish or delete {{path}}',
555
+ 'status.lock_free': '\nlock: free',
556
+ 'here.no_workflow': 'no active workflow for this repo ({{path}} has no entry for cwd)',
557
+ 'here.no_workflow.hint':
558
+ ' to start: run a stage (e.g. `harnessed gates discuss`) or `harnessed run <workflow>`',
559
+ 'audit_log.no_records_file': 'no audit records found ({{path}} does not exist)',
560
+ 'audit_log.no_records_empty': 'no audit records found (audit.log is empty)',
561
+ 'audit_log.jq_missing': '\u2717 jq not found in PATH \u2014 run: harnessed doctor',
562
+ 'audit_log.tail_invalid': '\u2717 --tail must be a positive integer',
563
+ 'audit_log.head_invalid': '\u2717 --head must be a positive integer',
564
+ 'execute_task.require_task': 'error: --task <text> is required',
565
+ 'execute_task.load_phases_failed':
566
+ 'error: failed to load workflows/{{workflow}}/phases.yaml \u2014 {{message}}',
567
+ 'execute_task.precommit_skipped':
568
+ '\u26A0\uFE0F before-commit pre-flight skipped ({{message}}); subagent will biome-check at commit time.',
569
+ 'research.require_query': 'error: --query <text> is required',
570
+ 'manifest_add.non_interactive_warn':
571
+ '[ee-5-gate] WARN: --non-interactive skips 5-question prompt (D-03 dry-run-only). plan-phase hard reject still applies.',
572
+ 'manifest_add.dry_run_preview':
573
+ '[manifest-add] dry-run preview for upstream: {{upstream}} \u2192 {{path}}',
574
+ 'manifest_add.empty_answer': 'error: EE-5 gate requires non-empty answer',
575
+ 'manifest_add.gate_passed_wrote': '[manifest-add] EE-5 gate passed; wrote {{path}}',
576
+ 'manifest_add.gate_passed_dry_run':
577
+ '[manifest-add] EE-5 gate passed (dry-run); would write {{path}}',
578
+ 'resume.fail': '\u2717 {{error}}',
579
+ 'resume.corrupt': '\u2717 {{error}}\n path: {{path}}',
580
+ 'auto_update.consent_on': '[harnessed] auto-update ON',
581
+ 'auto_update.consent_off': '[harnessed] auto-update OFF',
582
+ 'auto_update.preferences_replaced':
583
+ '[harnessed] the preferences file was unreadable (invalid JSON) \u2014 it has been replaced.',
584
+ 'auto_update.reminder_off_note': `[harnessed] the update reminder is OFF \u2014 the "new version available" notice will not be printed. Use 'harnessed auto-update status' to check on it.`,
585
+ 'auto_update.path.host': ' host: {{host}}',
586
+ 'auto_update.path.preferences': ' preferences: {{path}}',
587
+ 'auto_update.path.status': ' status: {{path}}',
588
+ 'auto_update.error.unsupported_host': 'unsupported host: {{host}} (expected claude or codex)',
589
+ 'auto_update.error.runtime': 'could not resolve the {{host}} update-reminder runtime',
590
+ 'auto_update.notice.updated_from': 'harnessed updated {{from}} -> {{to}}.',
591
+ 'auto_update.notice.updated_to': 'harnessed updated to {{to}}.',
592
+ 'auto_update.notice.restart': 'Restart {{host}} so the new version + hooks take effect.',
593
+ 'auto_update.notice.codex_trust':
594
+ "Codex hooks still need your trust confirmed \u2014 approve the harness hook registration in Codex (or run 'harnessed setup' there).",
595
+ }
596
+ },
597
+ })
598
+
599
+ // src/i18n/index.ts
600
+ import { readFileSync as readFileSync2 } from 'node:fs'
601
+ import { dirname as dirname2, join as join2, resolve } from 'node:path'
602
+ import { fileURLToPath } from 'node:url'
603
+ function mapToSupported(raw) {
604
+ if (!raw) return 'en'
605
+ if (/^zh([^a-z]|$)/i.test(raw)) return 'zh-Hans'
606
+ return 'en'
607
+ }
608
+ function detectLocale() {
609
+ const raw =
610
+ process.env.HARNESSED_LANG ||
611
+ process.env.LC_ALL ||
612
+ process.env.LANG ||
613
+ process.env.LANGUAGE ||
614
+ safeIntlLocale()
615
+ return mapToSupported(raw)
616
+ }
617
+ function safeIntlLocale() {
618
+ try {
619
+ return Intl.DateTimeFormat().resolvedOptions().locale
620
+ } catch {
621
+ return void 0
622
+ }
623
+ }
624
+ function messagesDir() {
625
+ const here = dirname2(fileURLToPath(import.meta.url))
626
+ const candidates = []
627
+ if (wiredMessagesDirProvider) {
628
+ try {
629
+ candidates.push(wiredMessagesDirProvider())
630
+ } catch {}
631
+ }
632
+ candidates.push(resolve(here, '..', '..', 'messages'), resolve(here, '..', 'messages'))
633
+ for (const c of candidates) {
634
+ try {
635
+ readFileSync2(join2(c, 'en.json'), 'utf8')
636
+ return c
637
+ } catch {}
638
+ }
639
+ return resolve(process.cwd(), 'messages')
640
+ }
641
+ function loadLocale(locale) {
642
+ if (cache[locale]) return cache[locale]
643
+ const path = join2(messagesDir(), `${locale}.json`)
644
+ try {
645
+ const raw = readFileSync2(path, 'utf8')
646
+ cache[locale] = JSON.parse(raw)
647
+ } catch {
648
+ cache[locale] = locale === 'en' ? en_default : {}
649
+ }
650
+ return cache[locale]
651
+ }
652
+ function getLocale() {
653
+ if (currentLocale === null) currentLocale = detectLocale()
654
+ return currentLocale
655
+ }
656
+ function t(key, params) {
657
+ const locale = getLocale()
658
+ const primary = loadLocale(locale)
659
+ let template = primary[key]
660
+ if (template === void 0 && locale !== 'en') {
661
+ template = loadLocale('en')[key]
662
+ }
663
+ if (template === void 0) template = key
664
+ if (!params) return template
665
+ return template.replace(/\{\{(\w+)\}\}/g, (_match, name) => {
666
+ const v = params[name]
667
+ return v === void 0 ? `{{${name}}}` : String(v)
668
+ })
669
+ }
670
+ var currentLocale, cache, wiredMessagesDirProvider
671
+ var init_i18n = __esm({
672
+ 'src/i18n/index.ts'() {
673
+ 'use strict'
674
+ init_en()
675
+ currentLocale = null
676
+ cache = {}
677
+ wiredMessagesDirProvider = null
678
+ },
679
+ })
680
+
681
+ // src/cli/lib/autoUpdateNotice.ts
682
+ var autoUpdateNotice_exports = {}
683
+ __export(autoUpdateNotice_exports, {
684
+ consumeAutoUpdateNotice: () => consumeAutoUpdateNotice,
685
+ formatAutoUpdateNotice: () => formatAutoUpdateNotice,
686
+ isPrintableAutoUpdateNotice: () => isPrintableAutoUpdateNotice,
687
+ readAutoUpdateNotice: () => readAutoUpdateNotice,
688
+ writeAutoUpdateNotice: () => writeAutoUpdateNotice,
689
+ })
690
+ function readAutoUpdateNotice(statusPath) {
691
+ return readAutoUpdateStatus(statusPath)?.notice ?? null
692
+ }
693
+ function isPrintableAutoUpdateNotice(notice) {
694
+ if (!notice) return false
695
+ if (notice.to.trim() === '') return false
696
+ return (notice.consumedAt ?? 0) === 0
697
+ }
698
+ function formatAutoUpdateNotice(notice) {
699
+ const host = notice.restart.trim() || 'Claude Code'
700
+ const from = notice.from.trim()
701
+ const lines = []
702
+ lines.push(
703
+ from
704
+ ? t('auto_update.notice.updated_from', { from, to: notice.to })
705
+ : t('auto_update.notice.updated_to', { to: notice.to }),
706
+ )
707
+ const changelog = notice.changelog.trim()
708
+ if (changelog) lines.push('', changelog)
709
+ lines.push('', t('auto_update.notice.restart', { host }))
710
+ if (host === 'Codex') {
711
+ lines.push(t('auto_update.notice.codex_trust'))
712
+ }
713
+ return lines.join('\n')
714
+ }
715
+ function writeAutoUpdateNotice(statusPath, notice) {
716
+ const status = readAutoUpdateStatus(statusPath)
717
+ if (!status) return false
718
+ try {
719
+ writeAutoUpdateStatus(statusPath, { ...status, notice })
720
+ return true
721
+ } catch {
722
+ return false
723
+ }
724
+ }
725
+ function consumeAutoUpdateNotice(statusPath, now) {
726
+ const status = readAutoUpdateStatus(statusPath)
727
+ const notice = status?.notice
728
+ if (!status || !notice) return false
729
+ if ((notice.consumedAt ?? 0) !== 0) return false
730
+ if (notice.to.trim() === '') return false
731
+ try {
732
+ writeAutoUpdateStatus(statusPath, { ...status, notice: { ...notice, consumedAt: now } })
733
+ return true
734
+ } catch {
735
+ return false
736
+ }
737
+ }
738
+ var init_autoUpdateNotice = __esm({
739
+ 'src/cli/lib/autoUpdateNotice.ts'() {
740
+ 'use strict'
741
+ init_i18n()
742
+ init_autoUpdateStatus()
743
+ },
744
+ })
745
+
181
746
  // src/cli/lib/updateReminderCache.ts
182
747
  import fs from 'node:fs'
183
748
  function isReminderVersion(value) {
@@ -188,12 +753,12 @@ function isReminderVersion(value) {
188
753
  )
189
754
  }
190
755
  function parseCache(text, identity, now) {
191
- const cache = JSON.parse(text)
192
- if (!cache || cache.schemaVersion !== 1 || !cache.identity) return null
756
+ const cache2 = JSON.parse(text)
757
+ if (!cache2 || cache2.schemaVersion !== 1 || !cache2.identity) return null
193
758
  const keys = ['host', 'runtime', 'channel', 'source', 'fingerprint']
194
759
  if (identity.host !== 'claude' && identity.host !== 'codex') return null
195
760
  for (const key of keys) {
196
- const value = cache.identity[key]
761
+ const value = cache2.identity[key]
197
762
  if (
198
763
  typeof value !== 'string' ||
199
764
  !value.length ||
@@ -203,9 +768,9 @@ function parseCache(text, identity, now) {
203
768
  return null
204
769
  }
205
770
  }
206
- const { installed, latest, state, checkedAt, retryAfter } = cache
771
+ const { installed: installed2, latest, state, checkedAt, retryAfter } = cache2
207
772
  if (
208
- !isReminderVersion(installed) ||
773
+ !isReminderVersion(installed2) ||
209
774
  typeof checkedAt !== 'number' ||
210
775
  !Number.isSafeInteger(checkedAt) ||
211
776
  checkedAt < 0 ||
@@ -226,7 +791,7 @@ function parseCache(text, identity, now) {
226
791
  return {
227
792
  schemaVersion: 1,
228
793
  identity: { ...identity },
229
- installed,
794
+ installed: installed2,
230
795
  latest: latest ?? null,
231
796
  state,
232
797
  checkedAt,
@@ -237,11 +802,11 @@ function readReminderCache(cachePath, identity, now = Date.now()) {
237
802
  let descriptor
238
803
  try {
239
804
  descriptor = fs.openSync(cachePath, fs.constants.O_RDONLY | fs.constants.O_NONBLOCK)
240
- const stat = fs.fstatSync(descriptor)
241
- if (!stat.isFile() || stat.size > REMINDER_MAX_BYTES) return null
805
+ const stat2 = fs.fstatSync(descriptor)
806
+ if (!stat2.isFile() || stat2.size > REMINDER_MAX_BYTES) return null
242
807
  const buffer = Buffer.alloc(REMINDER_MAX_BYTES + 1)
243
808
  const bytes = fs.readSync(descriptor, buffer, 0, buffer.length, 0)
244
- if (bytes > REMINDER_MAX_BYTES || bytes < stat.size) return null
809
+ if (bytes > REMINDER_MAX_BYTES || bytes < stat2.size) return null
245
810
  return parseCache(buffer.toString('utf8', 0, bytes), identity, now)
246
811
  } catch {
247
812
  return null
@@ -253,10 +818,10 @@ function readReminderCache(cachePath, identity, now = Date.now()) {
253
818
  }
254
819
  }
255
820
  }
256
- function shouldRefreshReminder(cache, now) {
257
- if (!cache) return true
258
- if (cache.retryAfter > now) return false
259
- return cache.state === 'unknown' || now - cache.checkedAt >= REMINDER_TTL_MS
821
+ function shouldRefreshReminder(cache2, now) {
822
+ if (!cache2) return true
823
+ if (cache2.retryAfter > now) return false
824
+ return cache2.state === 'unknown' || now - cache2.checkedAt >= REMINDER_TTL_MS
260
825
  }
261
826
  var REMINDER_TTL_MS, REMINDER_RETRY_MS, REMINDER_MAX_BYTES, REMINDER_LOCK_STALE_MS
262
827
  var init_updateReminderCache = __esm({
@@ -269,6 +834,24 @@ var init_updateReminderCache = __esm({
269
834
  },
270
835
  })
271
836
 
837
+ // src/platform/stateRoot.ts
838
+ import { homedir } from 'node:os'
839
+ import { join as join3, resolve as resolve2 } from 'node:path'
840
+ function canonicalStateRoot(hostId) {
841
+ const override = process.env.HARNESSED_ROOT_OVERRIDE?.trim()
842
+ if (override) return resolve2(override)
843
+ const nativeHome =
844
+ hostId === 'codex'
845
+ ? process.env.CODEX_HOME?.trim() || join3(homedir(), '.codex')
846
+ : process.env.CLAUDE_CONFIG_DIR?.trim() || join3(homedir(), '.claude')
847
+ return resolve2(join3(nativeHome, 'harnessed'))
848
+ }
849
+ var init_stateRoot = __esm({
850
+ 'src/platform/stateRoot.ts'() {
851
+ 'use strict'
852
+ },
853
+ })
854
+
272
855
  // node_modules/.pnpm/graceful-fs@4.2.11/node_modules/graceful-fs/polyfills.js
273
856
  var require_polyfills = __commonJS({
274
857
  'node_modules/.pnpm/graceful-fs@4.2.11/node_modules/graceful-fs/polyfills.js'(exports, module) {
@@ -729,14 +1312,14 @@ var require_graceful_fs = __commonJS({
729
1312
  return close
730
1313
  })(fs2.close)
731
1314
  fs2.closeSync = (function (fs$closeSync) {
732
- function closeSync2(fd) {
1315
+ function closeSync3(fd) {
733
1316
  fs$closeSync.apply(fs2, arguments)
734
1317
  resetQueue()
735
1318
  }
736
- Object.defineProperty(closeSync2, previousSymbol, {
1319
+ Object.defineProperty(closeSync3, previousSymbol, {
737
1320
  value: fs$closeSync,
738
1321
  })
739
- return closeSync2
1322
+ return closeSync3
740
1323
  })(fs2.closeSync)
741
1324
  if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) {
742
1325
  process.on('exit', function () {
@@ -758,10 +1341,10 @@ var require_graceful_fs = __commonJS({
758
1341
  polyfills(fs3)
759
1342
  fs3.gracefulify = patch
760
1343
  fs3.createReadStream = createReadStream
761
- fs3.createWriteStream = createWriteStream
1344
+ fs3.createWriteStream = createWriteStream2
762
1345
  var fs$readFile = fs3.readFile
763
- fs3.readFile = readFile
764
- function readFile(path, options, cb) {
1346
+ fs3.readFile = readFile2
1347
+ function readFile2(path, options, cb) {
765
1348
  if (typeof options === 'function') (cb = options), (options = null)
766
1349
  return go$readFile(path, options, cb)
767
1350
  function go$readFile(path2, options2, cb2, startTime) {
@@ -847,9 +1430,9 @@ var require_graceful_fs = __commonJS({
847
1430
  }
848
1431
  }
849
1432
  var fs$readdir = fs3.readdir
850
- fs3.readdir = readdir
1433
+ fs3.readdir = readdir2
851
1434
  var noReaddirOptionVersions = /^v[0-5]\./
852
- function readdir(path, options, cb) {
1435
+ function readdir2(path, options, cb) {
853
1436
  if (typeof options === 'function') (cb = options), (options = null)
854
1437
  var go$readdir = noReaddirOptionVersions.test(process.version)
855
1438
  ? function go$readdir2(path2, options2, cb2, startTime) {
@@ -973,7 +1556,7 @@ var require_graceful_fs = __commonJS({
973
1556
  function createReadStream(path, options) {
974
1557
  return new fs3.ReadStream(path, options)
975
1558
  }
976
- function createWriteStream(path, options) {
1559
+ function createWriteStream2(path, options) {
977
1560
  return new fs3.WriteStream(path, options)
978
1561
  }
979
1562
  var fs$open = fs3.open
@@ -1478,11 +2061,11 @@ var require_mtime_precision = __commonJS({
1478
2061
  function probe(file, fs2, callback) {
1479
2062
  const cachedPrecision = fs2[cacheSymbol]
1480
2063
  if (cachedPrecision) {
1481
- return fs2.stat(file, (err, stat) => {
2064
+ return fs2.stat(file, (err, stat2) => {
1482
2065
  if (err) {
1483
2066
  return callback(err)
1484
2067
  }
1485
- callback(null, stat.mtime, cachedPrecision)
2068
+ callback(null, stat2.mtime, cachedPrecision)
1486
2069
  })
1487
2070
  }
1488
2071
  const mtime = new Date(Math.ceil(Date.now() / 1e3) * 1e3 + 5)
@@ -1490,13 +2073,13 @@ var require_mtime_precision = __commonJS({
1490
2073
  if (err) {
1491
2074
  return callback(err)
1492
2075
  }
1493
- fs2.stat(file, (err2, stat) => {
2076
+ fs2.stat(file, (err2, stat2) => {
1494
2077
  if (err2) {
1495
2078
  return callback(err2)
1496
2079
  }
1497
- const precision = stat.mtime.getTime() % 1e3 === 0 ? 's' : 'ms'
2080
+ const precision = stat2.mtime.getTime() % 1e3 === 0 ? 's' : 'ms'
1498
2081
  Object.defineProperty(fs2, cacheSymbol, { value: precision })
1499
- callback(null, stat.mtime, precision)
2082
+ callback(null, stat2.mtime, precision)
1500
2083
  })
1501
2084
  })
1502
2085
  }
@@ -1554,14 +2137,14 @@ var require_lockfile = __commonJS({
1554
2137
  Object.assign(new Error('Lock file is already being held'), { code: 'ELOCKED', file }),
1555
2138
  )
1556
2139
  }
1557
- options.fs.stat(lockfilePath, (err2, stat) => {
2140
+ options.fs.stat(lockfilePath, (err2, stat2) => {
1558
2141
  if (err2) {
1559
2142
  if (err2.code === 'ENOENT') {
1560
2143
  return acquireLock(file, { ...options, stale: 0 }, callback)
1561
2144
  }
1562
2145
  return callback(err2)
1563
2146
  }
1564
- if (!isLockStale(stat, options)) {
2147
+ if (!isLockStale(stat2, options)) {
1565
2148
  return callback(
1566
2149
  Object.assign(new Error('Lock file is already being held'), {
1567
2150
  code: 'ELOCKED',
@@ -1578,8 +2161,8 @@ var require_lockfile = __commonJS({
1578
2161
  })
1579
2162
  })
1580
2163
  }
1581
- function isLockStale(stat, options) {
1582
- return stat.mtime.getTime() < Date.now() - options.stale
2164
+ function isLockStale(stat2, options) {
2165
+ return stat2.mtime.getTime() < Date.now() - options.stale
1583
2166
  }
1584
2167
  function removeLock(file, options, callback) {
1585
2168
  options.fs.rmdir(getLockFile(file, options), (err) => {
@@ -1597,7 +2180,7 @@ var require_lockfile = __commonJS({
1597
2180
  lock2.updateDelay = lock2.updateDelay || options.update
1598
2181
  lock2.updateTimeout = setTimeout(() => {
1599
2182
  lock2.updateTimeout = null
1600
- options.fs.stat(lock2.lockfilePath, (err, stat) => {
2183
+ options.fs.stat(lock2.lockfilePath, (err, stat2) => {
1601
2184
  const isOverThreshold = lock2.lastUpdate + options.stale < Date.now()
1602
2185
  if (err) {
1603
2186
  if (err.code === 'ENOENT' || isOverThreshold) {
@@ -1606,7 +2189,7 @@ var require_lockfile = __commonJS({
1606
2189
  lock2.updateDelay = 1e3
1607
2190
  return updateLock(file, options)
1608
2191
  }
1609
- const isMtimeOurs = lock2.mtime.getTime() === stat.mtime.getTime()
2192
+ const isMtimeOurs = lock2.mtime.getTime() === stat2.mtime.getTime()
1610
2193
  if (!isMtimeOurs) {
1611
2194
  return setLockAsCompromised(
1612
2195
  file,
@@ -1742,11 +2325,11 @@ var require_lockfile = __commonJS({
1742
2325
  if (err) {
1743
2326
  return callback(err)
1744
2327
  }
1745
- options.fs.stat(getLockFile(file2, options), (err2, stat) => {
2328
+ options.fs.stat(getLockFile(file2, options), (err2, stat2) => {
1746
2329
  if (err2) {
1747
2330
  return err2.code === 'ENOENT' ? callback(null, false) : callback(err2)
1748
2331
  }
1749
- return callback(null, !isLockStale(stat, options))
2332
+ return callback(null, !isLockStale(stat2, options))
1750
2333
  })
1751
2334
  })
1752
2335
  }
@@ -1795,12 +2378,12 @@ var require_adapter = __commonJS({
1795
2378
  }
1796
2379
  function toPromise(method) {
1797
2380
  return (...args) =>
1798
- new Promise((resolve2, reject) => {
2381
+ new Promise((resolve5, reject) => {
1799
2382
  args.push((err, result) => {
1800
2383
  if (err) {
1801
2384
  reject(err)
1802
2385
  } else {
1803
- resolve2(result)
2386
+ resolve5(result)
1804
2387
  }
1805
2388
  })
1806
2389
  method(...args)
@@ -1849,27 +2432,27 @@ var require_proper_lockfile = __commonJS({
1849
2432
  module,
1850
2433
  ) {
1851
2434
  'use strict'
1852
- var lockfile2 = require_lockfile()
2435
+ var lockfile3 = require_lockfile()
1853
2436
  var { toPromise, toSync, toSyncOptions } = require_adapter()
1854
2437
  async function lock(file, options) {
1855
- const release = await toPromise(lockfile2.lock)(file, options)
2438
+ const release = await toPromise(lockfile3.lock)(file, options)
1856
2439
  return toPromise(release)
1857
2440
  }
1858
2441
  function lockSync(file, options) {
1859
- const release = toSync(lockfile2.lock)(file, toSyncOptions(options))
2442
+ const release = toSync(lockfile3.lock)(file, toSyncOptions(options))
1860
2443
  return toSync(release)
1861
2444
  }
1862
2445
  function unlock(file, options) {
1863
- return toPromise(lockfile2.unlock)(file, options)
2446
+ return toPromise(lockfile3.unlock)(file, options)
1864
2447
  }
1865
2448
  function unlockSync(file, options) {
1866
- return toSync(lockfile2.unlock)(file, toSyncOptions(options))
2449
+ return toSync(lockfile3.unlock)(file, toSyncOptions(options))
1867
2450
  }
1868
2451
  function check(file, options) {
1869
- return toPromise(lockfile2.check)(file, options)
2452
+ return toPromise(lockfile3.check)(file, options)
1870
2453
  }
1871
2454
  function checkSync(file, options) {
1872
- return toSync(lockfile2.check)(file, toSyncOptions(options))
2455
+ return toSync(lockfile3.check)(file, toSyncOptions(options))
1873
2456
  }
1874
2457
  module.exports = lock
1875
2458
  module.exports.lock = lock
@@ -1881,6 +2464,266 @@ var require_proper_lockfile = __commonJS({
1881
2464
  },
1882
2465
  })
1883
2466
 
2467
+ // src/cli/lib/autoUpdate.ts
2468
+ import {
2469
+ mkdirSync as mkdirSync2,
2470
+ renameSync as renameSync2,
2471
+ rmSync as rmSync2,
2472
+ writeFileSync as writeFileSync2,
2473
+ } from 'node:fs'
2474
+ import { dirname as dirname3 } from 'node:path'
2475
+ function isAutoUpdateConsentGranted(consent) {
2476
+ return consent.schemaVersion === 1 && consent.autoUpdate === true
2477
+ }
2478
+ function mapSelfUpdateFailureReason(message) {
2479
+ const text = message.toLowerCase()
2480
+ if (
2481
+ text.includes('integrity') ||
2482
+ text.includes('signature') ||
2483
+ text.includes('sha256') ||
2484
+ text.includes('ed25519')
2485
+ )
2486
+ return 'integrity'
2487
+ if (text.includes('smoke') || text.includes('--version')) return 'smoke'
2488
+ if (
2489
+ text.includes('swap') ||
2490
+ text.includes('rollback') ||
2491
+ text.includes('rename') ||
2492
+ text.includes('binary aside')
2493
+ )
2494
+ return 'swap'
2495
+ if (text.includes('handover') || text.includes('owned-state')) return 'handover'
2496
+ return 'network'
2497
+ }
2498
+ function isCriticalOutcome(outcome) {
2499
+ return outcome.critical === true || outcome.message.startsWith('CRITICAL')
2500
+ }
2501
+ function disableAutoUpdateConsent(path) {
2502
+ const { document } = readUpdateReminderPreferencesFile(path)
2503
+ const next = document ? { ...document } : { schemaVersion: 1, enabled: true }
2504
+ next.autoUpdate = false
2505
+ mkdirSync2(dirname3(path), { recursive: true })
2506
+ const temporary = `${path}.${process.pid}.tmp`
2507
+ try {
2508
+ writeFileSync2(
2509
+ temporary,
2510
+ `${JSON.stringify(next, null, 2)}
2511
+ `,
2512
+ 'utf8',
2513
+ )
2514
+ renameSync2(temporary, path)
2515
+ } catch (error) {
2516
+ try {
2517
+ rmSync2(temporary, { force: true })
2518
+ } catch {}
2519
+ throw error
2520
+ }
2521
+ }
2522
+ function quotaBlocked(status, version, now) {
2523
+ if (!status) return false
2524
+ const entries = status.lastResult ? [...status.history, status.lastResult] : status.history
2525
+ return entries.some((entry) => {
2526
+ if (entry.version !== version) return false
2527
+ if (entry.status !== 'failed') return false
2528
+ if ((entry.message ?? '').startsWith(AUTO_UPDATE_RESUMABLE_MARKER)) return false
2529
+ return Math.abs(now - entry.at) < AUTO_UPDATE_FAILURE_QUOTA_MS
2530
+ })
2531
+ }
2532
+ function baseStatus(deps, preferences, channel, installed2, version) {
2533
+ const now = deps.now()
2534
+ return {
2535
+ schemaVersion: 1,
2536
+ consent: { autoUpdate: preferences.autoUpdate, enabled: preferences.enabled },
2537
+ channel,
2538
+ installed: installed2,
2539
+ latest: version,
2540
+ state: 'idle',
2541
+ progress: { received: 0, total: 0, updatedAt: now },
2542
+ lastResult: null,
2543
+ history: [],
2544
+ notice: null,
2545
+ }
2546
+ }
2547
+ function persist(deps, preferences, channel, installed2, version, patch) {
2548
+ const existing = deps.readStatus()
2549
+ const base = existing ?? baseStatus(deps, preferences, channel, installed2, version)
2550
+ let next = {
2551
+ ...base,
2552
+ consent: { autoUpdate: preferences.autoUpdate, enabled: preferences.enabled },
2553
+ channel,
2554
+ installed: installed2,
2555
+ latest: version,
2556
+ state: patch.state ?? base.state,
2557
+ }
2558
+ if (patch.result) next = appendAutoUpdateHistory(next, patch.result)
2559
+ if (patch.notice) next = { ...next, notice: patch.notice }
2560
+ deps.writeStatus(next)
2561
+ return next
2562
+ }
2563
+ async function runAutoUpdate(deps, options) {
2564
+ const version = options.targetVersion
2565
+ const preferences = deps.readPreferences()
2566
+ if (!isAutoUpdateConsentGranted(preferences)) {
2567
+ return { status: 'skipped', reason: 'consent-off', version }
2568
+ }
2569
+ const channel = deps.channel()
2570
+ const installed2 = deps.installedVersion()
2571
+ if (channel !== 'binary') {
2572
+ persist(deps, preferences, channel, installed2, version, {
2573
+ state: 'skipped',
2574
+ result: { version, status: 'skipped', reason: 'npm-channel', at: deps.now() },
2575
+ })
2576
+ return { status: 'skipped', reason: 'npm-channel', version }
2577
+ }
2578
+ if (quotaBlocked(deps.readStatus(), version, deps.now())) {
2579
+ deps.log(`auto-update: ${version} already failed once in the last 24h \u2014 skipping`)
2580
+ return { status: 'skipped', reason: 'rate-limited', version }
2581
+ }
2582
+ const execPath = deps.target()
2583
+ if (!(await deps.execDirWritable(execPath))) {
2584
+ const message = `the directory of ${execPath} is not writable \u2014 the binary cannot be replaced`
2585
+ persist(deps, preferences, channel, installed2, version, {
2586
+ state: 'failed',
2587
+ result: { version, status: 'failed', reason: 'exec-dir-readonly', message, at: deps.now() },
2588
+ })
2589
+ return { status: 'error', reason: 'exec-dir-readonly', message, version }
2590
+ }
2591
+ const stateRoot = deps.context().platform.stateRoot
2592
+ let locked
2593
+ try {
2594
+ locked = await deps.withLock({ stateRoot, target: execPath }, () =>
2595
+ runLockedRound(deps, {
2596
+ preferences,
2597
+ channel,
2598
+ installed: installed2,
2599
+ version,
2600
+ }),
2601
+ )
2602
+ } catch (error) {
2603
+ const message = error instanceof Error ? error.message : String(error)
2604
+ persist(deps, preferences, channel, installed2, version, {
2605
+ state: 'failed',
2606
+ result: {
2607
+ version,
2608
+ status: 'failed',
2609
+ reason: 'exec-dir-readonly',
2610
+ message: `could not take the update lock: ${message}`,
2611
+ at: deps.now(),
2612
+ },
2613
+ })
2614
+ return { status: 'error', reason: 'exec-dir-readonly', message, version }
2615
+ }
2616
+ if (locked.status === 'busy') {
2617
+ persist(deps, preferences, channel, installed2, version, {
2618
+ state: 'skipped',
2619
+ result: { version, status: 'skipped', reason: 'busy', at: deps.now() },
2620
+ })
2621
+ return { status: 'skipped', reason: 'busy', version }
2622
+ }
2623
+ return locked.value
2624
+ }
2625
+ async function runLockedRound(deps, input) {
2626
+ const { preferences, channel, installed: installed2, version } = input
2627
+ if (quotaBlocked(deps.readStatus(), version, deps.now())) {
2628
+ return { status: 'skipped', reason: 'rate-limited', version }
2629
+ }
2630
+ persist(deps, preferences, channel, installed2, version, { state: 'downloading' })
2631
+ let outcome
2632
+ try {
2633
+ outcome = await deps.selfUpdate()
2634
+ } catch (error) {
2635
+ const message2 = error instanceof Error ? error.message : String(error)
2636
+ persist(deps, preferences, channel, installed2, version, {
2637
+ state: 'failed',
2638
+ result: { version, status: 'failed', reason: 'network', message: message2, at: deps.now() },
2639
+ })
2640
+ return { status: 'error', reason: 'network', message: message2, version }
2641
+ }
2642
+ if (outcome.status === 'updated') {
2643
+ const from = outcome.from
2644
+ const to = outcome.to
2645
+ persist(deps, preferences, channel, installed2, version, {
2646
+ state: 'updated',
2647
+ result: { version: to, status: 'updated', at: deps.now() },
2648
+ })
2649
+ persist(deps, preferences, channel, installed2, version, {
2650
+ notice: { from, to: '', changelog: '', restart: '', at: deps.now(), consumedAt: 0 },
2651
+ })
2652
+ const handover = await deps.handover({ from, to, statusPath: deps.statusPath() })
2653
+ if (!handover.ok) {
2654
+ const message2 = handover.error ?? 'the owned-state handover failed'
2655
+ persist(deps, preferences, channel, installed2, version, {
2656
+ state: 'updated',
2657
+ result: {
2658
+ version: to,
2659
+ status: 'updated',
2660
+ reason: 'handover',
2661
+ message: message2,
2662
+ at: deps.now(),
2663
+ },
2664
+ })
2665
+ return { status: 'updated', reason: 'handover', message: message2, version: to }
2666
+ }
2667
+ persist(deps, preferences, channel, installed2, version, { state: 'updated' })
2668
+ return { status: 'updated', version: to }
2669
+ }
2670
+ if (outcome.status === 'current') {
2671
+ persist(deps, preferences, channel, installed2, version, {
2672
+ state: 'skipped',
2673
+ result: { version, status: 'skipped', at: deps.now() },
2674
+ })
2675
+ return { status: 'skipped', reason: 'current', version }
2676
+ }
2677
+ if (outcome.status === 'refused') {
2678
+ const message2 = outcome.reason
2679
+ persist(deps, preferences, channel, installed2, version, {
2680
+ state: 'skipped',
2681
+ result: {
2682
+ version,
2683
+ status: 'skipped',
2684
+ reason: 'npm-channel',
2685
+ message: message2,
2686
+ at: deps.now(),
2687
+ },
2688
+ })
2689
+ return { status: 'skipped', reason: 'npm-channel', message: message2, version }
2690
+ }
2691
+ if (outcome.status === 'checked' || outcome.status === 'dry-run') {
2692
+ persist(deps, preferences, channel, installed2, version, {
2693
+ state: 'skipped',
2694
+ result: { version, status: 'skipped', at: deps.now() },
2695
+ })
2696
+ return { status: 'skipped', reason: 'current', version }
2697
+ }
2698
+ const critical = isCriticalOutcome(outcome)
2699
+ const reason = critical ? 'swap-critical' : mapSelfUpdateFailureReason(outcome.message)
2700
+ const resumable = outcome.progressed === true
2701
+ const message = resumable ? `${AUTO_UPDATE_RESUMABLE_MARKER} ${outcome.message}` : outcome.message
2702
+ persist(deps, preferences, channel, installed2, version, {
2703
+ state: 'failed',
2704
+ result: { version, status: 'failed', reason, message, at: deps.now() },
2705
+ })
2706
+ if (critical) {
2707
+ try {
2708
+ disableAutoUpdateConsent(deps.preferencesPath())
2709
+ } catch (error) {
2710
+ deps.log(
2711
+ `auto-update: could not turn the auto-update consent off: ${error instanceof Error ? error.message : String(error)}`,
2712
+ )
2713
+ }
2714
+ }
2715
+ return { status: 'error', reason, message: outcome.message, version }
2716
+ }
2717
+ var AUTO_UPDATE_FAILURE_QUOTA_MS
2718
+ var init_autoUpdate = __esm({
2719
+ 'src/cli/lib/autoUpdate.ts'() {
2720
+ 'use strict'
2721
+ init_autoUpdateStatus()
2722
+ init_updateReminderPreferences()
2723
+ AUTO_UPDATE_FAILURE_QUOTA_MS = 24 * 60 * 60 * 1e3
2724
+ },
2725
+ })
2726
+
1884
2727
  // src/platform/packagePath.ts
1885
2728
  var init_packagePath = __esm({
1886
2729
  'src/platform/packagePath.ts'() {
@@ -1889,9 +2732,167 @@ var init_packagePath = __esm({
1889
2732
  })
1890
2733
 
1891
2734
  // src/platform/platform.ts
2735
+ import { existsSync, readFileSync as readFileSync3 } from 'node:fs'
2736
+ import { homedir as homedir2 } from 'node:os'
2737
+ import { join as join4 } from 'node:path'
2738
+ function claudeDescriptor(home = homedir2()) {
2739
+ const claudeHome = join4(home, '.claude')
2740
+ return {
2741
+ id: 'claude',
2742
+ homeDir: claudeHome,
2743
+ stateRoot: join4(claudeHome, 'harnessed'),
2744
+ settingsPath: join4(claudeHome, 'settings.json'),
2745
+ skillsDir: join4(claudeHome, 'skills'),
2746
+ commandsDir: join4(claudeHome, 'commands'),
2747
+ pluginsRegistry: join4(claudeHome, 'plugins', 'installed_plugins.json'),
2748
+ // mcpConfigPath is a SIBLING of `.claude` (`<home>/.claude.json`), based on
2749
+ // the same home base — not a child of homeDir.
2750
+ mcpConfigPath: join4(home, '.claude.json'),
2751
+ // claude writes its env keys into JSON settings.json (capability present).
2752
+ supportsEnvKeyWrite: true,
2753
+ // Claude Code exposes the active session id to Bash-invoked CLI + hooks.
2754
+ sessionIdEnv: 'CLAUDE_CODE_SESSION_ID',
2755
+ }
2756
+ }
2757
+ function codexDescriptor(home = homedir2()) {
2758
+ const codexHome = join4(home, '.codex')
2759
+ const configToml = join4(codexHome, 'config.toml')
2760
+ return {
2761
+ id: 'codex',
2762
+ homeDir: codexHome,
2763
+ stateRoot: join4(codexHome, 'harnessed'),
2764
+ settingsPath: null,
2765
+ // SHARED convention dir, NOT <homeDir>/skills.
2766
+ skillsDir: join4(home, '.agents', 'skills'),
2767
+ commandsDir: join4(codexHome, 'prompts'),
2768
+ pluginsRegistry: null,
2769
+ mcpConfigPath: configToml,
2770
+ supportsEnvKeyWrite: false,
2771
+ // Measured on codex-cli 0.154: codex shells carry it, equal to hook session_id.
2772
+ sessionIdEnv: 'CODEX_SESSION_ID',
2773
+ }
2774
+ }
2775
+ function isHostId(id) {
2776
+ return HOST_IDS.includes(id)
2777
+ }
2778
+ function descriptorFor(id, home = homedir2()) {
2779
+ return id === 'codex' ? codexDescriptor(home) : claudeDescriptor(home)
2780
+ }
2781
+ function configuredHome(envVar) {
2782
+ const value = process.env[envVar]?.trim()
2783
+ return value || void 0
2784
+ }
2785
+ function descriptorForConfiguredHome(id, home = homedir2()) {
2786
+ const descriptor = descriptorFor(id, home)
2787
+ const nativeHome = configuredHome(id === 'codex' ? 'CODEX_HOME' : 'CLAUDE_CONFIG_DIR')
2788
+ if (nativeHome === void 0) return descriptor
2789
+ if (id === 'codex') {
2790
+ return {
2791
+ ...descriptor,
2792
+ homeDir: nativeHome,
2793
+ stateRoot: join4(nativeHome, 'harnessed'),
2794
+ commandsDir: join4(nativeHome, 'prompts'),
2795
+ mcpConfigPath: join4(nativeHome, 'config.toml'),
2796
+ }
2797
+ }
2798
+ return {
2799
+ ...descriptor,
2800
+ homeDir: nativeHome,
2801
+ stateRoot: join4(nativeHome, 'harnessed'),
2802
+ settingsPath: join4(nativeHome, 'settings.json'),
2803
+ skillsDir: join4(nativeHome, 'skills'),
2804
+ commandsDir: join4(nativeHome, 'commands'),
2805
+ pluginsRegistry: join4(nativeHome, 'plugins', 'installed_plugins.json'),
2806
+ }
2807
+ }
2808
+ function detectPlatform(home = homedir2()) {
2809
+ const resolved = resolveHost(home)
2810
+ const override = process.env.HARNESSED_ROOT_OVERRIDE
2811
+ if (override !== void 0 && override !== '') return { ...resolved, stateRoot: override }
2812
+ return resolved
2813
+ }
2814
+ function resolveHost(home) {
2815
+ return resolveHostWithReason(home).descriptor
2816
+ }
2817
+ function resolveHostWithReason(home = homedir2()) {
2818
+ const claudeHome = configuredHome('CLAUDE_CONFIG_DIR')
2819
+ const codexHome = configuredHome('CODEX_HOME')
2820
+ const envPlatform = process.env.HARNESSED_PLATFORM?.trim()
2821
+ const explicitHost = envPlatform !== void 0 && isHostId(envPlatform) ? envPlatform : void 0
2822
+ if (explicitHost === void 0 && claudeHome !== void 0 && codexHome !== void 0) {
2823
+ throw new Error('both CLAUDE_CONFIG_DIR and CODEX_HOME are set; pass --platform claude|codex')
2824
+ }
2825
+ const base = descriptorForConfiguredHome('claude', home)
2826
+ const codex = descriptorForConfiguredHome('codex', home)
2827
+ const skipped = []
2828
+ if (envPlatform !== void 0 && envPlatform !== '') {
2829
+ const d = isHostId(envPlatform) ? descriptorForConfiguredHome(envPlatform, home) : void 0
2830
+ if (d) {
2831
+ return {
2832
+ descriptor: d,
2833
+ reason: { kind: 'env-platform', envVar: 'HARNESSED_PLATFORM', value: envPlatform },
2834
+ skipped,
2835
+ }
2836
+ }
2837
+ skipped.push({ kind: 'env-platform-unknown', envVar: 'HARNESSED_PLATFORM', value: envPlatform })
2838
+ }
2839
+ if (claudeHome !== void 0 || codexHome !== void 0) {
2840
+ const id = claudeHome !== void 0 ? 'claude' : 'codex'
2841
+ return {
2842
+ descriptor: id === 'claude' ? base : codex,
2843
+ reason: {
2844
+ kind: 'env-platform',
2845
+ envVar: id === 'claude' ? 'CLAUDE_CONFIG_DIR' : 'CODEX_HOME',
2846
+ value: id === 'claude' ? claudeHome : codexHome,
2847
+ },
2848
+ skipped,
2849
+ }
2850
+ }
2851
+ const inClaude = Boolean(process.env.CLAUDE_CODE_SESSION_ID?.trim())
2852
+ const inCodex = Boolean(process.env.CODEX_SESSION_ID?.trim())
2853
+ if (inClaude !== inCodex) {
2854
+ return {
2855
+ descriptor: inClaude ? base : codex,
2856
+ reason: {
2857
+ kind: 'host-session-env',
2858
+ envVar: inClaude ? 'CLAUDE_CODE_SESSION_ID' : 'CODEX_SESSION_ID',
2859
+ },
2860
+ skipped,
2861
+ }
2862
+ }
2863
+ if (inClaude && inCodex) skipped.push({ kind: 'host-session-env-ambiguous' })
2864
+ for (const pinRoot of [codex.stateRoot, base.stateRoot]) {
2865
+ const pinPath = join4(pinRoot, '.platform')
2866
+ try {
2867
+ const value = readFileSync3(pinPath, 'utf8').trim()
2868
+ const d = isHostId(value) ? descriptorForConfiguredHome(value, home) : void 0
2869
+ if (d) return { descriptor: d, reason: { kind: 'platform-pin', pinPath, value }, skipped }
2870
+ skipped.push({ kind: 'platform-pin-unknown', pinPath, value })
2871
+ } catch {}
2872
+ }
2873
+ try {
2874
+ if (existsSync(base.homeDir)) {
2875
+ return {
2876
+ descriptor: base,
2877
+ reason: { kind: 'directory-probe', probedDir: base.homeDir },
2878
+ skipped,
2879
+ }
2880
+ }
2881
+ if (existsSync(codex.homeDir)) {
2882
+ return {
2883
+ descriptor: codex,
2884
+ reason: { kind: 'directory-probe', probedDir: codex.homeDir },
2885
+ skipped,
2886
+ }
2887
+ }
2888
+ } catch {}
2889
+ return { descriptor: base, reason: { kind: 'fallback' }, skipped }
2890
+ }
2891
+ var HOST_IDS
1892
2892
  var init_platform = __esm({
1893
2893
  'src/platform/platform.ts'() {
1894
2894
  'use strict'
2895
+ HOST_IDS = ['claude', 'codex']
1895
2896
  },
1896
2897
  })
1897
2898
 
@@ -1904,8 +2905,8 @@ function isCompiledModuleUrl(url) {
1904
2905
  try {
1905
2906
  s = decodeURIComponent(url)
1906
2907
  } catch {}
1907
- const normalized = s.replace(/\\/g, '/').toLowerCase()
1908
- return BUNFS_MARKERS.some((m) => normalized.includes(m))
2908
+ const normalized2 = s.replace(/\\/g, '/').toLowerCase()
2909
+ return BUNFS_MARKERS.some((m) => normalized2.includes(m))
1909
2910
  }
1910
2911
  var BUNFS_MARKERS
1911
2912
  var init_assetsRoot = __esm({
@@ -1938,6 +2939,7 @@ var init_runtime = __esm({
1938
2939
  // src/cli/lib/version-check.ts
1939
2940
  var version_check_exports = {}
1940
2941
  __export(version_check_exports, {
2942
+ compareVersionNames: () => compareVersionNames,
1941
2943
  compareVersions: () => compareVersions,
1942
2944
  fetchLatestBunVersion: () => fetchLatestBunVersion,
1943
2945
  fetchLatestNpmVersion: () => fetchLatestNpmVersion,
@@ -1950,8 +2952,8 @@ function parse(v) {
1950
2952
  if (!m) return null
1951
2953
  return { nums: [Number(m[1]), Number(m[2]), Number(m[3])], pre: m[4] ?? null }
1952
2954
  }
1953
- function compareVersions(installed, latest) {
1954
- const a = parse(installed)
2955
+ function compareVersions(installed2, latest) {
2956
+ const a = parse(installed2)
1955
2957
  const b = parse(latest)
1956
2958
  if (!a || !b) return 'unknown'
1957
2959
  for (let i = 0; i < 3; i++) {
@@ -1965,6 +2967,24 @@ function compareVersions(installed, latest) {
1965
2967
  if (a.pre && b.pre && a.pre !== b.pre) return a.pre < b.pre ? 'behind' : 'ahead'
1966
2968
  return 'current'
1967
2969
  }
2970
+ function compareVersionNames(a, b) {
2971
+ const relation = compareVersions(a, b)
2972
+ if (relation === 'ahead') return 1
2973
+ if (relation === 'behind') return -1
2974
+ if (relation === 'current') return 0
2975
+ const segments = (v) =>
2976
+ v.split('.').map((part) => {
2977
+ const n = Number.parseInt(part, 10)
2978
+ return Number.isNaN(n) ? 0 : n
2979
+ })
2980
+ const as = segments(a)
2981
+ const bs = segments(b)
2982
+ for (let i = 0; i < Math.max(as.length, bs.length); i++) {
2983
+ const diff = (as[i] ?? 0) - (bs[i] ?? 0)
2984
+ if (diff !== 0) return diff
2985
+ }
2986
+ return 0
2987
+ }
1968
2988
  function npmExecutable() {
1969
2989
  return process.platform === 'win32' ? 'npm.cmd' : 'npm'
1970
2990
  }
@@ -2026,52 +3046,1496 @@ var init_version_check = __esm({
2026
3046
  },
2027
3047
  })
2028
3048
 
2029
- // src/cli/updateReminderWorkerMain.ts
2030
- var updateReminderWorkerMain_exports = {}
2031
- __export(updateReminderWorkerMain_exports, {
2032
- runUpdateReminderWorker: () => runUpdateReminderWorker,
3049
+ // src/platform/hostInstallContext.ts
3050
+ var hostInstallContext_exports = {}
3051
+ __export(hostInstallContext_exports, {
3052
+ captureHostInstallContext: () => captureHostInstallContext,
3053
+ createHostInstallContext: () => createHostInstallContext,
2033
3054
  })
2034
- import { randomUUID } from 'node:crypto'
2035
- import asyncFs from 'node:fs/promises'
2036
- import { dirname } from 'node:path'
2037
- async function runUpdateReminderWorker(options) {
2038
- let release
2039
- let temporary
2040
- let timer
2041
- const controller = new AbortController()
2042
- let owned = false
2043
- try {
2044
- const now = options.now ?? Date.now
2045
- if (!isReminderVersion(options.installed)) return 0
2046
- await asyncFs.mkdir(dirname(options.cachePath), { recursive: true })
2047
- release = await import_proper_lockfile.default.lock(options.cachePath, {
2048
- realpath: false,
2049
- retries: 0,
2050
- stale: REMINDER_LOCK_STALE_MS,
2051
- update: 1e4,
2052
- onCompromised: () => {
2053
- owned = false
2054
- controller.abort()
2055
- },
2056
- })
2057
- owned = true
2058
- const cache = readReminderCache(options.cachePath, options.identity, now())
2059
- if (!shouldRefreshReminder(cache, now())) return 0
2060
- let latest = null
2061
- try {
2062
- const observation = await Promise.race([
2063
- options.observe(controller.signal),
2064
- new Promise((_, reject) => {
2065
- timer = setTimeout(() => {
2066
- controller.abort()
2067
- reject(new Error('timeout'))
2068
- }, 8e3)
2069
- }),
3055
+ import { homedir as homedir3 } from 'node:os'
3056
+ function createHostInstallContext(platform, selection) {
3057
+ if (platform.id !== 'claude' && platform.id !== 'codex') {
3058
+ throw new Error(`unsupported host: ${platform.id}`)
3059
+ }
3060
+ const nativeHome = platform.id === 'codex' ? selection.nativeHome?.trim() : selection.nativeHome
3061
+ const neutralSpawnCwd = selection.neutralSpawnCwd?.trim()
3062
+ return Object.freeze({
3063
+ hostId: platform.id,
3064
+ os: selection.os,
3065
+ userHome: selection.userHome,
3066
+ platform: Object.freeze({ ...platform }),
3067
+ nativeHome: nativeHome || platform.homeDir,
3068
+ ...(neutralSpawnCwd ? { neutralSpawnCwd } : {}),
3069
+ })
3070
+ }
3071
+ function captureHostInstallContext(options = {}) {
3072
+ if (options.hostId !== void 0 && !isHostId(options.hostId)) {
3073
+ throw new Error(`unsupported host: ${options.hostId}`)
3074
+ }
3075
+ const userHome = options.userHome ?? homedir3()
3076
+ const platformEnv = process.env.HARNESSED_PLATFORM?.trim()
3077
+ const explicitHost =
3078
+ options.hostId ?? (platformEnv !== void 0 && isHostId(platformEnv) ? platformEnv : void 0)
3079
+ const hostId = explicitHost ?? detectPlatform(userHome).id
3080
+ if (!isHostId(hostId)) throw new Error(`unsupported host: ${hostId}`)
3081
+ const platform = descriptorForConfiguredHome(hostId, userHome)
3082
+ const rootKey = platform.id === 'codex' ? 'CODEX_HOME' : 'CLAUDE_CONFIG_DIR'
3083
+ const nativeHome = process.env[rootKey]?.trim() || platform.homeDir
3084
+ return createHostInstallContext(platform, {
3085
+ os: options.os ?? process.platform,
3086
+ userHome,
3087
+ nativeHome,
3088
+ neutralSpawnCwd: process.env.HARNESSED_SPAWN_CWD,
3089
+ })
3090
+ }
3091
+ var init_hostInstallContext = __esm({
3092
+ 'src/platform/hostInstallContext.ts'() {
3093
+ 'use strict'
3094
+ init_platform()
3095
+ },
3096
+ })
3097
+
3098
+ // src/installers/lib/killTree.ts
3099
+ import { spawnSync } from 'node:child_process'
3100
+ function descendantsOf(pid) {
3101
+ const r = spawnSync('pgrep', ['-P', String(pid)], { encoding: 'utf8', timeout: 2e3 })
3102
+ if (r.status !== 0 || typeof r.stdout !== 'string') return []
3103
+ const out = []
3104
+ for (const tok of r.stdout.split(/\s+/)) {
3105
+ const child = Number(tok)
3106
+ if (Number.isInteger(child) && child > 0) out.push(child, ...descendantsOf(child))
3107
+ }
3108
+ return out
3109
+ }
3110
+ function killProcessTree(child) {
3111
+ const pid = child.pid
3112
+ if (pid === void 0) {
3113
+ child.kill('SIGKILL')
3114
+ return
3115
+ }
3116
+ if (process.platform === 'win32') {
3117
+ const r = spawnSync('taskkill', ['/PID', String(pid), '/T', '/F'], {
3118
+ windowsHide: true,
3119
+ stdio: 'ignore',
3120
+ timeout: 5e3,
3121
+ })
3122
+ if (r.status === 0) return
3123
+ child.kill('SIGKILL')
3124
+ return
3125
+ }
3126
+ const tree = descendantsOf(pid)
3127
+ child.kill('SIGKILL')
3128
+ for (const d of tree) {
3129
+ try {
3130
+ process.kill(d, 'SIGKILL')
3131
+ } catch {}
3132
+ }
3133
+ }
3134
+ var init_killTree = __esm({
3135
+ 'src/installers/lib/killTree.ts'() {
3136
+ 'use strict'
3137
+ },
3138
+ })
3139
+
3140
+ // src/installers/lib/winSpawn.ts
3141
+ import { win32 } from 'node:path'
3142
+ var extname, join5
3143
+ var init_winSpawn = __esm({
3144
+ 'src/installers/lib/winSpawn.ts'() {
3145
+ 'use strict'
3146
+ ;({ extname, join: join5 } = win32)
3147
+ },
3148
+ })
3149
+
3150
+ // src/installers/lib/runClaudeArgs.ts
3151
+ function withHostInstallEnv(env, hostContext) {
3152
+ if (!hostContext) return env
3153
+ const pins = {
3154
+ HOME: hostContext.userHome,
3155
+ USERPROFILE: hostContext.userHome,
3156
+ HARNESSED_PLATFORM: hostContext.hostId,
3157
+ HARNESSED_ROOT_OVERRIDE: hostContext.platform.stateRoot,
3158
+ HARNESSED_SPAWN_CWD: hostContext.neutralSpawnCwd ?? '',
3159
+ [hostContext.hostId === 'codex' ? 'CODEX_HOME' : 'CLAUDE_CONFIG_DIR']: hostContext.nativeHome,
3160
+ }
3161
+ const result = { ...env }
3162
+ if (hostContext.os === 'win32') {
3163
+ for (const key of Object.keys(result)) {
3164
+ if (Object.hasOwn(pins, key.toUpperCase())) delete result[key]
3165
+ }
3166
+ }
3167
+ return { ...result, ...pins }
3168
+ }
3169
+ var init_runClaudeArgs = __esm({
3170
+ 'src/installers/lib/runClaudeArgs.ts'() {
3171
+ 'use strict'
3172
+ init_killTree()
3173
+ init_winSpawn()
3174
+ },
3175
+ })
3176
+
3177
+ // src/cli/lib/proxyDispatcher.ts
3178
+ function hasProxyEnv() {
3179
+ return PROXY_VARS.some((k) => (process.env[k] ?? '').trim() !== '')
3180
+ }
3181
+ async function ensureProxyDispatcher(deps = {}) {
3182
+ if (installed) return 'already'
3183
+ if (!hasProxyEnv()) return 'no-proxy-env'
3184
+ const isCompiled = deps.isCompiled ?? (() => isCompiledRuntime())
3185
+ if (isCompiled()) return 'native-runtime'
3186
+ const load =
3187
+ deps.loadUndici ??
3188
+ (async () => {
3189
+ const spec = 'undici'
3190
+ return await import(spec)
3191
+ })
3192
+ try {
3193
+ const mod = await load()
3194
+ const Agent = mod.EnvHttpProxyAgent
3195
+ const setGlobalDispatcher = mod.setGlobalDispatcher
3196
+ if (typeof Agent !== 'function' || typeof setGlobalDispatcher !== 'function') {
3197
+ return 'unavailable'
3198
+ }
3199
+ setGlobalDispatcher(new Agent())
3200
+ installed = true
3201
+ return 'installed'
3202
+ } catch {
3203
+ return 'unavailable'
3204
+ }
3205
+ }
3206
+ var PROXY_VARS, installed
3207
+ var init_proxyDispatcher = __esm({
3208
+ 'src/cli/lib/proxyDispatcher.ts'() {
3209
+ 'use strict'
3210
+ init_assetsRoot()
3211
+ PROXY_VARS = ['HTTP_PROXY', 'http_proxy', 'HTTPS_PROXY', 'https_proxy', 'ALL_PROXY']
3212
+ installed = false
3213
+ },
3214
+ })
3215
+
3216
+ // src/cli/lib/updateSignature.ts
3217
+ import { createPublicKey, verify as edVerify } from 'node:crypto'
3218
+ function verifyShaSignature(shaText, sigBase64, publicKeyPem = HARNESSED_RELEASE_PUBKEY_PEM) {
3219
+ try {
3220
+ const sig = Buffer.from(sigBase64.trim(), 'base64')
3221
+ if (sig.length === 0) return false
3222
+ return edVerify(null, Buffer.from(shaText, 'utf8'), createPublicKey(publicKeyPem), sig)
3223
+ } catch {
3224
+ return false
3225
+ }
3226
+ }
3227
+ var HARNESSED_RELEASE_PUBKEY_PEM
3228
+ var init_updateSignature = __esm({
3229
+ 'src/cli/lib/updateSignature.ts'() {
3230
+ 'use strict'
3231
+ HARNESSED_RELEASE_PUBKEY_PEM = `-----BEGIN PUBLIC KEY-----
3232
+ MCowBQYDK2VwAyEAgCsfkZ+uCRNIBSHGfiOzp+TCSwQqOVJW1tsCW/beF4g=
3233
+ -----END PUBLIC KEY-----
3234
+ `
3235
+ },
3236
+ })
3237
+
3238
+ // src/cli/lib/selfUpdateBinary.ts
3239
+ var selfUpdateBinary_exports = {}
3240
+ __export(selfUpdateBinary_exports, {
3241
+ RELEASES_LATEST_URL: () => RELEASES_LATEST_URL,
3242
+ assetNameFor: () => assetNameFor,
3243
+ execDirWritable: () => execDirWritable,
3244
+ finalizeBinarySelfUpdate: () => finalizeBinarySelfUpdate,
3245
+ realSelfUpdateDeps: () => realSelfUpdateDeps,
3246
+ resolveLatestRelease: () => resolveLatestRelease,
3247
+ runBinaryRollback: () => runBinaryRollback,
3248
+ runBinarySelfUpdate: () => runBinarySelfUpdate,
3249
+ })
3250
+ import { createHash } from 'node:crypto'
3251
+ import { createWriteStream } from 'node:fs'
3252
+ import {
3253
+ access,
3254
+ chmod,
3255
+ copyFile as fsCopyFile,
3256
+ rename as fsRename,
3257
+ unlink as fsUnlink,
3258
+ mkdir,
3259
+ readdir,
3260
+ readFile,
3261
+ stat,
3262
+ } from 'node:fs/promises'
3263
+ import { basename, dirname as dirname4, join as join6 } from 'node:path'
3264
+ import { Readable, Transform } from 'node:stream'
3265
+ import { pipeline } from 'node:stream/promises'
3266
+ function assetNameFor(platform, arch) {
3267
+ const plat = { win32: 'windows', darwin: 'darwin', linux: 'linux' }[platform] ?? platform
3268
+ const ext = platform === 'win32' ? '.exe' : ''
3269
+ return `harnessed-${plat}-${arch}${ext}`
3270
+ }
3271
+ function normalized(p) {
3272
+ return p.replace(/\\/g, '/')
3273
+ }
3274
+ function downloadFailureMessage(error, version, url) {
3275
+ const detail = error instanceof Error ? error.message : String(error)
3276
+ const target = version ? ` for release v${version}` : ''
3277
+ return `download failed${target}${url ? ` (tried ${url})` : ''}: ${detail} \u2014 the original binary was left untouched; if the network blocks GitHub, use the npm channel (\`npm i -g harnessed@latest\`) or a local build via \`HARNESSED_UPDATE_SOURCE_DIR=<dir> harnessed update\``
3278
+ }
3279
+ async function sha256File(p) {
3280
+ const buf = await readFile(p)
3281
+ return createHash('sha256').update(buf).digest('hex')
3282
+ }
3283
+ function parseShaText(text) {
3284
+ const m = /^([0-9a-fA-F]{64})\b/.exec(text.trim())
3285
+ return m?.[1]?.toLowerCase() ?? null
3286
+ }
3287
+ async function runBinarySelfUpdate(deps, opts) {
3288
+ const rename = deps.fsOps?.rename ?? fsRename
3289
+ const copyFile = deps.fsOps?.copyFile ?? fsCopyFile
3290
+ const unlink = deps.fsOps?.unlink ?? fsUnlink
3291
+ if (normalized(deps.execPath).includes('/node_modules/')) {
3292
+ return { status: 'refused', reason: 'binary lives under node_modules (npm-managed)' }
3293
+ }
3294
+ const asset = assetNameFor(deps.platform, deps.arch)
3295
+ const execDir = dirname4(deps.execPath)
3296
+ const execBase = basename(deps.execPath)
3297
+ const ext = deps.platform === 'win32' ? '.exe' : ''
3298
+ const tempPath = join6(execDir, `.harnessed-update-${deps.pid}${ext}`)
3299
+ const bakPath = join6(execDir, `${execBase}.bak-${deps.currentVersion}`)
3300
+ let targetVersion = null
3301
+ let assetUrl = null
3302
+ let shaUrl = null
3303
+ let sigUrl = null
3304
+ let assetFallbackUrl
3305
+ let shaFallbackUrl
3306
+ let sigFallbackUrl
3307
+ let sourceAsset = null
3308
+ let sourceSha = null
3309
+ if (deps.sourceDir) {
3310
+ sourceAsset = join6(deps.sourceDir, asset)
3311
+ sourceSha = join6(deps.sourceDir, `${asset}.sha256`)
3312
+ if (opts.check) {
3313
+ try {
3314
+ const version = (await deps.smoke(sourceAsset)).trim()
3315
+ if (!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(version)) {
3316
+ throw new Error(`--version smoke returned unexpected output: ${version.slice(0, 80)}`)
3317
+ }
3318
+ return {
3319
+ status: 'checked',
3320
+ installed: deps.currentVersion,
3321
+ latest: version,
3322
+ cmp: compareVersions(deps.currentVersion, version),
3323
+ }
3324
+ } catch (e) {
3325
+ return {
3326
+ status: 'error',
3327
+ message: `could not check the local binary version: ${e.message}`,
3328
+ }
3329
+ }
3330
+ }
3331
+ } else {
3332
+ const rel = await deps.resolveRelease()
3333
+ if (rel === null) {
3334
+ return {
3335
+ status: 'error',
3336
+ message:
3337
+ 'could not resolve the latest release from GitHub (no release information returned) \u2014 use the npm channel (`npm i -g harnessed@latest`), or point `HARNESSED_UPDATE_SOURCE_DIR=<dir>` at a local build and re-run `harnessed update`',
3338
+ }
3339
+ }
3340
+ if ('error' in rel) {
3341
+ const publishing = rel.kind === void 0 || rel.kind === 'publishing'
3342
+ const remedy = publishing
3343
+ ? 'the release may still be publishing (retry in a few minutes) or use the npm channel (`npm i -g harnessed@latest`)'
3344
+ : 'the original binary was left untouched; use the npm channel (`npm i -g harnessed@latest`) or point `HARNESSED_UPDATE_SOURCE_DIR=<dir>` at a local build and re-run `harnessed update`'
3345
+ return { status: 'error', message: `${rel.error} \u2014 ${remedy}` }
3346
+ }
3347
+ targetVersion = rel.version
3348
+ assetUrl = rel.assetUrl
3349
+ shaUrl = rel.shaUrl
3350
+ sigUrl = rel.sigUrl ?? null
3351
+ assetFallbackUrl = rel.assetFallbackUrl
3352
+ shaFallbackUrl = rel.shaFallbackUrl
3353
+ sigFallbackUrl = rel.sigFallbackUrl
3354
+ if (opts.check) {
3355
+ return {
3356
+ status: 'checked',
3357
+ installed: deps.currentVersion,
3358
+ latest: rel.version,
3359
+ cmp: compareVersions(deps.currentVersion, rel.version),
3360
+ }
3361
+ }
3362
+ const cmp = compareVersions(deps.currentVersion, rel.version)
3363
+ if (cmp !== 'behind') {
3364
+ return { status: 'current', version: deps.currentVersion }
3365
+ }
3366
+ }
3367
+ const partPath = deps.sourceDir
3368
+ ? null
3369
+ : join6(execDir, `.harnessed-update-${targetVersion ?? 'unknown'}.part`)
3370
+ const verifyPath = partPath ?? tempPath
3371
+ const stagingPath = deps.sourceDir
3372
+ ? tempPath
3373
+ : join6(execDir, `.harnessed-update-${targetVersion ?? 'unknown'}${ext}`)
3374
+ if (opts.dryRun) {
3375
+ const backupDir2 = 'bin-backup/<oldver>/ under the harnessed state root'
3376
+ const steps = [
3377
+ deps.sourceDir
3378
+ ? `copy ${sourceAsset} \u2192 ${stagingPath} (local source dir \u2014 rehearsal seam)`
3379
+ : `download ${assetUrl ?? `latest ${asset}`} \u2192 ${partPath} (resumable fragment)`,
3380
+ `verify sha256 against ${deps.sourceDir ? sourceSha : (shaUrl ?? `${asset}.sha256`)}`,
3381
+ ...(deps.sourceDir
3382
+ ? []
3383
+ : ['verify the ed25519 signature (.sha256.sig) against the embedded release public key']),
3384
+ ...(deps.platform === 'win32' ? [] : ['chmod 755 the downloaded binary']),
3385
+ 'smoke: spawn `--version` on the new binary',
3386
+ `rename ${deps.execPath} \u2192 ${bakPath} (same-dir, same-volume)`,
3387
+ `rename ${stagingPath} \u2192 ${deps.execPath}`,
3388
+ `copy the .bak to ${backupDir2} (rollback net)`,
3389
+ 'delete the .bak (fail-soft \u2014 kept on Windows EPERM or when the backup copy failed)',
3390
+ ]
3391
+ return { status: 'dry-run', steps }
3392
+ }
3393
+ try {
3394
+ if (deps.sourceDir && sourceAsset) {
3395
+ await fsCopyFile(sourceAsset, tempPath)
3396
+ } else if (assetUrl && partPath) {
3397
+ await deps.downloadTo(assetUrl, partPath, assetFallbackUrl)
3398
+ }
3399
+ } catch (e) {
3400
+ if (!partPath) await unlink(tempPath).catch(() => {})
3401
+ return { status: 'error', message: downloadFailureMessage(e, targetVersion, assetUrl) }
3402
+ }
3403
+ try {
3404
+ const shaText = deps.sourceDir
3405
+ ? await readFile(sourceSha ?? '', 'utf8')
3406
+ : await deps.fetchShaText(shaUrl ?? '', shaFallbackUrl)
3407
+ const expected = parseShaText(shaText)
3408
+ if (!expected) throw new Error(`malformed .sha256 content`)
3409
+ const actual = await sha256File(verifyPath)
3410
+ if (actual !== expected) {
3411
+ throw new Error(
3412
+ `sha256 mismatch \u2014 expected ${expected.slice(0, 12)}\u2026, got ${actual.slice(0, 12)}\u2026`,
3413
+ )
3414
+ }
3415
+ if (!deps.sourceDir) {
3416
+ const sigText = await deps
3417
+ .fetchShaText(sigUrl ?? `${shaUrl ?? ''}.sig`, sigFallbackUrl)
3418
+ .catch(() => {
3419
+ throw new Error(`missing .sha256.sig (signature is contractual since 4.32.19)`)
3420
+ })
3421
+ if (!verifyShaSignature(shaText, sigText, deps.publicKeyPem)) {
3422
+ throw new Error(
3423
+ `ed25519 signature over .sha256 did not verify \u2014 the release assets may be tampered`,
3424
+ )
3425
+ }
3426
+ }
3427
+ } catch (e) {
3428
+ await unlink(verifyPath).catch(() => {})
3429
+ return {
3430
+ status: 'error',
3431
+ message: `integrity verification failed: ${e.message} \u2014 aborted; original binary untouched`,
3432
+ }
3433
+ }
3434
+ if (partPath) {
3435
+ try {
3436
+ await unlink(stagingPath).catch(() => {})
3437
+ await rename(partPath, stagingPath)
3438
+ } catch (e) {
3439
+ return {
3440
+ status: 'error',
3441
+ message: `could not stage the verified download: ${e.message} \u2014 the download was kept for the next attempt; original binary untouched`,
3442
+ }
3443
+ }
3444
+ }
3445
+ let smokeRan = false
3446
+ try {
3447
+ if (deps.platform !== 'win32') await chmod(stagingPath, 493)
3448
+ const out = (await deps.smoke(stagingPath)).trim()
3449
+ smokeRan = true
3450
+ const m = /^(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)/.exec(out)
3451
+ if (!m) throw new Error(`--version smoke returned unexpected output: ${out.slice(0, 80)}`)
3452
+ if (targetVersion !== null && out !== targetVersion) {
3453
+ throw new Error(`--version mismatch: expected ${targetVersion}, got ${out.slice(0, 80)}`)
3454
+ }
3455
+ targetVersion = targetVersion ?? m[1] ?? null
3456
+ } catch (e) {
3457
+ if (partPath && !smokeRan) {
3458
+ await rename(stagingPath, partPath).catch(() => {})
3459
+ } else {
3460
+ await unlink(stagingPath).catch(() => {})
3461
+ }
3462
+ return {
3463
+ status: 'error',
3464
+ message: `new binary failed the --version smoke: ${e.message} \u2014 aborted; original binary untouched`,
3465
+ }
3466
+ }
3467
+ try {
3468
+ await rename(deps.execPath, bakPath)
3469
+ } catch (e) {
3470
+ if (partPath) await rename(stagingPath, partPath).catch(() => {})
3471
+ else await unlink(stagingPath).catch(() => {})
3472
+ return {
3473
+ status: 'error',
3474
+ message: `could not move the current binary aside: ${e.message} \u2014 original untouched`,
3475
+ }
3476
+ }
3477
+ try {
3478
+ await rename(stagingPath, deps.execPath)
3479
+ } catch (e) {
3480
+ try {
3481
+ await rename(bakPath, deps.execPath)
3482
+ if (partPath) await rename(stagingPath, partPath).catch(() => {})
3483
+ else await unlink(stagingPath).catch(() => {})
3484
+ return {
3485
+ status: 'error',
3486
+ message: `swap failed (${e.message}) \u2014 rolled back to the previous binary`,
3487
+ }
3488
+ } catch (rb) {
3489
+ if (partPath) await rename(stagingPath, partPath).catch(() => {})
3490
+ return {
3491
+ status: 'error',
3492
+ critical: true,
3493
+ message: `CRITICAL: swap failed AND rollback failed (${rb.message}). Restore manually: copy "${bakPath}" "${deps.execPath}"`,
3494
+ }
3495
+ }
3496
+ }
3497
+ let backupDir = null
3498
+ let copied = false
3499
+ try {
3500
+ const dir = join6(deps.stateRoot(), 'bin-backup', deps.currentVersion)
3501
+ await mkdir(dir, { recursive: true })
3502
+ await copyFile(bakPath, join6(dir, execBase))
3503
+ backupDir = dir
3504
+ copied = true
3505
+ } catch (e) {
3506
+ deps.log(
3507
+ `warning: could not copy the previous binary to bin-backup (${e.message}) \u2014 keeping ${bakPath} as the rollback net`,
3508
+ )
3509
+ }
3510
+ let bakRemoved = false
3511
+ if (copied && !opts.retainBackupForContinuation) {
3512
+ try {
3513
+ await unlink(bakPath)
3514
+ bakRemoved = true
3515
+ } catch {}
3516
+ }
3517
+ return {
3518
+ status: 'updated',
3519
+ from: deps.currentVersion,
3520
+ to: targetVersion ?? '(unknown)',
3521
+ bakPath,
3522
+ bakRemoved,
3523
+ backupDir,
3524
+ }
3525
+ }
3526
+ async function finalizeBinarySelfUpdate(deps, outcome) {
3527
+ if (outcome.bakRemoved || outcome.backupDir === null) return outcome.bakRemoved
3528
+ const unlink = deps.fsOps?.unlink ?? fsUnlink
3529
+ try {
3530
+ await unlink(outcome.bakPath)
3531
+ outcome.bakRemoved = true
3532
+ return true
3533
+ } catch {
3534
+ return false
3535
+ }
3536
+ }
3537
+ async function runBinaryRollback(deps, opts) {
3538
+ const rename = deps.fsOps?.rename ?? fsRename
3539
+ const copyFile = deps.fsOps?.copyFile ?? fsCopyFile
3540
+ const unlink = deps.fsOps?.unlink ?? fsUnlink
3541
+ if (normalized(deps.execPath).includes('/node_modules/')) {
3542
+ return { status: 'refused', reason: 'binary lives under node_modules (npm-managed)' }
3543
+ }
3544
+ const asset = assetNameFor(deps.platform, deps.arch)
3545
+ const backupsRoot = join6(deps.stateRoot(), 'bin-backup')
3546
+ let versions = []
3547
+ try {
3548
+ const entries = await readdir(backupsRoot, { withFileTypes: true })
3549
+ for (const e of entries) {
3550
+ if (!e.isDirectory()) continue
3551
+ const has = await access(join6(backupsRoot, e.name, asset)).then(
3552
+ () => true,
3553
+ () => false,
3554
+ )
3555
+ if (has) versions.push(e.name)
3556
+ }
3557
+ } catch {
3558
+ versions = []
3559
+ }
3560
+ if (versions.length === 0) {
3561
+ return {
3562
+ status: 'error',
3563
+ message: `no rollback candidates \u2014 ${backupsRoot} holds no banked ${asset}`,
3564
+ }
3565
+ }
3566
+ let target
3567
+ if (opts.version) {
3568
+ if (!versions.includes(opts.version)) {
3569
+ return {
3570
+ status: 'error',
3571
+ message: `no backup for version ${opts.version} \u2014 available: ${versions.sort().join(', ')}`,
3572
+ }
3573
+ }
3574
+ target = opts.version
3575
+ } else {
3576
+ target = versions.reduce((a, b) => (compareVersions(a, b) === 'behind' ? b : a))
3577
+ }
3578
+ const backupBin = join6(backupsRoot, target, asset)
3579
+ const execDir = dirname4(deps.execPath)
3580
+ const execBase = basename(deps.execPath)
3581
+ const ext = deps.platform === 'win32' ? '.exe' : ''
3582
+ const tempPath = join6(execDir, `.harnessed-rollback-${deps.pid}${ext}`)
3583
+ const bakPath = join6(execDir, `${execBase}.bak-${deps.currentVersion}`)
3584
+ try {
3585
+ await fsCopyFile(backupBin, tempPath)
3586
+ if (deps.platform !== 'win32') await chmod(tempPath, 493)
3587
+ const out = (await deps.smoke(tempPath)).trim()
3588
+ if (!/^\d+\.\d+\.\d+/.test(out)) {
3589
+ throw new Error(`--version smoke returned unexpected output: ${out.slice(0, 80)}`)
3590
+ }
3591
+ } catch (e) {
3592
+ await unlink(tempPath).catch(() => {})
3593
+ return {
3594
+ status: 'error',
3595
+ message: `rollback staging failed: ${e.message} \u2014 original binary untouched`,
3596
+ }
3597
+ }
3598
+ try {
3599
+ await rename(deps.execPath, bakPath)
3600
+ } catch (e) {
3601
+ await unlink(tempPath).catch(() => {})
3602
+ return {
3603
+ status: 'error',
3604
+ message: `could not move the current binary aside: ${e.message} \u2014 original untouched`,
3605
+ }
3606
+ }
3607
+ try {
3608
+ await rename(tempPath, deps.execPath)
3609
+ } catch (e) {
3610
+ try {
3611
+ await rename(bakPath, deps.execPath)
3612
+ return {
3613
+ status: 'error',
3614
+ message: `swap failed (${e.message}) \u2014 restored the previous binary`,
3615
+ }
3616
+ } catch (rb) {
3617
+ return {
3618
+ status: 'error',
3619
+ message: `CRITICAL: swap failed AND restore failed (${rb.message}). Restore manually: copy "${bakPath}" "${deps.execPath}"`,
3620
+ }
3621
+ }
3622
+ }
3623
+ let copied = false
3624
+ try {
3625
+ const dir = join6(backupsRoot, deps.currentVersion)
3626
+ await mkdir(dir, { recursive: true })
3627
+ await copyFile(bakPath, join6(dir, execBase))
3628
+ copied = true
3629
+ } catch (e) {
3630
+ deps.log(`warning: could not bank the replaced binary (${e.message}) \u2014 keeping ${bakPath}`)
3631
+ }
3632
+ if (copied) await unlink(bakPath).catch(() => {})
3633
+ return { status: 'rolled-back', from: deps.currentVersion, to: target, backupUsed: backupBin }
3634
+ }
3635
+ function headerOf(res, name) {
3636
+ const headers = res.headers
3637
+ if (!headers || typeof headers.get !== 'function') return null
3638
+ return headers.get(name)
3639
+ }
3640
+ function parseContentRange(value) {
3641
+ if (!value) return null
3642
+ const text = value.trim()
3643
+ const unsat = /^bytes\s+\*\/(\d+|\*)$/i.exec(text)
3644
+ if (unsat) return { start: null, total: unsat[1] === '*' ? null : Number(unsat[1]) }
3645
+ const m = /^bytes\s+(\d+)-(\d+)\/(\d+|\*)$/i.exec(text)
3646
+ if (!m) return null
3647
+ return { start: Number(m[1]), total: m[3] === '*' ? null : Number(m[3]) }
3648
+ }
3649
+ function numberOrUndefined(value) {
3650
+ if (value === null) return void 0
3651
+ const n = Number(value)
3652
+ return Number.isFinite(n) ? n : void 0
3653
+ }
3654
+ async function fileSize(p) {
3655
+ try {
3656
+ return (await stat(p)).size
3657
+ } catch {
3658
+ return 0
3659
+ }
3660
+ }
3661
+ async function fetchWithTimeout(url, timeoutMs, net = {}, headers = {}, controller) {
3662
+ await ensureProxyDispatcher()
3663
+ const doFetch = net.fetchImpl ?? fetch
3664
+ const ac = controller ?? new AbortController()
3665
+ const timer = setTimeout(() => {
3666
+ ac.abort(new RequestTimeoutError(`the request to ${url} timed out after ${timeoutMs} ms`))
3667
+ }, timeoutMs)
3668
+ try {
3669
+ return await doFetch(url, {
3670
+ signal: ac.signal,
3671
+ headers: { 'user-agent': `harnessed/${package_default.version}`, ...headers },
3672
+ // GitHub's asset endpoint answers 302 → release-assets.githubusercontent.com
3673
+ // only when the Accept header asks for the raw bytes; without it the API
3674
+ // returns asset METADATA JSON instead of the file.
3675
+ redirect: 'follow',
3676
+ })
3677
+ } finally {
3678
+ clearTimeout(timer)
3679
+ }
3680
+ }
3681
+ function isTransientNetworkError(error) {
3682
+ const code = error?.code
3683
+ if (code && ['ECONNRESET', 'ECONNREFUSED', 'ETIMEDOUT', 'EPIPE', 'EAI_AGAIN'].includes(code)) {
3684
+ return true
3685
+ }
3686
+ const message = error instanceof Error ? error.message : String(error)
3687
+ return /socket connection was closed|ECONNRESET|ETIMEDOUT|network|terminated|fetch failed/i.test(
3688
+ message,
3689
+ )
3690
+ }
3691
+ async function fetchAsset(url, fallbackUrl, timeoutMs, net, label, consume, extra) {
3692
+ const sleep = net.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)))
3693
+ const attempts = []
3694
+ let lastError
3695
+ for (const candidate of [url, fallbackUrl].filter((u) => !!u)) {
3696
+ for (let attempt = 1; attempt <= DOWNLOAD_ATTEMPTS; attempt++) {
3697
+ const ac = new AbortController()
3698
+ try {
3699
+ const offset =
3700
+ extra?.existingBytes === void 0
3701
+ ? 0
3702
+ : await (typeof extra.existingBytes === 'function'
3703
+ ? extra.existingBytes()
3704
+ : extra.existingBytes)
3705
+ const headers = {
3706
+ accept: 'application/octet-stream',
3707
+ ...extra?.headers,
3708
+ }
3709
+ if (offset > 0) headers.range = `bytes=${offset}-`
3710
+ const res = await fetchWithTimeout(candidate, timeoutMs, net, headers, ac)
3711
+ if (!res.ok) {
3712
+ if (res.status === 416) {
3713
+ throw new RangeNotSatisfiableError(
3714
+ parseContentRange(headerOf(res, 'content-range'))?.total ?? null,
3715
+ )
3716
+ }
3717
+ lastError = new Error(`HTTP ${res.status} downloading ${candidate}`)
3718
+ if (res.status < 500) break
3719
+ } else {
3720
+ return await consume(res, ac, offset)
3721
+ }
3722
+ } catch (error) {
3723
+ if (error instanceof RangeNotSatisfiableError) throw error
3724
+ lastError = error
3725
+ const retryable =
3726
+ error instanceof RangeMismatchError ||
3727
+ error instanceof TransferStalledError ||
3728
+ isTransientNetworkError(error)
3729
+ if (!retryable) break
3730
+ }
3731
+ attempts.push(candidate)
3732
+ if (attempt < DOWNLOAD_ATTEMPTS) await sleep(250 * attempt)
3733
+ }
3734
+ }
3735
+ throw new Error(
3736
+ `${label} download failed (${attempts.length} attempt(s) over ${[url, fallbackUrl].filter(Boolean).join(', ')}): ${lastError instanceof Error ? lastError.message : String(lastError)}`,
3737
+ )
3738
+ }
3739
+ function formatBytes(n) {
3740
+ if (n >= 1024 * 1024) return `${(n / 1024 / 1024).toFixed(1)} MB`
3741
+ if (n >= 1024) return `${(n / 1024).toFixed(1)} KB`
3742
+ return `${n} B`
3743
+ }
3744
+ function formatRate(received, elapsedMs) {
3745
+ if (received <= 0 || elapsedMs <= 0) return '0 KB/s'
3746
+ return `${(received / 1024 / (elapsedMs / 1e3)).toFixed(1)} KB/s`
3747
+ }
3748
+ function transferStats(received, elapsedMs) {
3749
+ const seconds = (elapsedMs / 1e3).toFixed(1)
3750
+ const rate = received > 0 ? `, ${formatRate(received, elapsedMs)} average` : ''
3751
+ return `${received} bytes received in ${seconds} s${rate}`
3752
+ }
3753
+ async function streamAssetToFile(res, dest, ac, stallTimeoutMs, progressIntervalMs, log, opts) {
3754
+ if (!res.body) throw new Error('the release asset response carried no body')
3755
+ const started = Date.now()
3756
+ const initialBytes = opts?.initialBytes ?? 0
3757
+ let received = initialBytes
3758
+ let attemptBytes = 0
3759
+ let lastProgressAt = started
3760
+ let stalled = false
3761
+ let stallTimer
3762
+ const resetStall = () => {
3763
+ if (stallTimer) clearTimeout(stallTimer)
3764
+ stallTimer = setTimeout(() => {
3765
+ stalled = true
3766
+ ac.abort(
3767
+ new TransferStalledError(`no data received for ${Math.round(stallTimeoutMs / 1e3)} s`),
3768
+ )
3769
+ }, stallTimeoutMs)
3770
+ }
3771
+ const meter = new Transform({
3772
+ transform(chunk, _encoding, callback) {
3773
+ received += chunk.length
3774
+ attemptBytes += chunk.length
3775
+ const now = Date.now()
3776
+ if (now - lastProgressAt >= progressIntervalMs) {
3777
+ lastProgressAt = now
3778
+ const total = opts?.totalBytes
3779
+ const totalPart = total ? ` / ${formatBytes(total)}` : ''
3780
+ log(
3781
+ `downloading ${formatBytes(received)}${totalPart} (${formatRate(attemptBytes, now - started)})`,
3782
+ )
3783
+ }
3784
+ resetStall()
3785
+ callback(null, chunk)
3786
+ },
3787
+ })
3788
+ resetStall()
3789
+ try {
3790
+ await pipeline(
3791
+ // undici types the body as a DOM-ish ReadableStream; node:stream/web's
3792
+ // class is the one Readable.fromWeb accepts.
3793
+ Readable.fromWeb(res.body),
3794
+ meter,
3795
+ // flags 'a' appends (a 206 continues the fragment); 'w' truncates (a
3796
+ // 200 rewrites it — a retried attempt must not append to the bytes a
3797
+ // previous attempt already wrote).
3798
+ createWriteStream(dest, { flags: opts?.append ? 'a' : 'w' }),
3799
+ { signal: ac.signal },
3800
+ )
3801
+ } catch (e) {
3802
+ if (stalled) {
3803
+ throw new TransferStalledError(
3804
+ `the download stalled \u2014 no data for ${Math.round(stallTimeoutMs / 1e3)} s (${transferStats(attemptBytes, Date.now() - started)})`,
3805
+ )
3806
+ }
3807
+ throw e
3808
+ } finally {
3809
+ if (stallTimer) clearTimeout(stallTimer)
3810
+ }
3811
+ }
3812
+ async function downloadResumableAsset(url, fallbackUrl, dest, net, log) {
3813
+ const stallTimeoutMs = net.stallTimeoutMs ?? ASSET_STALL_TIMEOUT_MS
3814
+ const progressIntervalMs = net.progressIntervalMs ?? ASSET_PROGRESS_INTERVAL_MS
3815
+ let forceFullDownload = false
3816
+ const offsetOf = async () => {
3817
+ if (forceFullDownload) return 0
3818
+ return await fileSize(dest)
3819
+ }
3820
+ for (let round = 0; round < 2; round++) {
3821
+ try {
3822
+ await fetchAsset(
3823
+ url,
3824
+ fallbackUrl,
3825
+ ASSET_HEADERS_TIMEOUT_MS,
3826
+ net,
3827
+ 'binary',
3828
+ async (res, attempt, requested) => {
3829
+ const range = parseContentRange(headerOf(res, 'content-range'))
3830
+ const start = range ? range.start : null
3831
+ const totalBytes =
3832
+ res.status === 206
3833
+ ? (range?.total ?? void 0)
3834
+ : numberOrUndefined(headerOf(res, 'content-length'))
3835
+ if (res.status === 206) {
3836
+ if (start === null || start !== requested) {
3837
+ await fsUnlink(dest).catch(() => {})
3838
+ forceFullDownload = true
3839
+ throw new RangeMismatchError(
3840
+ `the server answered 206 starting at ${start ?? '?'}, not ${requested}`,
3841
+ )
3842
+ }
3843
+ await streamAssetToFile(res, dest, attempt, stallTimeoutMs, progressIntervalMs, log, {
3844
+ append: true,
3845
+ initialBytes: requested,
3846
+ totalBytes,
3847
+ })
3848
+ return
3849
+ }
3850
+ await streamAssetToFile(res, dest, attempt, stallTimeoutMs, progressIntervalMs, log, {
3851
+ append: false,
3852
+ initialBytes: 0,
3853
+ totalBytes,
3854
+ })
3855
+ },
3856
+ { existingBytes: offsetOf },
3857
+ )
3858
+ return
3859
+ } catch (e) {
3860
+ if (e instanceof RangeNotSatisfiableError) {
3861
+ const have = await fileSize(dest)
3862
+ if (e.total !== null && e.total === have) return
3863
+ await fsUnlink(dest).catch(() => {})
3864
+ forceFullDownload = true
3865
+ continue
3866
+ }
3867
+ throw e
3868
+ }
3869
+ }
3870
+ throw new Error('the release asset could not be downloaded (the server ignored the resume range)')
3871
+ }
3872
+ async function resolveLatestRelease(platform = process.platform, arch = process.arch, net = {}) {
3873
+ let res
3874
+ try {
3875
+ res = await fetchWithTimeout(RELEASES_LATEST_URL, RELEASE_METADATA_TIMEOUT_MS, net)
3876
+ } catch (e) {
3877
+ const budget = `${RELEASE_METADATA_TIMEOUT_MS / 1e3} s timeout budget`
3878
+ return {
3879
+ error:
3880
+ e instanceof RequestTimeoutError
3881
+ ? `the request to the GitHub releases API timed out (${budget})`
3882
+ : `the request to the GitHub releases API failed or timed out (${budget}): ${e instanceof Error ? e.message : String(e)}`,
3883
+ kind: e instanceof RequestTimeoutError ? 'timeout' : 'network',
3884
+ }
3885
+ }
3886
+ if (!res.ok) {
3887
+ return { error: `the GitHub releases API returned HTTP ${res.status}`, kind: 'http' }
3888
+ }
3889
+ let body
3890
+ try {
3891
+ body = await res.json()
3892
+ } catch (e) {
3893
+ return {
3894
+ error: `the GitHub releases API response could not be parsed: ${e instanceof Error ? e.message : String(e)}`,
3895
+ kind: 'parse',
3896
+ }
3897
+ }
3898
+ const version = (body.tag_name ?? '').replace(/^v/, '')
3899
+ if (!/^\d+\.\d+\.\d+/.test(version)) {
3900
+ return {
3901
+ error: `the GitHub releases API response could not be parsed: unexpected tag_name "${body.tag_name ?? ''}"`,
3902
+ kind: 'parse',
3903
+ }
3904
+ }
3905
+ const asset = assetNameFor(platform, arch)
3906
+ const pick = (name) => body.assets?.find((a) => a.name === name)
3907
+ const found = pick(asset)
3908
+ const sha = pick(`${asset}.sha256`)
3909
+ const sig = pick(`${asset}.sha256.sig`)
3910
+ if (!found?.browser_download_url && !found?.url) {
3911
+ return { error: `asset ${asset} not found on release v${version}`, kind: 'publishing' }
3912
+ }
3913
+ if (!sha?.browser_download_url && !sha?.url) {
3914
+ return { error: `asset ${asset}.sha256 not found on release v${version}`, kind: 'publishing' }
3915
+ }
3916
+ const pair = (a) => {
3917
+ const api = a?.url
3918
+ const browser = a?.browser_download_url
3919
+ return api && browser
3920
+ ? { primary: api, fallback: browser }
3921
+ : { primary: api ?? browser ?? '', fallback: void 0 }
3922
+ }
3923
+ const assetPair = pair(found)
3924
+ const shaPair = pair(sha)
3925
+ const sigPair = pair(sig)
3926
+ return {
3927
+ version,
3928
+ assetUrl: assetPair.primary,
3929
+ shaUrl: shaPair.primary,
3930
+ sigUrl: sigPair.primary || void 0,
3931
+ assetFallbackUrl: assetPair.fallback,
3932
+ shaFallbackUrl: shaPair.fallback,
3933
+ sigFallbackUrl: sigPair.fallback,
3934
+ }
3935
+ }
3936
+ function realSelfUpdateDeps(context, net = {}) {
3937
+ const log = (line) => console.warn(line)
3938
+ return {
3939
+ execPath: process.execPath,
3940
+ platform: process.platform,
3941
+ arch: process.arch,
3942
+ currentVersion: package_default.version,
3943
+ sourceDir: process.env.HARNESSED_UPDATE_SOURCE_DIR?.trim() || null,
3944
+ resolveRelease: () => resolveLatestRelease(process.platform, process.arch, net),
3945
+ downloadTo: async (url, dest, fallbackUrl) => {
3946
+ await downloadResumableAsset(url, fallbackUrl, dest, net, log)
3947
+ },
3948
+ fetchShaText: async (url, fallbackUrl) => {
3949
+ return fetchAsset(url, fallbackUrl, CHECKSUM_TIMEOUT_MS, net, 'checksum', (res) => res.text())
3950
+ },
3951
+ smoke: async (bin) => {
3952
+ const { execFile: execFile2 } = await import('node:child_process')
3953
+ const { promisify: promisify2 } = await import('node:util')
3954
+ const { stdout } = await promisify2(execFile2)(bin, ['--version'], {
3955
+ timeout: 3e4,
3956
+ windowsHide: true,
3957
+ shell: false,
3958
+ env: withHostInstallEnv(process.env, context),
3959
+ })
3960
+ return stdout
3961
+ },
3962
+ stateRoot: () => context.platform.stateRoot,
3963
+ log,
3964
+ pid: process.pid,
3965
+ }
3966
+ }
3967
+ async function execDirWritable(execPath) {
3968
+ try {
3969
+ await access(
3970
+ dirname4(execPath),
3971
+ 2,
3972
+ /* W_OK */
3973
+ )
3974
+ return true
3975
+ } catch {
3976
+ return false
3977
+ }
3978
+ }
3979
+ var OWNER_REPO,
3980
+ RELEASES_LATEST_URL,
3981
+ RELEASE_METADATA_TIMEOUT_MS,
3982
+ ASSET_HEADERS_TIMEOUT_MS,
3983
+ CHECKSUM_TIMEOUT_MS,
3984
+ ASSET_STALL_TIMEOUT_MS,
3985
+ ASSET_PROGRESS_INTERVAL_MS,
3986
+ RequestTimeoutError,
3987
+ TransferStalledError,
3988
+ RangeMismatchError,
3989
+ RangeNotSatisfiableError,
3990
+ DOWNLOAD_ATTEMPTS
3991
+ var init_selfUpdateBinary = __esm({
3992
+ 'src/cli/lib/selfUpdateBinary.ts'() {
3993
+ 'use strict'
3994
+ init_package()
3995
+ init_runClaudeArgs()
3996
+ init_proxyDispatcher()
3997
+ init_updateSignature()
3998
+ init_version_check()
3999
+ OWNER_REPO = 'easyinplay/harnessed'
4000
+ RELEASES_LATEST_URL = `https://api.github.com/repos/${OWNER_REPO}/releases/latest`
4001
+ RELEASE_METADATA_TIMEOUT_MS = 3e4
4002
+ ASSET_HEADERS_TIMEOUT_MS = 12e4
4003
+ CHECKSUM_TIMEOUT_MS = 3e4
4004
+ ASSET_STALL_TIMEOUT_MS = 12e4
4005
+ ASSET_PROGRESS_INTERVAL_MS = 6e4
4006
+ RequestTimeoutError = class extends Error {}
4007
+ TransferStalledError = class extends Error {}
4008
+ RangeMismatchError = class extends Error {}
4009
+ RangeNotSatisfiableError = class extends Error {
4010
+ constructor(total) {
4011
+ super('the requested range is not satisfiable')
4012
+ this.total = total
4013
+ }
4014
+ total
4015
+ }
4016
+ DOWNLOAD_ATTEMPTS = 3
4017
+ },
4018
+ })
4019
+
4020
+ // src/cli/lib/updateLock.ts
4021
+ var updateLock_exports = {}
4022
+ __export(updateLock_exports, {
4023
+ UPDATE_LOCK_PROTOCOL_VERSION: () => UPDATE_LOCK_PROTOCOL_VERSION,
4024
+ acquireUpdateLock: () => acquireUpdateLock,
4025
+ consumeUpdateLockContinuation: () => consumeUpdateLockContinuation,
4026
+ updateTargetKey: () => updateTargetKey,
4027
+ withUpdateLock: () => withUpdateLock,
4028
+ })
4029
+ import { createHash as createHash2, randomBytes, timingSafeEqual } from 'node:crypto'
4030
+ import {
4031
+ closeSync as closeSync2,
4032
+ fsyncSync,
4033
+ mkdirSync as mkdirSync3,
4034
+ openSync as openSync2,
4035
+ readFileSync as readFileSync4,
4036
+ realpathSync,
4037
+ renameSync as renameSync3,
4038
+ statSync,
4039
+ unlinkSync,
4040
+ writeFileSync as writeFileSync3,
4041
+ } from 'node:fs'
4042
+ import {
4043
+ basename as basename2,
4044
+ dirname as dirname5,
4045
+ join as join7,
4046
+ resolve as resolve3,
4047
+ } from 'node:path'
4048
+ import { setTimeout as delay } from 'node:timers/promises'
4049
+ function normalizeTarget(target) {
4050
+ let candidate = resolve3(target)
4051
+ const missing = []
4052
+ for (;;) {
4053
+ try {
4054
+ let canonical = resolve3(realpathSync.native(candidate), ...missing)
4055
+ if (/\.(?:[cm]?js|ts)$/.test(canonical)) {
4056
+ for (let directory = dirname5(canonical); ; ) {
4057
+ try {
4058
+ const manifest = JSON.parse(readFileSync4(join7(directory, 'package.json'), 'utf8'))
4059
+ if (manifest.name === 'harnessed') canonical = directory
4060
+ break
4061
+ } catch (error) {
4062
+ if (error.code !== 'ENOENT') throw error
4063
+ }
4064
+ const parent = dirname5(directory)
4065
+ if (parent === directory) break
4066
+ directory = parent
4067
+ }
4068
+ }
4069
+ return process.platform === 'win32' ? canonical.toLowerCase() : canonical
4070
+ } catch (error) {
4071
+ if (error.code !== 'ENOENT') throw error
4072
+ missing.unshift(basename2(candidate))
4073
+ const parent = dirname5(candidate)
4074
+ if (parent === candidate) throw error
4075
+ candidate = parent
4076
+ }
4077
+ }
4078
+ }
4079
+ function updateTargetKey(target) {
4080
+ return createHash2('sha256').update(normalizeTarget(target), 'utf8').digest('hex')
4081
+ }
4082
+ function pathsFor(target) {
4083
+ const anchor = `${target}.harnessed-update-anchor`
4084
+ return { anchor, path: `${anchor}.json` }
4085
+ }
4086
+ function ensureAnchor(anchor) {
4087
+ mkdirSync3(dirname5(anchor), { recursive: true })
4088
+ const descriptor = openSync2(anchor, 'a', 384)
4089
+ closeSync2(descriptor)
4090
+ }
4091
+ function guarded(anchor, work, recover = true) {
4092
+ const release = import_proper_lockfile.default.lockSync(anchor, {
4093
+ realpath: true,
4094
+ retries: 0,
4095
+ stale: recover ? 3e4 : Number.MAX_SAFE_INTEGER,
4096
+ update: 1e3,
4097
+ })
4098
+ try {
4099
+ return work()
4100
+ } finally {
4101
+ release()
4102
+ }
4103
+ }
4104
+ function defaultIsProcessAlive(pid) {
4105
+ try {
4106
+ process.kill(pid, 0)
4107
+ return true
4108
+ } catch (error) {
4109
+ return error.code !== 'ESRCH'
4110
+ }
4111
+ }
4112
+ function sameSecret(left, right) {
4113
+ const leftBuffer = Buffer.from(left)
4114
+ const rightBuffer = Buffer.from(right)
4115
+ return leftBuffer.length === rightBuffer.length && timingSafeEqual(leftBuffer, rightBuffer)
4116
+ }
4117
+ function readLockRecord(path) {
4118
+ try {
4119
+ if (statSync(path).size > MAX_LOCK_BYTES) return null
4120
+ const value = JSON.parse(readFileSync4(path, 'utf8'))
4121
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null
4122
+ if (
4123
+ value.protocolVersion !== UPDATE_LOCK_PROTOCOL_VERSION ||
4124
+ typeof value.target !== 'string' ||
4125
+ typeof value.targetKey !== 'string' ||
4126
+ typeof value.nonce !== 'string' ||
4127
+ !Number.isInteger(value.ownerPid) ||
4128
+ (value.ownerPid ?? 0) <= 0 ||
4129
+ !Number.isFinite(value.createdAt) ||
4130
+ !Number.isFinite(value.heartbeatAt) ||
4131
+ (value.consumedAt !== null && !Number.isFinite(value.consumedAt))
4132
+ )
4133
+ return null
4134
+ return value
4135
+ } catch (error) {
4136
+ if (error instanceof SyntaxError || error.code === 'ENOENT') return null
4137
+ throw error
4138
+ }
4139
+ }
4140
+ function removeTemporaryLockRecord(path) {
4141
+ try {
4142
+ unlinkSync(path)
4143
+ } catch (error) {
4144
+ if (error.code !== 'ENOENT') throw error
4145
+ }
4146
+ }
4147
+ function writeLockRecord(path, record) {
4148
+ const temporary = `${path}.${randomBytes(12).toString('hex')}.tmp`
4149
+ try {
4150
+ const descriptor = openSync2(temporary, 'wx', 384)
4151
+ try {
4152
+ writeFileSync3(
4153
+ descriptor,
4154
+ `${JSON.stringify(record)}
4155
+ `,
4156
+ 'utf8',
4157
+ )
4158
+ fsyncSync(descriptor)
4159
+ } finally {
4160
+ closeSync2(descriptor)
4161
+ }
4162
+ renameSync3(temporary, path)
4163
+ } finally {
4164
+ removeTemporaryLockRecord(temporary)
4165
+ }
4166
+ }
4167
+ async function consumeUpdateLockContinuation(options) {
4168
+ if (options.protocolVersion !== UPDATE_LOCK_PROTOCOL_VERSION)
4169
+ return { ok: false, reason: 'protocol-mismatch' }
4170
+ const target = normalizeTarget(options.target)
4171
+ const targetKey = updateTargetKey(target)
4172
+ if (options.targetKey !== targetKey) return { ok: false, reason: 'target-mismatch' }
4173
+ const { anchor, path } = pathsFor(target)
4174
+ ensureAnchor(anchor)
4175
+ return guarded(anchor, () => {
4176
+ const current = readLockRecord(path)
4177
+ if (!current || current.target !== target || current.targetKey !== targetKey) {
4178
+ return { ok: false, reason: 'target-mismatch' }
4179
+ }
4180
+ if (!sameSecret(options.nonce, current.nonce)) return { ok: false, reason: 'nonce-mismatch' }
4181
+ if (current.consumedAt !== null) return { ok: false, reason: 'nonce-consumed' }
4182
+ if (!defaultIsProcessAlive(current.ownerPid)) return { ok: false, reason: 'target-mismatch' }
4183
+ const timestamp = (options.now ?? Date.now)()
4184
+ writeLockRecord(path, {
4185
+ ...current,
4186
+ ownerPid: options.pid ?? process.pid,
4187
+ heartbeatAt: timestamp,
4188
+ consumedAt: timestamp,
4189
+ })
4190
+ return { ok: true }
4191
+ })
4192
+ }
4193
+ async function acquireUpdateLock(options) {
4194
+ const now = options.now ?? Date.now
4195
+ const target = normalizeTarget(options.target)
4196
+ const targetKey = updateTargetKey(target)
4197
+ const { anchor, path } = pathsFor(target)
4198
+ const nonce = options.nonce ?? randomBytes(24).toString('base64url')
4199
+ const busy = (ownerPid = null) => ({
4200
+ status: 'busy',
4201
+ targetKey,
4202
+ ownerPid,
4203
+ })
4204
+ ensureAnchor(anchor)
4205
+ try {
4206
+ return guarded(
4207
+ anchor,
4208
+ () => {
4209
+ const current = readLockRecord(path)
4210
+ let modified = null
4211
+ try {
4212
+ modified = statSync(path).mtimeMs
4213
+ } catch (error) {
4214
+ if (error.code !== 'ENOENT') throw error
4215
+ }
4216
+ if (modified !== null) {
4217
+ const stale =
4218
+ now() - (current?.heartbeatAt ?? modified) >
4219
+ Math.max(1e3, options.staleAfterMs ?? DEFAULT_STALE_AFTER_MS)
4220
+ if (
4221
+ !stale ||
4222
+ (options.maxStaleRecoveries ?? 1) <= 0 ||
4223
+ (current && (options.isProcessAlive ?? defaultIsProcessAlive)(current.ownerPid))
4224
+ )
4225
+ return busy(current?.ownerPid)
4226
+ }
4227
+ const timestamp = now()
4228
+ writeLockRecord(path, {
4229
+ protocolVersion: UPDATE_LOCK_PROTOCOL_VERSION,
4230
+ target,
4231
+ targetKey,
4232
+ nonce,
4233
+ ownerPid: options.pid ?? process.pid,
4234
+ createdAt: timestamp,
4235
+ heartbeatAt: timestamp,
4236
+ consumedAt: null,
4237
+ })
4238
+ const handle = {
4239
+ path,
4240
+ target,
4241
+ targetKey,
4242
+ nonce,
4243
+ async refresh() {
4244
+ try {
4245
+ guarded(anchor, () => {
4246
+ const current2 = readLockRecord(path)
4247
+ if (current2 && sameSecret(current2.nonce, nonce))
4248
+ writeLockRecord(path, { ...current2, heartbeatAt: now() })
4249
+ })
4250
+ } catch (error) {
4251
+ if (error.code !== 'ELOCKED') throw error
4252
+ }
4253
+ },
4254
+ consumeContinuation: (input) =>
4255
+ consumeUpdateLockContinuation({ stateRoot: options.stateRoot, target, ...input, now }),
4256
+ async release() {
4257
+ for (let attempt = 0; attempt < 10; attempt++) {
4258
+ try {
4259
+ guarded(anchor, () => {
4260
+ const current2 = readLockRecord(path)
4261
+ if (current2 && sameSecret(current2.nonce, nonce)) unlinkSync(path)
4262
+ })
4263
+ return
4264
+ } catch (error) {
4265
+ if (error.code !== 'ELOCKED') throw error
4266
+ await delay(20)
4267
+ }
4268
+ }
4269
+ throw new Error('Update lock release guard remained busy')
4270
+ },
4271
+ }
4272
+ return { status: 'acquired', lock: handle }
4273
+ },
4274
+ (options.maxStaleRecoveries ?? 1) > 0,
4275
+ )
4276
+ } catch (error) {
4277
+ if (error.code === 'ELOCKED') return busy()
4278
+ throw error
4279
+ }
4280
+ }
4281
+ async function withUpdateLock(options, work) {
4282
+ const acquired = await acquireUpdateLock(options)
4283
+ if (acquired.status === 'busy') return acquired
4284
+ const heartbeat = setInterval(
4285
+ () => void acquired.lock.refresh().catch(() => {}),
4286
+ Math.max(1e3, Math.min(3e4, Math.floor((options.staleAfterMs ?? DEFAULT_STALE_AFTER_MS) / 3))),
4287
+ )
4288
+ heartbeat.unref()
4289
+ try {
4290
+ return { status: 'completed', value: await work(acquired.lock) }
4291
+ } finally {
4292
+ clearInterval(heartbeat)
4293
+ await acquired.lock.release()
4294
+ }
4295
+ }
4296
+ var import_proper_lockfile, UPDATE_LOCK_PROTOCOL_VERSION, DEFAULT_STALE_AFTER_MS, MAX_LOCK_BYTES
4297
+ var init_updateLock = __esm({
4298
+ 'src/cli/lib/updateLock.ts'() {
4299
+ 'use strict'
4300
+ import_proper_lockfile = __toESM(require_proper_lockfile(), 1)
4301
+ UPDATE_LOCK_PROTOCOL_VERSION = 1
4302
+ DEFAULT_STALE_AFTER_MS = 5 * 6e4
4303
+ MAX_LOCK_BYTES = 16 * 1024
4304
+ },
4305
+ })
4306
+
4307
+ // src/cli/lib/ownedRefreshFlag.ts
4308
+ var OWNED_REFRESH_FLAG
4309
+ var init_ownedRefreshFlag = __esm({
4310
+ 'src/cli/lib/ownedRefreshFlag.ts'() {
4311
+ 'use strict'
4312
+ OWNED_REFRESH_FLAG = '--internal-owned-refresh'
4313
+ },
4314
+ })
4315
+
4316
+ // src/cli/lib/ownedRefresh.ts
4317
+ import { spawn } from 'node:child_process'
4318
+ async function spawnOwnedRefresh(
4319
+ execPath,
4320
+ context,
4321
+ deps = {},
4322
+ timeoutMs = OWNED_REFRESH_TIMEOUT_MS,
4323
+ ) {
4324
+ const spawnImpl = deps.spawn ?? spawn
4325
+ return new Promise((resolve5) => {
4326
+ let child
4327
+ try {
4328
+ child = spawnImpl(execPath, [OWNED_REFRESH_FLAG], {
4329
+ env: withHostInstallEnv(process.env, context),
4330
+ // stdout is dropped on purpose: the handover's result is the exit code,
4331
+ // and the parent owns the user-facing line. Keeping the child's stdout
4332
+ // empty also means an abrupt child exit cannot truncate a half-written
4333
+ // summary. stderr stays inherited so a failed refresh explains itself.
4334
+ stdio: ['ignore', 'ignore', 'inherit'],
4335
+ windowsHide: true,
4336
+ shell: false,
4337
+ })
4338
+ } catch (error) {
4339
+ resolve5({
4340
+ ok: false,
4341
+ exitCode: null,
4342
+ error: error instanceof Error ? error.message : String(error),
4343
+ })
4344
+ return
4345
+ }
4346
+ const timer = setTimeout(() => {
4347
+ try {
4348
+ killProcessTree(child)
4349
+ } catch {}
4350
+ resolve5({ ok: false, exitCode: null, error: `timed out after ${timeoutMs}ms` })
4351
+ }, timeoutMs)
4352
+ child.on('error', (error) => {
4353
+ clearTimeout(timer)
4354
+ resolve5({ ok: false, exitCode: null, error: error.message })
4355
+ })
4356
+ child.on('close', (code) => {
4357
+ clearTimeout(timer)
4358
+ resolve5({ ok: code === 0, exitCode: code })
4359
+ })
4360
+ })
4361
+ }
4362
+ var OWNED_REFRESH_TIMEOUT_MS
4363
+ var init_ownedRefresh = __esm({
4364
+ 'src/cli/lib/ownedRefresh.ts'() {
4365
+ 'use strict'
4366
+ init_killTree()
4367
+ init_runClaudeArgs()
4368
+ init_autoUpdateStatus()
4369
+ init_ownedRefreshFlag()
4370
+ OWNED_REFRESH_TIMEOUT_MS = 18e4
4371
+ },
4372
+ })
4373
+
4374
+ // src/cli/lib/autoUpdateHandover.ts
4375
+ var autoUpdateHandover_exports = {}
4376
+ __export(autoUpdateHandover_exports, {
4377
+ AUTO_UPDATE_STATUS_PATH_ENV: () => AUTO_UPDATE_STATUS_PATH_ENV,
4378
+ handoverAutoUpdate: () => handoverAutoUpdate,
4379
+ })
4380
+ async function handoverAutoUpdate(input, deps) {
4381
+ const { from, statusPath } = input
4382
+ try {
4383
+ const { readAutoUpdateNotice: readAutoUpdateNotice2 } = await Promise.resolve().then(
4384
+ () => (init_autoUpdateNotice(), autoUpdateNotice_exports),
4385
+ )
4386
+ const notice = readAutoUpdateNotice2(statusPath)
4387
+ if (notice) writeAutoUpdateNotice(statusPath, { ...notice, from })
4388
+ } catch {}
4389
+ const previous = process.env[AUTO_UPDATE_STATUS_PATH_ENV]
4390
+ process.env[AUTO_UPDATE_STATUS_PATH_ENV] = statusPath
4391
+ try {
4392
+ const execPath = deps.execPath
4393
+ const context = deps.context
4394
+ const spawnImpl = deps.spawnOwnedRefresh ?? spawnOwnedRefresh
4395
+ const refresh = await spawnImpl(execPath, context, { spawn: deps.spawn })
4396
+ return refresh.ok ? { ok: true } : { ok: false, error: refresh.error }
4397
+ } catch (error) {
4398
+ return { ok: false, error: error instanceof Error ? error.message : String(error) }
4399
+ } finally {
4400
+ if (previous === void 0) delete process.env[AUTO_UPDATE_STATUS_PATH_ENV]
4401
+ else process.env[AUTO_UPDATE_STATUS_PATH_ENV] = previous
4402
+ }
4403
+ }
4404
+ var init_autoUpdateHandover = __esm({
4405
+ 'src/cli/lib/autoUpdateHandover.ts'() {
4406
+ 'use strict'
4407
+ init_autoUpdateNotice()
4408
+ init_autoUpdateStatus()
4409
+ init_ownedRefresh()
4410
+ },
4411
+ })
4412
+
4413
+ // src/cli/updateReminderWorkerMain.ts
4414
+ var updateReminderWorkerMain_exports = {}
4415
+ __export(updateReminderWorkerMain_exports, {
4416
+ runUpdateReminderWorker: () => runUpdateReminderWorker,
4417
+ })
4418
+ import { randomUUID } from 'node:crypto'
4419
+ import { realpathSync as realpathSync2, statSync as statSync2 } from 'node:fs'
4420
+ import asyncFs from 'node:fs/promises'
4421
+ import { dirname as dirname6, join as join8 } from 'node:path'
4422
+ function autoUpdateChannel(channel) {
4423
+ if (channel === 'binary' || channel === 'npm' || channel === 'bun' || channel === 'node') {
4424
+ return channel
4425
+ }
4426
+ return 'npm'
4427
+ }
4428
+ function resumeFragmentBytes(execPath, version) {
4429
+ try {
4430
+ return statSync2(join8(dirname6(execPath), `.harnessed-update-${version}.part`)).size
4431
+ } catch {
4432
+ return 0
4433
+ }
4434
+ }
4435
+ function readAutoUpdateConsent(preferencesPath) {
4436
+ const { preferences, document } = readUpdateReminderPreferencesFile(preferencesPath)
4437
+ const schemaVersion = typeof document?.schemaVersion === 'number' ? document.schemaVersion : null
4438
+ return { ...preferences, schemaVersion }
4439
+ }
4440
+ async function runAutomaticUpdate(options, targetVersion) {
4441
+ const preferencesPath = options.preferencesPath
4442
+ if (!preferencesPath) return
4443
+ if (!isAutoUpdateConsentGranted(readAutoUpdateConsent(preferencesPath))) return
4444
+ const [
4445
+ { captureHostInstallContext: captureHostInstallContext2 },
4446
+ engine,
4447
+ { withUpdateLock: withUpdateLock2 },
4448
+ ] = await Promise.all([
4449
+ Promise.resolve().then(() => (init_hostInstallContext(), hostInstallContext_exports)),
4450
+ Promise.resolve().then(() => (init_selfUpdateBinary(), selfUpdateBinary_exports)),
4451
+ Promise.resolve().then(() => (init_updateLock(), updateLock_exports)),
4452
+ ])
4453
+ const context = captureHostInstallContext2({ hostId: options.identity.host })
4454
+ const stateRoot = options.stateRoot ?? dirname6(options.cachePath)
4455
+ const statusPath = autoUpdateStatusPath(stateRoot)
4456
+ const deps = {
4457
+ readPreferences: () => readAutoUpdateConsent(preferencesPath),
4458
+ channel: () => autoUpdateChannel(options.identity.channel),
4459
+ installedVersion: () => options.installed,
4460
+ context: () => context,
4461
+ // The lock target is the exec path — `updateTarget().target` for the
4462
+ // binary channel is exactly `realpath(process.execPath)`
4463
+ // (updateCoordinator.ts:233-239). It is spelled out here instead of
4464
+ // importing the coordinator, which would drag the i18n and the repair
4465
+ // machinery into the always-resident reminder worker bundle.
4466
+ target: () => realpathSync2(process.execPath),
4467
+ execDirWritable: (execPath) => engine.execDirWritable(execPath),
4468
+ withLock: async (input, work) =>
4469
+ withUpdateLock2({ stateRoot: input.stateRoot, target: input.target }, async () => work()),
4470
+ selfUpdate: async () => {
4471
+ const outcome = await engine.runBinarySelfUpdate(engine.realSelfUpdateDeps(context), {})
4472
+ if (outcome.status !== 'error') return outcome
4473
+ const progressed =
4474
+ mapSelfUpdateFailureReason(outcome.message) === 'network' &&
4475
+ resumeFragmentBytes(realpathSync2(process.execPath), targetVersion) > 0
4476
+ return { ...outcome, progressed }
4477
+ },
4478
+ handover: async (input) => {
4479
+ const { handoverAutoUpdate: handoverAutoUpdate2 } = await Promise.resolve().then(
4480
+ () => (init_autoUpdateHandover(), autoUpdateHandover_exports),
4481
+ )
4482
+ const result = await handoverAutoUpdate2(
4483
+ { from: input.from, to: input.to, statusPath: input.statusPath },
4484
+ { context, execPath: realpathSync2(process.execPath) },
4485
+ )
4486
+ return { ok: result.ok, error: result.error }
4487
+ },
4488
+ statusPath: () => statusPath,
4489
+ readStatus: () => readAutoUpdateStatus(statusPath),
4490
+ writeStatus: (status) => writeAutoUpdateStatus(statusPath, status),
4491
+ preferencesPath: () => preferencesPath,
4492
+ now: () => Date.now(),
4493
+ // The worker has no stdout (stdio: 'ignore') — the status file is the
4494
+ // report channel.
4495
+ log: () => {},
4496
+ }
4497
+ await runAutoUpdate(deps, { targetVersion })
4498
+ }
4499
+ async function runUpdateReminderWorker(options) {
4500
+ let release
4501
+ let temporary
4502
+ let timer
4503
+ const controller = new AbortController()
4504
+ let owned = false
4505
+ let autoUpdateTarget = null
4506
+ try {
4507
+ const now = options.now ?? Date.now
4508
+ if (!isReminderVersion(options.installed)) return 0
4509
+ await asyncFs.mkdir(dirname6(options.cachePath), { recursive: true })
4510
+ release = await import_proper_lockfile2.default.lock(options.cachePath, {
4511
+ realpath: false,
4512
+ retries: 0,
4513
+ stale: REMINDER_LOCK_STALE_MS,
4514
+ update: 1e4,
4515
+ onCompromised: () => {
4516
+ owned = false
4517
+ controller.abort()
4518
+ },
4519
+ })
4520
+ owned = true
4521
+ const cache2 = readReminderCache(options.cachePath, options.identity, now())
4522
+ if (!shouldRefreshReminder(cache2, now())) return 0
4523
+ let latest = null
4524
+ try {
4525
+ const observation = await Promise.race([
4526
+ options.observe(controller.signal),
4527
+ new Promise((_, reject) => {
4528
+ timer = setTimeout(() => {
4529
+ controller.abort()
4530
+ reject(new Error('timeout'))
4531
+ }, 8e3)
4532
+ }),
2070
4533
  ])
2071
4534
  if (isReminderVersion(observation.latest)) latest = observation.latest
2072
4535
  } catch {}
2073
4536
  const checkedAt = now()
2074
4537
  const state = latest === null ? 'unknown' : compareVersions(options.installed, latest)
4538
+ if (state === 'behind' && latest !== null) autoUpdateTarget = latest
2075
4539
  const result = {
2076
4540
  schemaVersion: 1,
2077
4541
  identity: { ...options.identity },
@@ -2093,31 +4557,43 @@ async function runUpdateReminderWorker(options) {
2093
4557
  controller.abort()
2094
4558
  if (temporary) await asyncFs.unlink(temporary).catch(() => {})
2095
4559
  if (release) await release().catch(() => {})
4560
+ if (autoUpdateTarget) {
4561
+ try {
4562
+ await runAutomaticUpdate(options, autoUpdateTarget)
4563
+ } catch {}
4564
+ }
2096
4565
  }
2097
4566
  return 0
2098
4567
  }
2099
- var import_proper_lockfile
4568
+ var import_proper_lockfile2
2100
4569
  var init_updateReminderWorkerMain = __esm({
2101
4570
  'src/cli/updateReminderWorkerMain.ts'() {
2102
4571
  'use strict'
2103
- import_proper_lockfile = __toESM(require_proper_lockfile(), 1)
4572
+ import_proper_lockfile2 = __toESM(require_proper_lockfile(), 1)
4573
+ init_autoUpdate()
4574
+ init_autoUpdateStatus()
2104
4575
  init_updateReminderCache()
4576
+ init_updateReminderPreferences()
2105
4577
  init_version_check()
2106
4578
  },
2107
4579
  })
2108
4580
 
2109
4581
  // src/compile/updateReminderEntrypoint.ts
4582
+ import { createHash as createHash3 } from 'node:crypto'
2110
4583
  init_package()
2111
- import { createHash } from 'node:crypto'
2112
- import { closeSync, constants, fstatSync, openSync, readSync, statSync } from 'node:fs'
2113
- import { homedir } from 'node:os'
2114
- import { dirname as dirname2, isAbsolute, join, resolve } from 'node:path'
2115
- import { fileURLToPath } from 'node:url'
4584
+ init_autoUpdateStatus()
4585
+ init_updateReminderPreferences()
4586
+ import { homedir as homedir4 } from 'node:os'
4587
+ import { dirname as dirname7, isAbsolute, join as join9, resolve as resolve4 } from 'node:path'
4588
+ import { fileURLToPath as fileURLToPath2 } from 'node:url'
2116
4589
 
2117
4590
  // src/cli/updateReminderHookMain.ts
4591
+ init_autoUpdateNotice()
4592
+ init_autoUpdateStatus()
2118
4593
  init_updateReminderCache()
2119
4594
 
2120
4595
  // src/compile/updateReminderEntrypoint.ts
4596
+ init_stateRoot()
2121
4597
  var UPDATE_REMINDER_OPERATION = 'update-reminder'
2122
4598
  var UPDATE_REMINDER_WORKER_OPERATION = 'update-reminder-worker'
2123
4599
  var UPDATE_REMINDER_PREFERENCES_FILE = 'update-reminder-preferences.json'
@@ -2146,19 +4622,17 @@ function resolveUpdateReminderRuntime(options = {}) {
2146
4622
  host = value
2147
4623
  } else if (flag === '--state-root') {
2148
4624
  if (explicitStateRoot !== void 0 || !isAbsolute(value)) return null
2149
- explicitStateRoot = resolve(value)
4625
+ explicitStateRoot = resolve4(value)
2150
4626
  } else return null
2151
4627
  }
2152
- const nativeHome = resolve(
4628
+ const nativeHome = resolve4(
2153
4629
  (host === 'codex' ? process.env.CODEX_HOME?.trim() : process.env.CLAUDE_CONFIG_DIR) ||
2154
- join(homedir(), host === 'codex' ? '.codex' : '.claude'),
4630
+ join9(homedir4(), host === 'codex' ? '.codex' : '.claude'),
2155
4631
  )
2156
- const stateRoot =
2157
- explicitStateRoot ??
2158
- resolve(process.env.HARNESSED_ROOT_OVERRIDE || join(nativeHome, 'harnessed'))
4632
+ const stateRoot = explicitStateRoot ?? canonicalStateRoot(host)
2159
4633
  const channel = options.compiled ? 'binary' : process.versions.bun ? 'bun' : 'npm'
2160
4634
  const source = channel === 'binary' ? BINARY_SOURCE : `${channel}:harnessed`
2161
- const fingerprint = createHash('sha256')
4635
+ const fingerprint = createHash3('sha256')
2162
4636
  .update(
2163
4637
  JSON.stringify([
2164
4638
  host === 'codex' ? stateRoot : nativeHome,
@@ -2171,8 +4645,11 @@ function resolveUpdateReminderRuntime(options = {}) {
2171
4645
  return {
2172
4646
  stateRoot,
2173
4647
  nativeHome,
2174
- cachePath: join(stateRoot, `update-reminder-${host}.json`),
2175
- preferencesPath: join(stateRoot, UPDATE_REMINDER_PREFERENCES_FILE),
4648
+ cachePath: join9(stateRoot, `update-reminder-${host}.json`),
4649
+ preferencesPath: join9(stateRoot, UPDATE_REMINDER_PREFERENCES_FILE),
4650
+ // The auto-update status file of THIS host — the hook reads the pending
4651
+ // update notice from it, the worker writes the run state into it.
4652
+ statusPath: autoUpdateStatusPath(stateRoot),
2176
4653
  installed: package_default.version,
2177
4654
  identity: {
2178
4655
  host,
@@ -2186,7 +4663,10 @@ function resolveUpdateReminderRuntime(options = {}) {
2186
4663
  args: [
2187
4664
  options.compiled
2188
4665
  ? UPDATE_REMINDER_WORKER_OPERATION
2189
- : join(dirname2(fileURLToPath(import.meta.url)), 'harnessed-update-reminder-worker.mjs'),
4666
+ : join9(
4667
+ dirname7(fileURLToPath2(import.meta.url)),
4668
+ 'harnessed-update-reminder-worker.mjs',
4669
+ ),
2190
4670
  '--platform',
2191
4671
  host,
2192
4672
  ...(explicitStateRoot ? ['--state-root', explicitStateRoot] : []),
@@ -2194,38 +4674,22 @@ function resolveUpdateReminderRuntime(options = {}) {
2194
4674
  },
2195
4675
  }
2196
4676
  }
2197
- function reminderEnabled(path) {
2198
- let descriptor
2199
- try {
2200
- descriptor = openSync(path, constants.O_RDONLY | constants.O_NONBLOCK)
2201
- const info = fstatSync(descriptor)
2202
- if (!info.isFile() || info.size > 1024) return false
2203
- const buffer = Buffer.alloc(1025)
2204
- const bytes = readSync(descriptor, buffer, 0, buffer.length, 0)
2205
- if (bytes > 1024 || bytes < info.size) return false
2206
- const value = JSON.parse(buffer.toString('utf8', 0, bytes))
2207
- return (
2208
- typeof value === 'object' &&
2209
- value !== null &&
2210
- 'schemaVersion' in value &&
2211
- value.schemaVersion === 1 &&
2212
- 'enabled' in value &&
2213
- value.enabled === true
2214
- )
2215
- } catch (error) {
2216
- return error.code === 'ENOENT'
2217
- } finally {
2218
- if (descriptor !== void 0) {
2219
- try {
2220
- closeSync(descriptor)
2221
- } catch {}
2222
- }
2223
- }
4677
+ function readConsents(path) {
4678
+ const { preferences, missing, document } = readUpdateReminderPreferencesFile(path)
4679
+ if (preferences.unreadable) return { enabled: false, autoUpdate: false }
4680
+ if (missing) return { enabled: true, autoUpdate: false }
4681
+ const known = document?.schemaVersion === 1
4682
+ return { enabled: known && preferences.enabled, autoUpdate: known && preferences.autoUpdate }
4683
+ }
4684
+ function anyConsent(consents) {
4685
+ return consents.enabled || consents.autoUpdate
2224
4686
  }
2225
4687
  async function runUpdateReminderWorkerEntrypoint(options = {}) {
2226
4688
  try {
2227
4689
  const runtime = resolveUpdateReminderRuntime(options)
2228
- if (!runtime || !reminderEnabled(runtime.preferencesPath)) return 0
4690
+ if (!runtime) return 0
4691
+ const consents = readConsents(runtime.preferencesPath)
4692
+ if (!anyConsent(consents)) return 0
2229
4693
  const { runUpdateReminderWorker: runUpdateReminderWorker2 } = await Promise.resolve().then(
2230
4694
  () => (init_updateReminderWorkerMain(), updateReminderWorkerMain_exports),
2231
4695
  )