runwork 0.14.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/dist/__tests__/install-scripts.test.js +33 -0
  2. package/dist/agents/__tests__/chatgpt-registry.test.d.ts +1 -0
  3. package/dist/agents/__tests__/chatgpt-registry.test.js +61 -0
  4. package/dist/agents/__tests__/detection.test.js +3 -0
  5. package/dist/agents/detection.js +3 -0
  6. package/dist/agents/intro-skill.js +5 -3
  7. package/dist/agents/registry-data.d.ts +59 -2
  8. package/dist/agents/registry-data.js +176 -0
  9. package/dist/commands/__tests__/clone-args.test.js +8 -1
  10. package/dist/commands/__tests__/clone-source-result.test.d.ts +1 -0
  11. package/dist/commands/__tests__/clone-source-result.test.js +45 -0
  12. package/dist/commands/clone.d.ts +33 -0
  13. package/dist/commands/clone.js +105 -10
  14. package/dist/commands/deploy.js +128 -11
  15. package/dist/commands/dev.js +72 -32
  16. package/dist/commands/doctor.js +64 -3
  17. package/dist/commands/info.d.ts +3 -0
  18. package/dist/commands/info.js +11 -0
  19. package/dist/commands/sync.js +14 -1
  20. package/dist/commands/validate.d.ts +2 -0
  21. package/dist/commands/validate.js +89 -0
  22. package/dist/deploy/__tests__/deploy-state.test.d.ts +1 -0
  23. package/dist/deploy/__tests__/deploy-state.test.js +80 -0
  24. package/dist/deploy/__tests__/deploy-status.test.d.ts +1 -0
  25. package/dist/deploy/__tests__/deploy-status.test.js +41 -0
  26. package/dist/deploy/__tests__/detach-args.test.d.ts +1 -0
  27. package/dist/deploy/__tests__/detach-args.test.js +30 -0
  28. package/dist/deploy/deploy-state.d.ts +36 -0
  29. package/dist/deploy/deploy-state.js +63 -0
  30. package/dist/deploy/deploy-status.d.ts +21 -0
  31. package/dist/deploy/deploy-status.js +36 -0
  32. package/dist/deploy/detach.d.ts +32 -0
  33. package/dist/deploy/detach.js +71 -0
  34. package/dist/dev/__tests__/session.test.js +39 -0
  35. package/dist/dev/__tests__/startup-sync.test.d.ts +1 -0
  36. package/dist/dev/__tests__/startup-sync.test.js +32 -0
  37. package/dist/dev/session.d.ts +9 -0
  38. package/dist/dev/session.js +4 -1
  39. package/dist/dev/startup-sync.d.ts +23 -0
  40. package/dist/dev/startup-sync.js +14 -0
  41. package/dist/generated/version.d.ts +1 -1
  42. package/dist/generated/version.js +1 -1
  43. package/dist/git/__tests__/classify-sync-error.test.d.ts +1 -0
  44. package/dist/git/__tests__/classify-sync-error.test.js +57 -0
  45. package/dist/git/__tests__/ensure-git-credential-helper.test.d.ts +1 -0
  46. package/dist/git/__tests__/ensure-git-credential-helper.test.js +133 -0
  47. package/dist/git/__tests__/ensure-runwork-remote.test.d.ts +1 -0
  48. package/dist/git/__tests__/ensure-runwork-remote.test.js +109 -0
  49. package/dist/git/__tests__/repo-config.test.d.ts +1 -0
  50. package/dist/git/__tests__/repo-config.test.js +26 -0
  51. package/dist/git/classify-sync-error.d.ts +21 -0
  52. package/dist/git/classify-sync-error.js +111 -0
  53. package/dist/git/credentials.d.ts +43 -0
  54. package/dist/git/credentials.js +67 -0
  55. package/dist/git/remote.d.ts +37 -0
  56. package/dist/git/remote.js +75 -0
  57. package/dist/git/repo-config.d.ts +8 -0
  58. package/dist/git/repo-config.js +29 -0
  59. package/dist/health/__tests__/checks.test.js +2 -2
  60. package/dist/health/__tests__/fix.test.d.ts +1 -0
  61. package/dist/health/__tests__/fix.test.js +72 -0
  62. package/dist/health/__tests__/runner-filter.test.d.ts +1 -0
  63. package/dist/health/__tests__/runner-filter.test.js +61 -0
  64. package/dist/health/checks.d.ts +7 -0
  65. package/dist/health/checks.js +50 -36
  66. package/dist/health/fix.d.ts +22 -0
  67. package/dist/health/fix.js +62 -0
  68. package/dist/health/runner.d.ts +7 -1
  69. package/dist/health/runner.js +40 -27
  70. package/dist/index.js +2 -0
  71. package/dist/tools/types.d.ts +5 -0
  72. package/dist/utils/__tests__/help-json.test.d.ts +1 -0
  73. package/dist/utils/__tests__/help-json.test.js +39 -0
  74. package/dist/utils/__tests__/ignore-matcher.test.js +18 -1
  75. package/dist/utils/help-json.d.ts +14 -0
  76. package/dist/utils/help-json.js +4 -1
  77. package/dist/validate/__tests__/validate.test.d.ts +1 -0
  78. package/dist/validate/__tests__/validate.test.js +42 -0
  79. package/dist/validate/freshness.d.ts +28 -0
  80. package/dist/validate/freshness.js +48 -0
  81. package/dist/validate/preview.d.ts +21 -0
  82. package/dist/validate/preview.js +39 -0
  83. package/package.json +1 -1
