harnessed 5.0.12 → 5.0.14

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