@hyperdrive.bot/gut 0.1.14 → 0.1.15-alpha.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.
@@ -0,0 +1,6 @@
1
+ import { BaseCommand } from '../../base-command.js';
2
+ export default class WorktreePrune extends BaseCommand {
3
+ static description: string;
4
+ static examples: string[];
5
+ run(): Promise<void>;
6
+ }
@@ -0,0 +1,28 @@
1
+ import chalk from 'chalk';
2
+ import fs from 'node:fs';
3
+ import { BaseCommand } from '../../base-command.js';
4
+ export default class WorktreePrune extends BaseCommand {
5
+ static description = 'Remove worktree records whose paths no longer exist on disk';
6
+ static examples = ['<%= config.bin %> worktree prune'];
7
+ async run() {
8
+ const state = this.worktreeService.loadState();
9
+ const stale = [];
10
+ const kept = [];
11
+ for (const w of state.worktrees) {
12
+ if (fs.existsSync(w.path))
13
+ kept.push(w);
14
+ else
15
+ stale.push(w);
16
+ }
17
+ if (stale.length === 0) {
18
+ this.log(chalk.dim('No stale worktree records found'));
19
+ return;
20
+ }
21
+ for (const record of stale) {
22
+ this.log(` ${chalk.yellow('✗')} ${record.name} ${chalk.dim('→')} ${record.path}`);
23
+ }
24
+ this.worktreeService.saveState({ worktrees: kept });
25
+ await this.gitService.worktreePrune(this.configService.getWorkspaceRoot());
26
+ this.log(chalk.green(`✓ Pruned ${stale.length} stale worktree record(s)`));
27
+ }
28
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,105 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import fs from 'node:fs';
3
+ vi.mock('node:fs', () => ({
4
+ default: {
5
+ existsSync: vi.fn(() => true),
6
+ },
7
+ existsSync: vi.fn(() => true),
8
+ }));
9
+ vi.mock('chalk', () => ({
10
+ default: {
11
+ bold: (s) => s,
12
+ cyan: (s) => s,
13
+ dim: (s) => s,
14
+ green: (s) => s,
15
+ yellow: (s) => s,
16
+ },
17
+ }));
18
+ function makeRecord(overrides = {}) {
19
+ return {
20
+ baseBranch: 'master',
21
+ createdAt: new Date('2026-03-19T13:22:00Z').getTime(),
22
+ entities: [
23
+ { branch: 'workflow/deploy-batch', entityName: 'api', entityPath: 'packages/serverless/api', worktreePath: '/tmp/gut-worktrees/workflow-deploy-batch/packages/serverless/api' },
24
+ ],
25
+ name: 'workflow/deploy-batch',
26
+ path: '/tmp/gut-worktrees/workflow-deploy-batch',
27
+ ...overrides,
28
+ };
29
+ }
30
+ async function makeCmd(state) {
31
+ const logs = [];
32
+ const { default: WorktreePrune } = await import('./prune.js');
33
+ const cmd = Object.create(WorktreePrune.prototype);
34
+ cmd.log = (msg = '') => { logs.push(msg); };
35
+ const stubs = {
36
+ configService: { getWorkspaceRoot: vi.fn(() => '/fake/workspace') },
37
+ gitService: { worktreePrune: vi.fn(async () => { }) },
38
+ worktreeService: {
39
+ loadState: vi.fn(() => state),
40
+ saveState: vi.fn(),
41
+ },
42
+ };
43
+ cmd.configService = stubs.configService;
44
+ cmd.gitService = stubs.gitService;
45
+ cmd.worktreeService = stubs.worktreeService;
46
+ return { cmd, logs, stubs };
47
+ }
48
+ describe('WorktreePrune', () => {
49
+ it('mixed stale+healthy: removes only stale, logs, calls saveState(kept) and worktreePrune once', async () => {
50
+ const healthy = makeRecord({ name: 'workflow/alive', path: '/tmp/alive' });
51
+ const stale = makeRecord({ name: 'workflow/dead', path: '/tmp/dead' });
52
+ vi.mocked(fs.existsSync).mockImplementation((p) => p === '/tmp/alive');
53
+ const { cmd, logs, stubs } = await makeCmd({ worktrees: [healthy, stale] });
54
+ await cmd.run();
55
+ expect(stubs.worktreeService.saveState).toHaveBeenCalledTimes(1);
56
+ expect(stubs.worktreeService.saveState).toHaveBeenCalledWith({ worktrees: [healthy] });
57
+ expect(stubs.gitService.worktreePrune).toHaveBeenCalledTimes(1);
58
+ expect(stubs.gitService.worktreePrune).toHaveBeenCalledWith('/fake/workspace');
59
+ const output = logs.join('\n');
60
+ expect(output).toContain('✗');
61
+ expect(output).toContain('workflow/dead');
62
+ expect(output).toContain('/tmp/dead');
63
+ expect(output).not.toContain('workflow/alive');
64
+ expect(output).toContain('✓ Pruned 1 stale worktree record(s)');
65
+ });
66
+ it('all stale: removes all, saveState called with empty, summary reports full count', async () => {
67
+ const a = makeRecord({ name: 'workflow/dead-a', path: '/tmp/dead-a' });
68
+ const b = makeRecord({ name: 'workflow/dead-b', path: '/tmp/dead-b' });
69
+ vi.mocked(fs.existsSync).mockReturnValue(false);
70
+ const { cmd, logs, stubs } = await makeCmd({ worktrees: [a, b] });
71
+ await cmd.run();
72
+ expect(stubs.worktreeService.saveState).toHaveBeenCalledTimes(1);
73
+ expect(stubs.worktreeService.saveState).toHaveBeenCalledWith({ worktrees: [] });
74
+ expect(stubs.gitService.worktreePrune).toHaveBeenCalledTimes(1);
75
+ expect(stubs.gitService.worktreePrune).toHaveBeenCalledWith('/fake/workspace');
76
+ const output = logs.join('\n');
77
+ expect(output).toContain('workflow/dead-a');
78
+ expect(output).toContain('/tmp/dead-a');
79
+ expect(output).toContain('workflow/dead-b');
80
+ expect(output).toContain('/tmp/dead-b');
81
+ expect(output).toContain('✓ Pruned 2 stale worktree record(s)');
82
+ });
83
+ it('all healthy: no save, no git prune, logs empty-state message', async () => {
84
+ const a = makeRecord({ name: 'workflow/alive-a', path: '/tmp/alive-a' });
85
+ const b = makeRecord({ name: 'workflow/alive-b', path: '/tmp/alive-b' });
86
+ vi.mocked(fs.existsSync).mockReturnValue(true);
87
+ const { cmd, logs, stubs } = await makeCmd({ worktrees: [a, b] });
88
+ await cmd.run();
89
+ expect(stubs.worktreeService.saveState).not.toHaveBeenCalled();
90
+ expect(stubs.gitService.worktreePrune).not.toHaveBeenCalled();
91
+ const output = logs.join('\n');
92
+ expect(output).toContain('No stale worktree records found');
93
+ expect(output).not.toContain('Pruned');
94
+ });
95
+ it('empty state: no save, no git prune, logs empty-state message', async () => {
96
+ vi.mocked(fs.existsSync).mockReturnValue(true);
97
+ const { cmd, logs, stubs } = await makeCmd({ worktrees: [] });
98
+ await cmd.run();
99
+ expect(stubs.worktreeService.saveState).not.toHaveBeenCalled();
100
+ expect(stubs.gitService.worktreePrune).not.toHaveBeenCalled();
101
+ const output = logs.join('\n');
102
+ expect(output).toContain('No stale worktree records found');
103
+ expect(output).not.toContain('Pruned');
104
+ });
105
+ });
@@ -0,0 +1,12 @@
1
+ import { BaseCommand } from '../../base-command.js';
2
+ export default class WorktreeRemove extends BaseCommand {
3
+ static args: {
4
+ name: import("@oclif/core/interfaces").Arg<string, Record<string, unknown>>;
5
+ };
6
+ static description: string;
7
+ static examples: string[];
8
+ static flags: {
9
+ force: import("@oclif/core/interfaces").BooleanFlag<boolean>;
10
+ };
11
+ run(): Promise<void>;
12
+ }
@@ -0,0 +1,48 @@
1
+ import { Args, Flags } from '@oclif/core';
2
+ import chalk from 'chalk';
3
+ import { BaseCommand } from '../../base-command.js';
4
+ export default class WorktreeRemove extends BaseCommand {
5
+ static args = {
6
+ name: Args.string({ description: 'Worktree name to remove', required: true }),
7
+ };
8
+ static description = 'Remove a worktree and all entity worktrees';
9
+ static examples = [
10
+ '<%= config.bin %> worktree remove workflow/batch',
11
+ '<%= config.bin %> worktree remove workflow/batch --force',
12
+ ];
13
+ static flags = {
14
+ force: Flags.boolean({ char: 'f', default: false, description: 'Remove even with uncommitted changes' }),
15
+ };
16
+ async run() {
17
+ const { args, flags } = await this.parse(WorktreeRemove);
18
+ const { name } = args;
19
+ const record = this.worktreeService.get(name);
20
+ if (!record) {
21
+ this.error(`Worktree '${name}' not found`);
22
+ }
23
+ this.log(chalk.bold('\n🗑️ Removing worktree...'));
24
+ const result = await this.worktreeService.removeWorktreeRecord(name, {
25
+ force: flags.force,
26
+ logger: (msg) => {
27
+ if (msg.includes('⚠'))
28
+ this.log(chalk.yellow(msg));
29
+ else if (msg.includes('○'))
30
+ this.log(chalk.dim(msg));
31
+ else if (msg.includes('✓'))
32
+ this.log(chalk.green(msg));
33
+ else
34
+ this.log(msg);
35
+ },
36
+ });
37
+ if (result.skippedDueToDirty) {
38
+ const dirtyList = result.dirtyEntities
39
+ .map(d => ` ${d.entityName}: ${d.changeCount} uncommitted changes`)
40
+ .join('\n');
41
+ this.error(`Cannot remove worktree with uncommitted changes:\n${dirtyList}\n\nUse --force to remove anyway.`);
42
+ }
43
+ this.log(chalk.dim('─'.repeat(50)));
44
+ this.log(chalk.green(`✓ Removed worktree '${name}'`));
45
+ this.log(` Path: ${record.path}`);
46
+ this.log(` Entities: ${result.removedEntities} removed${result.skippedEntities > 0 ? `, ${result.skippedEntities} skipped` : ''}`);
47
+ }
48
+ }
@@ -0,0 +1,9 @@
1
+ import { BaseCommand } from '../../base-command.js';
2
+ export default class WorktreeStatus extends BaseCommand {
3
+ static args: {
4
+ name: import("@oclif/core/interfaces").Arg<string | undefined, Record<string, unknown>>;
5
+ };
6
+ static description: string;
7
+ static examples: string[];
8
+ run(): Promise<void>;
9
+ }
@@ -0,0 +1,58 @@
1
+ import { Args } from '@oclif/core';
2
+ import chalk from 'chalk';
3
+ import Table from 'cli-table3';
4
+ import fs from 'node:fs';
5
+ import { BaseCommand } from '../../base-command.js';
6
+ export default class WorktreeStatus extends BaseCommand {
7
+ static args = {
8
+ name: Args.string({ description: 'Worktree name (shows all if omitted)', required: false }),
9
+ };
10
+ static description = 'Show per-entity git status for worktrees';
11
+ static examples = [
12
+ '<%= config.bin %> worktree status',
13
+ '<%= config.bin %> worktree status workflow/deploy-batch',
14
+ ];
15
+ async run() {
16
+ const { args } = await this.parse(WorktreeStatus);
17
+ let worktrees;
18
+ if (args.name) {
19
+ const record = this.worktreeService.get(args.name);
20
+ if (!record) {
21
+ this.error(`Worktree "${args.name}" not found. Run "gut worktree list" to see active worktrees.`);
22
+ }
23
+ worktrees = [record];
24
+ }
25
+ else {
26
+ worktrees = this.worktreeService.list();
27
+ if (worktrees.length === 0) {
28
+ this.log(`No active worktrees. Create one with: ${chalk.cyan('gut worktree create <branch-name>')}`);
29
+ return;
30
+ }
31
+ }
32
+ for (const worktree of worktrees) {
33
+ this.log(chalk.bold(`\n${worktree.name}`));
34
+ this.log(chalk.dim(worktree.path));
35
+ const table = new Table({
36
+ head: [chalk.cyan('Entity'), chalk.cyan('Branch'), chalk.cyan('Status'), chalk.cyan('Changes'), chalk.cyan('Ahead'), chalk.cyan('Behind')],
37
+ style: { border: [], head: [] },
38
+ });
39
+ for (const entity of worktree.entities) {
40
+ if (!fs.existsSync(entity.worktreePath)) {
41
+ table.push([entity.entityName, '-', chalk.yellow('[stale - path missing]'), '-', '-', '-']);
42
+ continue;
43
+ }
44
+ const status = await this.gitService.getStatus(entity.worktreePath);
45
+ const changeCount = status.changes.length + status.untracked.length;
46
+ table.push([
47
+ entity.entityName,
48
+ status.branch,
49
+ status.hasChanges ? chalk.yellow('dirty') : chalk.green('clean'),
50
+ status.hasChanges ? chalk.yellow(`${changeCount} changes`) : chalk.green('clean'),
51
+ status.ahead.toString(),
52
+ status.behind.toString(),
53
+ ]);
54
+ }
55
+ this.log(table.toString());
56
+ }
57
+ }
58
+ }
@@ -2,6 +2,20 @@ import type { WorktreeRecord, WorktreeState } from '../models/entity.model.js';
2
2
  import type { ConfigService } from './config.service.js';
3
3
  import type { FocusService } from './focus.service.js';
4
4
  import type { GitService } from './git.service.js';
5
+ export interface RemoveWorktreeOptions {
6
+ force: boolean;
7
+ logger?: (message: string) => void;
8
+ }
9
+ export interface RemoveWorktreeResult {
10
+ dirtyEntities: Array<{
11
+ changeCount: number;
12
+ entityName: string;
13
+ }>;
14
+ removed: boolean;
15
+ removedEntities: number;
16
+ skippedDueToDirty: boolean;
17
+ skippedEntities: number;
18
+ }
5
19
  export declare class WorktreeService {
6
20
  private readonly configService;
7
21
  private readonly gitService;
@@ -11,6 +25,16 @@ export declare class WorktreeService {
11
25
  constructor(configService: ConfigService, gitService: GitService, focusService: FocusService);
12
26
  get(name: string): WorktreeRecord | null;
13
27
  list(): WorktreeRecord[];
28
+ findStale(): WorktreeRecord[];
14
29
  loadState(): WorktreeState;
30
+ /**
31
+ * Remove a worktree record: all entity worktrees in reverse order, then the
32
+ * super-repo worktree, pruning refs along the way, then splice the record
33
+ * out of state. Shared between `worktree remove` and `worktree gc`.
34
+ *
35
+ * If any entity has uncommitted changes and `force` is false, nothing is
36
+ * removed and `skippedDueToDirty` is returned true.
37
+ */
38
+ removeWorktreeRecord(name: string, options: RemoveWorktreeOptions): Promise<RemoveWorktreeResult>;
15
39
  saveState(state: WorktreeState): void;
16
40
  }
@@ -20,6 +20,9 @@ export class WorktreeService {
20
20
  list() {
21
21
  return this.loadState().worktrees;
22
22
  }
23
+ findStale() {
24
+ return this.loadState().worktrees.filter(w => !fs.existsSync(w.path));
25
+ }
23
26
  loadState() {
24
27
  if (!fs.existsSync(this.stateFile)) {
25
28
  return { worktrees: [] };
@@ -37,6 +40,93 @@ export class WorktreeService {
37
40
  return { worktrees: [] };
38
41
  }
39
42
  }
43
+ /**
44
+ * Remove a worktree record: all entity worktrees in reverse order, then the
45
+ * super-repo worktree, pruning refs along the way, then splice the record
46
+ * out of state. Shared between `worktree remove` and `worktree gc`.
47
+ *
48
+ * If any entity has uncommitted changes and `force` is false, nothing is
49
+ * removed and `skippedDueToDirty` is returned true.
50
+ */
51
+ async removeWorktreeRecord(name, options) {
52
+ const { force, logger } = options;
53
+ const log = (message) => {
54
+ if (logger)
55
+ logger(message);
56
+ };
57
+ const record = this.get(name);
58
+ if (!record) {
59
+ throw new Error(`Worktree '${name}' not found`);
60
+ }
61
+ const workspaceRoot = this.configService.getWorkspaceRoot();
62
+ // Dirty-state pre-check (mirrors remove.ts:39-50)
63
+ const dirtyEntities = [];
64
+ for (const entity of record.entities) {
65
+ if (!fs.existsSync(entity.worktreePath))
66
+ continue;
67
+ // eslint-disable-next-line no-await-in-loop
68
+ const status = await this.gitService.getStatus(entity.worktreePath);
69
+ if (status.hasChanges) {
70
+ dirtyEntities.push({
71
+ changeCount: status.changes.length + status.untracked.length,
72
+ entityName: entity.entityName,
73
+ });
74
+ }
75
+ }
76
+ if (dirtyEntities.length > 0 && !force) {
77
+ return {
78
+ dirtyEntities,
79
+ removed: false,
80
+ removedEntities: 0,
81
+ skippedDueToDirty: true,
82
+ skippedEntities: 0,
83
+ };
84
+ }
85
+ if (dirtyEntities.length > 0 && force) {
86
+ for (const d of dirtyEntities) {
87
+ log(` ⚠ ${d.entityName}: ${d.changeCount} uncommitted changes will be lost`);
88
+ }
89
+ }
90
+ // Entity worktrees in reverse order
91
+ let removedEntities = 0;
92
+ let skippedEntities = 0;
93
+ const reversed = [...record.entities].reverse();
94
+ for (const entity of reversed) {
95
+ const mainRepoPath = path.join(workspaceRoot, entity.entityPath);
96
+ if (!fs.existsSync(entity.worktreePath)) {
97
+ log(` ○ ${entity.entityName}: already removed (skipped)`);
98
+ skippedEntities++;
99
+ // eslint-disable-next-line no-await-in-loop
100
+ await this.gitService.worktreePrune(mainRepoPath).catch(() => { });
101
+ continue;
102
+ }
103
+ // eslint-disable-next-line no-await-in-loop
104
+ await this.gitService.worktreeRemove(mainRepoPath, entity.worktreePath, force);
105
+ // eslint-disable-next-line no-await-in-loop
106
+ await this.gitService.worktreePrune(mainRepoPath);
107
+ log(` ✓ ${entity.entityName}: worktree removed`);
108
+ removedEntities++;
109
+ }
110
+ // Super-repo worktree
111
+ if (fs.existsSync(record.path)) {
112
+ await this.gitService.worktreeRemove(workspaceRoot, record.path, force);
113
+ }
114
+ await this.gitService.worktreePrune(workspaceRoot);
115
+ // Splice the record out of state
116
+ const state = this.loadState();
117
+ const idx = state.worktrees.findIndex(w => w.name === name);
118
+ if (idx !== -1) {
119
+ state.worktrees.splice(idx, 1);
120
+ }
121
+ this.saveState(state);
122
+ return {
123
+ dirtyEntities,
124
+ removed: true,
125
+ removedEntities,
126
+ skippedDueToDirty: false,
127
+ skippedEntities,
128
+ };
129
+ }
40
130
  saveState(state) {
41
131
  const serialized = JSON.stringify(state, null, 2);
42
132
  try {
@@ -0,0 +1 @@
1
+ export declare function parseDuration(input: string): number;
@@ -0,0 +1,26 @@
1
+ const SUFFIX_MS = {
2
+ d: 86_400_000,
3
+ h: 3_600_000,
4
+ m: 60_000,
5
+ s: 1000,
6
+ };
7
+ export function parseDuration(input) {
8
+ const invalid = () => {
9
+ throw new Error(`Invalid duration: '${input}'. Expected format like '7d', '24h', '30m', or '90s'.`);
10
+ };
11
+ if (typeof input !== 'string' || input.length === 0)
12
+ invalid();
13
+ if (/\s/.test(input))
14
+ invalid();
15
+ const match = /^(\d+)([a-zA-Z])$/.exec(input);
16
+ if (!match)
17
+ invalid();
18
+ const [, numStr, suffix] = match;
19
+ const multiplier = SUFFIX_MS[suffix];
20
+ if (multiplier === undefined)
21
+ invalid();
22
+ const value = Number(numStr);
23
+ if (!Number.isFinite(value) || value < 0)
24
+ invalid();
25
+ return value * multiplier;
26
+ }