@@ -1,7 +1,9 @@
1
1
  import { Command } from 'commander';
2
2
  import { shouldOutputJson, jsonOut } from '../utils/output.js';
3
- import { bold, dim, green, yellow, cyan } from '../ui/colors.js';
4
- import { runAllChecks } from '../health/runner.js';
3
+ import { bold, dim, green, yellow, cyan, red } from '../ui/colors.js';
4
+ import { runAllChecks, ALL_CHECK_NAMES } from '../health/runner.js';
5
+ import { buildContext } from '../health/checks.js';
6
+ import { applyDoctorFixes } from '../health/fix.js';
5
7
  import { detectCurrentAgent } from '../agents/runtime-detection.js';
6
8
  /**
7
9
  * Env vars worth surfacing in --verbose for AI agents debugging their own
@@ -98,6 +100,7 @@ const CHECK_LABELS = {
98
100
  'project-config': 'Project config',
99
101
  'app-exists': 'App exists',
100
102
  'git-remote': 'Git remote',
103
+ 'deploy-freshness': 'Deploy freshness',
101
104
  'agent-setup': 'Agent setup',
102
105
  };
103
106
  function printHumanReport(report) {
@@ -147,12 +150,70 @@ function printHumanReport(report) {
147
150
  }
148
151
  console.log('');
149
152
  }
153
+ function printFixOutcomes(outcomes) {
154
+ console.log('');
155
+ console.log(bold('Applying fixes'));
156
+ if (outcomes.length === 0) {
157
+ console.log(` ${dim('Nothing to fix (no auto-remediable failures).')}`);
158
+ return;
159
+ }
160
+ for (const o of outcomes) {
161
+ const marker = o.applied ? green('[fixed]') : yellow('[skip]');
162
+ console.log(` ${marker} ${o.name}: ${dim(o.message)}`);
163
+ }
164
+ }
165
+ /** Parse and validate `--check a,b,c` against the known check names. */
166
+ function parseCheckNames(raw) {
167
+ const requested = raw.split(',').map(s => s.trim()).filter(Boolean);
168
+ const known = new Set(ALL_CHECK_NAMES);
169
+ const only = requested.filter(n => known.has(n));
170
+ const unknown = requested.filter(n => !known.has(n));
171
+ return { only, unknown };
172
+ }
150
173
  export const doctorCommand = new Command('doctor')
151
174
  .description('Check system health: auth, network, project config, agent setup')
152
175
  .option('-v, --verbose', 'Include host-agent detection results, runtime info, and allowlisted env vars (useful for AI agents debugging their own environment)')
176
+ .option('--check <names>', `Run only the named checks (comma-separated). Available: ${ALL_CHECK_NAMES.join(', ')}`)
177
+ .option('--fix', 'Auto-remediate fixable failures (git credential helper, runwork remote), then re-check')
153
178
  .action(async (opts, command) => {
154
179
  const asJson = shouldOutputJson(command.optsWithGlobals().json);
155
- const report = await runAllChecks();
180
+ // Resolve `--check` scope (if any) up front so both fix and report honor it.
181
+ let only;
182
+ if (opts.check) {
183
+ const parsed = parseCheckNames(opts.check);
184
+ if (parsed.unknown.length > 0) {
185
+ const msg = `Unknown check(s): ${parsed.unknown.join(', ')}. Available: ${ALL_CHECK_NAMES.join(', ')}`;
186
+ if (asJson) {
187
+ jsonOut({ success: false, command: 'doctor', error: msg });
188
+ }
189
+ else {
190
+ console.error(red(msg));
191
+ }
192
+ process.exit(1);
193
+ }
194
+ only = parsed.only;
195
+ }
196
+ // --- Fix flow: report, remediate fixable failures, re-check ---
197
+ if (opts.fix) {
198
+ const before = await runAllChecks({ only });
199
+ const failingNames = before.checks.filter(c => c.status === 'fail').map(c => c.name);
200
+ const ctx = buildContext();
201
+ const outcomes = await applyDoctorFixes(ctx, failingNames);
202
+ const after = await runAllChecks({ only });
203
+ if (asJson) {
204
+ jsonOut({ success: after.status !== 'fail', command: 'doctor', fixes: outcomes, report: after });
205
+ }
206
+ else {
207
+ printFixOutcomes(outcomes);
208
+ printHumanReport(after);
209
+ }
210
+ if (after.checks.some(c => c.status === 'fail')) {
211
+ process.exit(1);
212
+ }
213
+ return;
214
+ }
215
+ // --- Normal (optionally scoped) report ---
216
+ const report = await runAllChecks({ only });
156
217
  const verboseInfo = opts.verbose ? collectVerboseInfo() : null;
157
218
  if (asJson) {
158
219
  jsonOut(verboseInfo ? { ...report, verbose: verboseInfo } : report);
@@ -1,5 +1,6 @@
1
1
  import { Command } from 'commander';
2
2
  import { type SessionMode, type SessionStaleReason } from '../dev/session.js';
3
+ import { type DeploySummary } from '../deploy/deploy-state.js';
3
4
  import type { WorkspaceAllData } from '../types.js';
4
5
  interface BlueprintEntity {
5
6
  entityName: string;
@@ -124,6 +125,8 @@ interface InfoOutput {
124
125
  url: string | null;
125
126
  deployed: boolean;
126
127
  };
128
+ /** Last deploy from this machine vs the current local HEAD (friction log #8). */
129
+ deploy: DeploySummary;
127
130
  integrations: Array<{
128
131
  id: string;
129
132
  status: string;
@@ -10,6 +10,7 @@ import { requireAuth } from '../auth/store.js';
10
10
  import { ApiClient } from '../api/client.js';
11
11
  import { resolveWorkspace } from '../workspace/resolve.js';
12
12
  import { getSessionState } from '../dev/session.js';
13
+ import { getDeploySummary } from '../deploy/deploy-state.js';
13
14
  function readLocalDevSession(appDir, appId) {
14
15
  if (!appId)
15
16
  return { state: 'none' };
@@ -245,6 +246,15 @@ function printHumanOutput(data) {
245
246
  else {
246
247
  console.log(` ${dim(pad('Production:'))}${dim('(not deployed)')}`);
247
248
  }
249
+ if (data.deploy.deployedShortSha) {
250
+ const localPart = data.deploy.localShortSha ? `, local ${data.deploy.localShortSha}` : '';
251
+ const sync = data.deploy.inSync === true
252
+ ? green('in sync')
253
+ : data.deploy.inSync === false
254
+ ? yellow('local has undeployed commits')
255
+ : dim('unknown');
256
+ console.log(` ${dim(pad('Last deploy:'))}${data.deploy.deployedShortSha}${dim(localPart)} ${sync}`);
257
+ }
248
258
  // Local dev session view: what's running on THIS machine, from the
249
259
  // session file. This may disagree with the server's "preview"
250
260
  // status above; that's diagnostic, not a bug.
@@ -428,6 +438,7 @@ export const infoCommand = new Command('info')
428
438
  preview,
429
439
  localDevSession,
430
440
  production: appInfo?.production ?? { url: null, deployed: false },
441
+ deploy: getDeploySummary(process.cwd()),
431
442
  integrations,
432
443
  registries,
433
444
  cli: {
@@ -16,7 +16,7 @@ import { buildShareConversationSkill, buildSaveConversationSkill, BUILT_IN_SKILL
16
16
  import { computeSyncPlan } from '../sync/change-detect.js';
17
17
  import { printSyncSummary, resolveConflict, resolveConflictNonInteractive } from '../sync/conflict-ui.js';
18
18
  import { executeSyncPlan } from '../sync/executor.js';
19
- import { getRegistryAgent, resolveToAbsolute } from '../agents/registry.js';
19
+ import { getRegistryAgent, resolveToAbsolute, isConnectOnlyAgent } from '../agents/registry.js';
20
20
  function loadSetupState(filePath) {
21
21
  if (!existsSync(filePath))
22
22
  return null;
@@ -340,6 +340,13 @@ export async function syncFromState(state, statePath, credentials, opts) {
340
340
  hookInstallCalls: 0,
341
341
  };
342
342
  for (const adapter of adapters) {
343
+ // Connect-only agents (e.g. ChatGPT) have no local files to write; the
344
+ // connector lives in the user's account. Skip all local-write phases.
345
+ if (isConnectOnlyAgent(getRegistryAgent(adapter.slug))) {
346
+ console.log(` [${adapter.name}] Connect-only agent: no local files to sync`);
347
+ summary.adaptersProcessed++;
348
+ continue;
349
+ }
343
350
  let adapterFailedAnyScope = false;
344
351
  for (const scope of scopes) {
345
352
  try {
@@ -433,6 +440,8 @@ export async function syncFromState(state, statePath, credentials, opts) {
433
440
  }
434
441
  // Write team instructions and/or per-agent extra instructions.
435
442
  for (const adapter of adapters) {
443
+ if (isConnectOnlyAgent(getRegistryAgent(adapter.slug)))
444
+ continue;
436
445
  if (!adapter.writeTeamInstructions)
437
446
  continue;
438
447
  const agentExtra = agentConfigs?.[adapter.slug]?.extraInstructions;
@@ -455,6 +464,8 @@ export async function syncFromState(state, statePath, credentials, opts) {
455
464
  // User scope is handled below in the unified defaults+network+minimum block.
456
465
  if (agentConfigs) {
457
466
  for (const adapter of adapters) {
467
+ if (isConnectOnlyAgent(getRegistryAgent(adapter.slug)))
468
+ continue;
458
469
  const agentConfig = agentConfigs[adapter.slug];
459
470
  if (!agentConfig || !adapter.writeAgentConfig)
460
471
  continue;
@@ -507,6 +518,8 @@ export async function syncFromState(state, statePath, credentials, opts) {
507
518
  if (!state.agentDefaults)
508
519
  state.agentDefaults = {};
509
520
  for (const adapter of adapters) {
521
+ if (isConnectOnlyAgent(getRegistryAgent(adapter.slug)))
522
+ continue;
510
523
  if (!adapter.writeAgentConfig)
511
524
  continue;
512
525
  const slug = adapter.slug;
@@ -0,0 +1,2 @@
1
+ import { Command } from 'commander';
2
+ export declare const validateCommand: Command;
@@ -0,0 +1,89 @@
1
+ import { Command } from 'commander';
2
+ import { readFileSync, existsSync } from 'fs';
3
+ import { requireAuth } from '../auth/store.js';
4
+ import { ApiClient } from '../api/client.js';
5
+ import { shouldOutputJson, jsonOut } from '../utils/output.js';
6
+ import { bold, dim, green, yellow, red } from '../ui/colors.js';
7
+ import { requireGit } from '../git/preflight.js';
8
+ import { getGitFreshness } from '../validate/freshness.js';
9
+ import { checkPreview } from '../validate/preview.js';
10
+ const BUILD_FOLLOWUP = 'In-sandbox typecheck/lint requires a worker exec endpoint (not yet available). The preview error-overlay check is used as a build proxy.';
11
+ export const validateCommand = new Command('validate')
12
+ .description('Validate the app before deploy: git sync state + preview liveness (no local deps needed)')
13
+ .action(async (_opts, command) => {
14
+ const useJson = shouldOutputJson(command.optsWithGlobals().json);
15
+ const cwd = process.cwd();
16
+ if (!existsSync('.runwork.json')) {
17
+ if (useJson) {
18
+ jsonOut({ success: false, command: 'validate', error: 'No .runwork.json found. Run inside a Runwork app.' });
19
+ process.exit(1);
20
+ }
21
+ console.error('No .runwork.json found. Run `runwork validate` inside a Runwork app.');
22
+ process.exit(1);
23
+ }
24
+ requireGit('validate');
25
+ const config = JSON.parse(readFileSync('.runwork.json', 'utf-8'));
26
+ const creds = requireAuth();
27
+ const client = new ApiClient(creds);
28
+ const sync = getGitFreshness(cwd);
29
+ // Best-effort: ask the server for the current preview URL. No running
30
+ // preview is not a failure -- the preview check is simply skipped.
31
+ let previewUrl = null;
32
+ try {
33
+ const status = await client.getDevStatus(config.appId);
34
+ previewUrl = status.previewUrl || null;
35
+ }
36
+ catch {
37
+ /* no active session -- preview check skipped */
38
+ }
39
+ const preview = await checkPreview(previewUrl);
40
+ // Overall: fail only on a concrete problem -- the preview is down or
41
+ // serving a broken build. Local commits not yet deployed are informational.
42
+ const ok = preview.url === null ? true : preview.responds && !preview.errorDetected;
43
+ const result = { sync, preview, build: { checked: false, reason: BUILD_FOLLOWUP }, ok };
44
+ if (useJson) {
45
+ jsonOut({ success: ok, command: 'validate', result });
46
+ if (!ok)
47
+ process.exit(1);
48
+ return;
49
+ }
50
+ console.log('');
51
+ console.log(bold('runwork validate'));
52
+ console.log('');
53
+ // Sync
54
+ if (sync.inSync) {
55
+ console.log(` ${green('[ok]')} Sync ${dim('local matches the deploy remote, working tree clean')}`);
56
+ }
57
+ else {
58
+ const bits = [];
59
+ if (sync.uncommitted)
60
+ bits.push('uncommitted changes');
61
+ if (sync.ahead > 0)
62
+ bits.push(`${sync.ahead} commit(s) not yet pushed/deployed`);
63
+ if (sync.behind > 0)
64
+ bits.push(`${sync.behind} commit(s) behind the remote`);
65
+ if (!sync.remoteSha)
66
+ bits.push('no runwork/main ref (push or run dev first)');
67
+ console.log(` ${yellow('[info]')} Sync ${dim(bits.join('; ') || 'not in sync')}`);
68
+ }
69
+ // Preview
70
+ if (!preview.url) {
71
+ console.log(` ${dim('[skip]')} Preview ${dim('no preview running (start `runwork dev`)')}`);
72
+ }
73
+ else if (!preview.responds) {
74
+ console.log(` ${red('[FAIL]')} Preview ${dim(`not responding${preview.error ? `: ${preview.error}` : ` (status ${preview.status})`}`)}`);
75
+ }
76
+ else if (preview.errorDetected) {
77
+ console.log(` ${red('[FAIL]')} Preview ${dim('serving a build error overlay -- the app does not compile')}`);
78
+ }
79
+ else {
80
+ console.log(` ${green('[ok]')} Preview ${dim(`live and serving a working build (status ${preview.status})`)}`);
81
+ }
82
+ // Build (proxy)
83
+ console.log(` ${dim('[note]')} Build ${dim(BUILD_FOLLOWUP)}`);
84
+ console.log('');
85
+ console.log(ok ? green(' validate: ok') : red(' validate: FAILED'));
86
+ console.log('');
87
+ if (!ok)
88
+ process.exit(1);
89
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,80 @@
1
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
2
+ vi.mock('child_process');
3
+ vi.mock('fs', () => ({
4
+ existsSync: vi.fn(),
5
+ mkdirSync: vi.fn(),
6
+ readFileSync: vi.fn(),
7
+ writeFileSync: vi.fn(),
8
+ }));
9
+ const mockExecFileSync = (await import('child_process')).execFileSync;
10
+ const fs = await import('fs');
11
+ const { summarizeDeploy, getHeadSha, writeDeployState, readDeployState, } = await import('../deploy-state.js');
12
+ const SHA = 'a1b2c3d4e5f600000000000000000000deadbeef';
13
+ describe('deploy/deploy-state', () => {
14
+ beforeEach(() => {
15
+ vi.clearAllMocks();
16
+ });
17
+ describe('summarizeDeploy()', () => {
18
+ it('reports in-sync when local HEAD matches the deployed SHA', () => {
19
+ const s = summarizeDeploy(SHA, { sha: SHA, deployedAt: '2026-06-05T00:00:00Z', url: 'https://app' });
20
+ expect(s.inSync).toBe(true);
21
+ expect(s.deployedShortSha).toBe('a1b2c3d');
22
+ expect(s.localShortSha).toBe('a1b2c3d');
23
+ expect(s.deployedAt).toBe('2026-06-05T00:00:00Z');
24
+ expect(s.url).toBe('https://app');
25
+ });
26
+ it('reports out-of-sync when local HEAD has moved past the deploy', () => {
27
+ const s = summarizeDeploy('ffffffffffffffffffffffffffffffffffffffff', {
28
+ sha: SHA, deployedAt: '2026-06-05T00:00:00Z', url: 'https://app',
29
+ });
30
+ expect(s.inSync).toBe(false);
31
+ expect(s.deployedShortSha).toBe('a1b2c3d');
32
+ expect(s.localShortSha).toBe('fffffff');
33
+ });
34
+ it('returns inSync=null when there is no recorded deploy', () => {
35
+ const s = summarizeDeploy(SHA, null);
36
+ expect(s.inSync).toBeNull();
37
+ expect(s.deployedSha).toBeNull();
38
+ expect(s.localShortSha).toBe('a1b2c3d');
39
+ });
40
+ it('returns inSync=null when local HEAD is unknown (not a repo)', () => {
41
+ const s = summarizeDeploy(null, { sha: SHA, deployedAt: 't', url: '' });
42
+ expect(s.inSync).toBeNull();
43
+ expect(s.localSha).toBeNull();
44
+ });
45
+ });
46
+ describe('getHeadSha()', () => {
47
+ it('returns the trimmed HEAD sha', () => {
48
+ mockExecFileSync.mockReturnValue(Buffer.from(SHA + '\n'));
49
+ expect(getHeadSha('/repo')).toBe(SHA);
50
+ });
51
+ it('returns null when git fails (no commits / not a repo)', () => {
52
+ mockExecFileSync.mockImplementation(() => { throw new Error('no HEAD'); });
53
+ expect(getHeadSha('/repo')).toBeNull();
54
+ });
55
+ });
56
+ describe('writeDeployState() / readDeployState()', () => {
57
+ it('writes JSON, creating .runwork when missing', () => {
58
+ vi.mocked(fs.existsSync).mockReturnValue(false);
59
+ writeDeployState('/repo', { sha: SHA, deployedAt: 't', url: 'https://app' });
60
+ expect(fs.mkdirSync).toHaveBeenCalled();
61
+ expect(fs.writeFileSync).toHaveBeenCalledOnce();
62
+ const written = vi.mocked(fs.writeFileSync).mock.calls[0][1];
63
+ expect(JSON.parse(written)).toEqual({ sha: SHA, deployedAt: 't', url: 'https://app' });
64
+ });
65
+ it('reads back a valid state', () => {
66
+ vi.mocked(fs.existsSync).mockReturnValue(true);
67
+ vi.mocked(fs.readFileSync).mockReturnValue(JSON.stringify({ sha: SHA, deployedAt: 't', url: 'https://app' }));
68
+ expect(readDeployState('/repo')).toEqual({ sha: SHA, deployedAt: 't', url: 'https://app' });
69
+ });
70
+ it('returns null when the file is missing', () => {
71
+ vi.mocked(fs.existsSync).mockReturnValue(false);
72
+ expect(readDeployState('/repo')).toBeNull();
73
+ });
74
+ it('returns null when the file is malformed', () => {
75
+ vi.mocked(fs.existsSync).mockReturnValue(true);
76
+ vi.mocked(fs.readFileSync).mockReturnValue('{ not json');
77
+ expect(readDeployState('/repo')).toBeNull();
78
+ });
79
+ });
80
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,41 @@
1
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
2
+ vi.mock('fs', () => ({
3
+ existsSync: vi.fn(),
4
+ mkdirSync: vi.fn(),
5
+ readFileSync: vi.fn(),
6
+ writeFileSync: vi.fn(),
7
+ }));
8
+ const fs = await import('fs');
9
+ const { writeDeployStatus, readDeployStatus, deployLogPath } = await import('../deploy-status.js');
10
+ describe('deploy/deploy-status', () => {
11
+ beforeEach(() => vi.clearAllMocks());
12
+ it('writes status JSON, creating .runwork when missing', () => {
13
+ vi.mocked(fs.existsSync).mockReturnValue(false);
14
+ writeDeployStatus('/repo', { state: 'in-progress', startedAt: '2026-06-05T00:00:00Z', pid: 123 });
15
+ expect(fs.mkdirSync).toHaveBeenCalled();
16
+ const written = vi.mocked(fs.writeFileSync).mock.calls[0][1];
17
+ expect(JSON.parse(written)).toEqual({ state: 'in-progress', startedAt: '2026-06-05T00:00:00Z', pid: 123 });
18
+ });
19
+ it('reads back a valid status', () => {
20
+ vi.mocked(fs.existsSync).mockReturnValue(true);
21
+ vi.mocked(fs.readFileSync).mockReturnValue(JSON.stringify({ state: 'succeeded', startedAt: 't', finishedAt: 'u', url: 'https://app', sha: 'abc' }));
22
+ expect(readDeployStatus('/repo')).toMatchObject({ state: 'succeeded', url: 'https://app', sha: 'abc' });
23
+ });
24
+ it('returns null when the file is missing', () => {
25
+ vi.mocked(fs.existsSync).mockReturnValue(false);
26
+ expect(readDeployStatus('/repo')).toBeNull();
27
+ });
28
+ it('rejects a malformed state', () => {
29
+ vi.mocked(fs.existsSync).mockReturnValue(true);
30
+ vi.mocked(fs.readFileSync).mockReturnValue(JSON.stringify({ state: 'weird', startedAt: 't' }));
31
+ expect(readDeployStatus('/repo')).toBeNull();
32
+ });
33
+ it('rejects invalid JSON', () => {
34
+ vi.mocked(fs.existsSync).mockReturnValue(true);
35
+ vi.mocked(fs.readFileSync).mockReturnValue('{ not json');
36
+ expect(readDeployStatus('/repo')).toBeNull();
37
+ });
38
+ it('deployLogPath points at .runwork/deploy-stdout.log', () => {
39
+ expect(deployLogPath('/repo')).toContain('deploy-stdout.log');
40
+ });
41
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,30 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { buildDeployChildArgs, isInternalDeployChild, DEPLOY_DETACHED_CHILD_FLAG, } from '../detach.js';
3
+ describe('deploy/detach arg handling', () => {
4
+ describe('buildDeployChildArgs()', () => {
5
+ it('drops --detach and appends exactly one child marker', () => {
6
+ const out = buildDeployChildArgs(['node', '/p/runwork', 'deploy', '--detach']);
7
+ expect(out).toEqual(['/p/runwork', 'deploy', DEPLOY_DETACHED_CHILD_FLAG]);
8
+ });
9
+ it('preserves other flags like --json', () => {
10
+ const out = buildDeployChildArgs(['node', '/p/runwork', 'deploy', '--detach', '--json']);
11
+ expect(out).toEqual(['/p/runwork', 'deploy', '--json', DEPLOY_DETACHED_CHILD_FLAG]);
12
+ });
13
+ it('does not duplicate the marker when already present', () => {
14
+ const out = buildDeployChildArgs(['node', '/p/runwork', 'deploy', DEPLOY_DETACHED_CHILD_FLAG]);
15
+ expect(out.filter(a => a === DEPLOY_DETACHED_CHILD_FLAG)).toHaveLength(1);
16
+ });
17
+ it('skips a Bun-on-Windows virtual-FS argv[1]', () => {
18
+ const out = buildDeployChildArgs(['runwork.exe', 'B:/~BUN/root/runwork-windows-x64.exe', 'deploy', '--detach']);
19
+ expect(out).toEqual(['deploy', DEPLOY_DETACHED_CHILD_FLAG]);
20
+ });
21
+ });
22
+ describe('isInternalDeployChild()', () => {
23
+ it('detects the marker', () => {
24
+ expect(isInternalDeployChild(['node', 'runwork', 'deploy', DEPLOY_DETACHED_CHILD_FLAG])).toBe(true);
25
+ });
26
+ it('is false without the marker', () => {
27
+ expect(isInternalDeployChild(['node', 'runwork', 'deploy'])).toBe(false);
28
+ });
29
+ });
30
+ });
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Record of the last deploy triggered from this machine, persisted to
3
+ * `.runwork/last-deploy.json`. `sha` is the commit that was pushed and
4
+ * deployed (local HEAD at deploy time), so comparing it to the current HEAD
5
+ * cheaply answers "is what I have locally what's deployed?" without scraping
6
+ * the production bundle (friction log #8).
7
+ *
8
+ * NOTE: this reflects deploys from THIS machine. A teammate deploying
9
+ * elsewhere won't update this file -- an authoritative production-build SHA
10
+ * would require the deploy API to return it (tracked as a follow-up).
11
+ */
12
+ export interface DeployState {
13
+ sha: string;
14
+ deployedAt: string;
15
+ url: string;
16
+ }
17
+ export interface DeploySummary {
18
+ deployedSha: string | null;
19
+ deployedShortSha: string | null;
20
+ deployedAt: string | null;
21
+ url: string | null;
22
+ localSha: string | null;
23
+ localShortSha: string | null;
24
+ /** true/false when both SHAs are known; null when undeterminable. */
25
+ inSync: boolean | null;
26
+ }
27
+ /** Current git HEAD commit SHA, or null if not a repo / no commits. */
28
+ export declare function getHeadSha(cwd: string): string | null;
29
+ /** Persist the deploy state for `cwd`. Creates `.runwork/` if needed. */
30
+ export declare function writeDeployState(cwd: string, state: DeployState): void;
31
+ /** Read the recorded deploy state for `cwd`, or null if none/unreadable. */
32
+ export declare function readDeployState(cwd: string): DeployState | null;
33
+ /** Compare the local HEAD against a recorded deploy. Pure (no IO). */
34
+ export declare function summarizeDeploy(localSha: string | null, state: DeployState | null): DeploySummary;
35
+ /** Convenience: read git HEAD + recorded deploy and summarize the comparison. */
36
+ export declare function getDeploySummary(cwd: string): DeploySummary;
@@ -0,0 +1,63 @@
1
+ import { execFileSync } from '../utils/subprocess.js';
2
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs';
3
+ import { dirname, join } from 'path';
4
+ function deployStatePath(cwd) {
5
+ return join(cwd, '.runwork', 'last-deploy.json');
6
+ }
7
+ /** Current git HEAD commit SHA, or null if not a repo / no commits. */
8
+ export function getHeadSha(cwd) {
9
+ try {
10
+ return execFileSync('git', ['rev-parse', 'HEAD'], { cwd, stdio: ['ignore', 'pipe', 'ignore'] })
11
+ .toString()
12
+ .trim() || null;
13
+ }
14
+ catch {
15
+ return null;
16
+ }
17
+ }
18
+ /** Persist the deploy state for `cwd`. Creates `.runwork/` if needed. */
19
+ export function writeDeployState(cwd, state) {
20
+ const path = deployStatePath(cwd);
21
+ try {
22
+ if (!existsSync(dirname(path)))
23
+ mkdirSync(dirname(path), { recursive: true });
24
+ writeFileSync(path, JSON.stringify(state, null, 2));
25
+ }
26
+ catch {
27
+ // Best-effort: a failure to record state must never fail a deploy.
28
+ }
29
+ }
30
+ /** Read the recorded deploy state for `cwd`, or null if none/unreadable. */
31
+ export function readDeployState(cwd) {
32
+ const path = deployStatePath(cwd);
33
+ if (!existsSync(path))
34
+ return null;
35
+ try {
36
+ const parsed = JSON.parse(readFileSync(path, 'utf-8'));
37
+ if (typeof parsed.sha === 'string' && typeof parsed.deployedAt === 'string') {
38
+ return { sha: parsed.sha, deployedAt: parsed.deployedAt, url: parsed.url ?? '' };
39
+ }
40
+ return null;
41
+ }
42
+ catch {
43
+ return null;
44
+ }
45
+ }
46
+ /** Compare the local HEAD against a recorded deploy. Pure (no IO). */
47
+ export function summarizeDeploy(localSha, state) {
48
+ const deployedSha = state?.sha ?? null;
49
+ const inSync = deployedSha && localSha ? deployedSha === localSha : null;
50
+ return {
51
+ deployedSha,
52
+ deployedShortSha: deployedSha ? deployedSha.slice(0, 7) : null,
53
+ deployedAt: state?.deployedAt ?? null,
54
+ url: state?.url ?? null,
55
+ localSha,
56
+ localShortSha: localSha ? localSha.slice(0, 7) : null,
57
+ inSync,
58
+ };
59
+ }
60
+ /** Convenience: read git HEAD + recorded deploy and summarize the comparison. */
61
+ export function getDeploySummary(cwd) {
62
+ return summarizeDeploy(getHeadSha(cwd), readDeployState(cwd));
63
+ }
@@ -0,0 +1,21 @@
1
+ /** Lifecycle state of a (possibly detached) deploy run. */
2
+ export type DeployRunState = 'in-progress' | 'succeeded' | 'failed';
3
+ /**
4
+ * Status of the most recent deploy started from this machine, persisted to
5
+ * `.runwork/deploy-status.json`. Lets `runwork deploy --status` report
6
+ * progress/outcome of a `--detach`ed deploy that outlived the shell that
7
+ * launched it (friction log #7).
8
+ */
9
+ export interface DeployStatus {
10
+ state: DeployRunState;
11
+ startedAt: string;
12
+ finishedAt?: string;
13
+ url?: string;
14
+ sha?: string;
15
+ error?: string;
16
+ pid?: number;
17
+ }
18
+ /** Path of the detached deploy's stdout log (mirrors dev's log convention). */
19
+ export declare function deployLogPath(cwd: string): string;
20
+ export declare function writeDeployStatus(cwd: string, status: DeployStatus): void;
21
+ export declare function readDeployStatus(cwd: string): DeployStatus | null;
@@ -0,0 +1,36 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs';
2
+ import { dirname, join } from 'path';
3
+ function statusPath(cwd) {
4
+ return join(cwd, '.runwork', 'deploy-status.json');
5
+ }
6
+ /** Path of the detached deploy's stdout log (mirrors dev's log convention). */
7
+ export function deployLogPath(cwd) {
8
+ return join(cwd, '.runwork', 'deploy-stdout.log');
9
+ }
10
+ export function writeDeployStatus(cwd, status) {
11
+ const path = statusPath(cwd);
12
+ try {
13
+ if (!existsSync(dirname(path)))
14
+ mkdirSync(dirname(path), { recursive: true });
15
+ writeFileSync(path, JSON.stringify(status, null, 2));
16
+ }
17
+ catch {
18
+ // Best-effort: status recording must never fail a deploy.
19
+ }
20
+ }
21
+ export function readDeployStatus(cwd) {
22
+ const path = statusPath(cwd);
23
+ if (!existsSync(path))
24
+ return null;
25
+ try {
26
+ const parsed = JSON.parse(readFileSync(path, 'utf-8'));
27
+ if ((parsed.state === 'in-progress' || parsed.state === 'succeeded' || parsed.state === 'failed') &&
28
+ typeof parsed.startedAt === 'string') {
29
+ return parsed;
30
+ }
31
+ return null;
32
+ }
33
+ catch {
34
+ return null;
35
+ }
36
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * `runwork deploy --detach` orchestration.
3
+ *
4
+ * Unlike `runwork dev --detach`, a deploy has no "ready" rendezvous to wait
5
+ * for -- it's fire-and-forget-then-poll. So the parent simply spawns a
6
+ * detached child (whose stdout/stderr go to `.runwork/deploy-*.log`), records
7
+ * an `in-progress` status, prints a poll hint, and exits. The child runs the
8
+ * real deploy and finalizes the status file to `succeeded`/`failed`.
9
+ *
10
+ * This exists so agents whose shell tool times out (~45s) can launch a deploy
11
+ * that survives, then poll `runwork deploy --status` (friction log #7).
12
+ */
13
+ /** Hidden marker passed to the spawned child. Not shown in --help. */
14
+ export declare const DEPLOY_DETACHED_CHILD_FLAG = "--internal-detached-deploy-child";
15
+ /** Whether this invocation is the detached deploy child. */
16
+ export declare function isInternalDeployChild(argv?: readonly string[]): boolean;
17
+ /**
18
+ * Build the args for the spawned child so it re-runs the same deploy in the
19
+ * foreground (the child must NOT re-detach). Drops `--detach`, any stale
20
+ * marker, and a Bun-on-Windows virtual-FS path; re-adds exactly one marker.
21
+ * Pure for testability.
22
+ */
23
+ export declare function buildDeployChildArgs(parentArgv: readonly string[]): string[];
24
+ export interface SpawnedDeployHandle {
25
+ pid: number;
26
+ }
27
+ /**
28
+ * Spawn the detached deploy child with stdout/stderr routed to
29
+ * `.runwork/deploy-{stdout,stderr}.log`. Cross-platform: uses
30
+ * `process.execPath` so it never depends on PATH (Bun-standalone-safe).
31
+ */
32
+ export declare function spawnDetachedDeploy(childArgs: string[], cwd: string): SpawnedDeployHandle;