@hyperdrive.bot/gut 0.1.12 → 0.1.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -18,7 +18,7 @@ $ npm install -g @hyperdrive.bot/gut
18
18
  $ gut COMMAND
19
19
  running command...
20
20
  $ gut (--version)
21
- @hyperdrive.bot/gut/0.1.12 linux-x64 node-v22.22.1
21
+ @hyperdrive.bot/gut/0.1.13 linux-x64 node-v22.22.1
22
22
  $ gut --help [COMMAND]
23
23
  USAGE
24
24
  $ gut COMMAND
@@ -2,5 +2,9 @@ import { BaseCommand } from '../base-command.js';
2
2
  export default class Context extends BaseCommand {
3
3
  static description: string;
4
4
  static examples: string[];
5
+ static flags: {
6
+ all: import("@oclif/core/interfaces").BooleanFlag<boolean>;
7
+ json: import("@oclif/core/interfaces").BooleanFlag<boolean>;
8
+ };
5
9
  run(): Promise<void>;
6
10
  }
@@ -1,3 +1,4 @@
1
+ import { Flags } from '@oclif/core';
1
2
  import chalk from 'chalk';
2
3
  import path from 'node:path';
3
4
  import { BaseCommand } from '../base-command.js';
@@ -5,22 +6,106 @@ export default class Context extends BaseCommand {
5
6
  static description = 'Show current focus context with entity details';
6
7
  static examples = [
7
8
  '<%= config.bin %> <%= command.id %>',
9
+ '<%= config.bin %> <%= command.id %> --json',
10
+ '<%= config.bin %> <%= command.id %> --json --all',
8
11
  ];
12
+ static flags = {
13
+ all: Flags.boolean({
14
+ default: false,
15
+ description: 'Include all registered entities, not just focused ones (implies --json or adds to text output)',
16
+ }),
17
+ json: Flags.boolean({
18
+ default: false,
19
+ description: 'Emit structured JSON for programmatic consumption (includes per-entity branch + hasUncommitted)',
20
+ }),
21
+ };
9
22
  async run() {
10
- await this.parse(Context);
23
+ const { flags } = await this.parse(Context);
24
+ const workspaceRoot = this.configService.getWorkspaceRoot();
11
25
  const focusedEntities = await this.focusService.getFocusedEntities();
12
- if (focusedEntities.length === 0) {
26
+ const focus = await this.focusService.getCurrentFocus();
27
+ const focusedNames = new Set(focusedEntities.map(e => e.name));
28
+ // For JSON or --all, resolve the full entity set. For normal text output,
29
+ // keep the existing behavior (focused only).
30
+ const includeAll = flags.json || flags.all;
31
+ const entitiesToReport = includeAll
32
+ ? this.entityService.getAllEntities()
33
+ : focusedEntities;
34
+ // Enrich each entity with branch + uncommitted status. Entities may not
35
+ // exist on disk (not cloned), so be defensive.
36
+ const enriched = [];
37
+ for (const entity of entitiesToReport) {
38
+ const relativePath = entity.path.replace(/^\.\//, '');
39
+ const absolutePath = path.isAbsolute(entity.path)
40
+ ? entity.path
41
+ : path.join(workspaceRoot, relativePath);
42
+ let currentBranch = null;
43
+ let hasUncommitted = false;
44
+ let pathExists = false;
45
+ try {
46
+ const { existsSync } = await import('node:fs');
47
+ pathExists = existsSync(path.join(absolutePath, '.git')) || existsSync(absolutePath);
48
+ }
49
+ catch {
50
+ pathExists = false;
51
+ }
52
+ if (pathExists) {
53
+ try {
54
+ currentBranch = await this.gitService.getCurrentBranch(absolutePath);
55
+ }
56
+ catch {
57
+ currentBranch = null;
58
+ }
59
+ try {
60
+ hasUncommitted = await this.gitService.hasChanges(absolutePath);
61
+ }
62
+ catch {
63
+ hasUncommitted = false;
64
+ }
65
+ }
66
+ enriched.push({
67
+ currentBranch,
68
+ focused: focusedNames.has(entity.name),
69
+ hasUncommitted,
70
+ name: entity.name,
71
+ path: relativePath,
72
+ pathExists,
73
+ type: entity.type,
74
+ });
75
+ }
76
+ if (flags.json) {
77
+ const payload = {
78
+ entities: enriched,
79
+ focus: {
80
+ entities: [...focusedNames],
81
+ mode: focus?.mode ?? null,
82
+ },
83
+ workspaceRoot,
84
+ };
85
+ // Emit compact, machine-readable JSON on stdout. No chalk, no decoration.
86
+ this.log(JSON.stringify(payload, null, 2));
87
+ return;
88
+ }
89
+ if (focusedEntities.length === 0 && !flags.all) {
13
90
  this.log(chalk.yellow('No entities are currently focused'));
14
91
  this.log(chalk.dim('Use "gut focus <entity>" to set focus'));
15
92
  return;
16
93
  }
17
- const workspaceRoot = this.configService.getWorkspaceRoot();
18
94
  this.log(chalk.bold('\nšŸ“ Current Focus Context'));
19
95
  this.log(chalk.dim('─'.repeat(50)));
20
- for (const entity of focusedEntities) {
21
- this.log(`\n${chalk.green('ā–ø')} ${chalk.bold(entity.name)}`);
96
+ for (const entity of enriched) {
97
+ if (!flags.all && !entity.focused)
98
+ continue;
99
+ const marker = entity.focused ? chalk.green('ā–ø') : chalk.dim('Ā·');
100
+ this.log(`\n${marker} ${chalk.bold(entity.name)}`);
22
101
  this.log(` ${chalk.dim('Type:')} ${entity.type}`);
23
- this.log(` ${chalk.dim('Path:')} ${path.relative(workspaceRoot, entity.path)}`);
102
+ this.log(` ${chalk.dim('Path:')} ${entity.path}`);
103
+ if (entity.pathExists) {
104
+ this.log(` ${chalk.dim('Branch:')} ${entity.currentBranch ?? chalk.red('(unknown)')}${entity.hasUncommitted ? chalk.yellow(' *dirty') : ''}`);
105
+ }
106
+ else {
107
+ this.log(` ${chalk.dim('Branch:')} ${chalk.dim('(not checked out)')}`);
108
+ }
24
109
  }
25
110
  this.log(chalk.dim('\n─'.repeat(50)));
26
111
  this.log(`${chalk.dim('Total focused entities:')} ${focusedEntities.length}`);
@@ -125,6 +125,9 @@ export default class Focus extends BaseCommand {
125
125
  this.log(` ${this.getTypeEmoji(entity.type)} ${entity.name} (${entity.type})`);
126
126
  }
127
127
  }
128
+ // Machine-readable confirmation line for programmatic callers (e.g.,
129
+ // bmad-workflow execSync). Always printed, grep-friendly format.
130
+ this.log(`FOCUSED: ${entities.map(e => e.name).join(',')}`);
128
131
  }
129
132
  catch (error) {
130
133
  const message = error instanceof Error ? error.message : String(error);
@@ -7,6 +7,7 @@ export default class WorktreeCreate extends BaseCommand {
7
7
  static examples: string[];
8
8
  static flags: {
9
9
  'base-dir': import("@oclif/core/interfaces").OptionFlag<string, import("@oclif/core/interfaces").CustomOptions>;
10
+ entity: import("@oclif/core/interfaces").OptionFlag<string[] | undefined, import("@oclif/core/interfaces").CustomOptions>;
10
11
  from: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
11
12
  install: import("@oclif/core/interfaces").BooleanFlag<boolean>;
12
13
  };
@@ -2,8 +2,11 @@ import { Args, Flags } from '@oclif/core';
2
2
  import chalk from 'chalk';
3
3
  import { spawn } from 'node:child_process';
4
4
  import fs from 'node:fs';
5
+ import os from 'node:os';
5
6
  import path from 'node:path';
6
7
  import { BaseCommand } from '../../base-command.js';
8
+ import { parseEntitySpecs } from '../../utils/entity-spec.js';
9
+ const xdgDefaultBaseDir = path.join(os.homedir(), '.local', 'share', 'gut', 'worktrees');
7
10
  export default class WorktreeCreate extends BaseCommand {
8
11
  static args = {
9
12
  name: Args.string({ description: 'Branch name for the worktree', required: true }),
@@ -13,9 +16,18 @@ export default class WorktreeCreate extends BaseCommand {
13
16
  '<%= config.bin %> worktree create workflow/deploy-batch',
14
17
  '<%= config.bin %> worktree create workflow/deploy-batch --from master --install',
15
18
  '<%= config.bin %> worktree create feature/story-42 --base-dir /home/user/worktrees',
19
+ '<%= config.bin %> worktree create seo-lake --entity serverless-api:feature/seo-lake --entity sign',
20
+ 'GUT_WORKTREE_DIR=/tmp/gut-worktrees <%= config.bin %> worktree create feature/ci-run',
16
21
  ];
17
22
  static flags = {
18
- 'base-dir': Flags.string({ default: '/tmp/gut-worktrees', description: 'Root directory for worktrees' }),
23
+ 'base-dir': Flags.string({
24
+ default: async () => process.env.GUT_WORKTREE_DIR ?? xdgDefaultBaseDir,
25
+ description: 'Root directory for worktrees (default: ~/.local/share/gut/worktrees, override via GUT_WORKTREE_DIR env var; explicit --base-dir wins)',
26
+ }),
27
+ entity: Flags.string({
28
+ description: 'Entity to include, optionally pinned to a branch via "name:branch". Repeatable. Overrides current focus when provided.',
29
+ multiple: true,
30
+ }),
19
31
  from: Flags.string({ description: 'Base branch to create from (defaults to current branch)' }),
20
32
  install: Flags.boolean({ default: false, description: 'Run pnpm install after creation' }),
21
33
  };
@@ -24,6 +36,9 @@ export default class WorktreeCreate extends BaseCommand {
24
36
  const workspaceRoot = this.configService.getWorkspaceRoot();
25
37
  const slug = args.name.replace(/\//g, '-');
26
38
  const wtPath = path.join(flags['base-dir'], slug);
39
+ // Ensure the base directory exists — git worktree add creates the target
40
+ // dir, but the parent (the base dir itself) must already exist.
41
+ fs.mkdirSync(flags['base-dir'], { recursive: true });
27
42
  const baseBranch = flags.from ?? await this.gitService.getCurrentBranch(workspaceRoot);
28
43
  // --- Validation (AC: 7) ---
29
44
  const existing = this.worktreeService.get(args.name);
@@ -35,10 +50,35 @@ export default class WorktreeCreate extends BaseCommand {
35
50
  if (branchCollision) {
36
51
  this.error(`Branch "${args.name}" already has a worktree at ${branchCollision.path}. Remove it first or use a different name.`);
37
52
  }
38
- // --- Validation (AC: 8) ---
39
- const focusedEntities = await this.focusService.getFocusedEntities();
40
- if (focusedEntities.length === 0) {
41
- this.error('No entities focused. Use "gut focus <entity>" first.');
53
+ // --- Resolve entity set: --entity flag overrides focus ---
54
+ let entitySpecs;
55
+ try {
56
+ entitySpecs = parseEntitySpecs(flags.entity);
57
+ }
58
+ catch (err) {
59
+ const message = err instanceof Error ? err.message : String(err);
60
+ this.error(message);
61
+ }
62
+ let selectedEntities;
63
+ const branchOverrides = new Map();
64
+ if (entitySpecs.length > 0) {
65
+ selectedEntities = [];
66
+ for (const spec of entitySpecs) {
67
+ const entity = this.entityService.findEntity(spec.name);
68
+ if (!entity) {
69
+ this.error(`Entity "${spec.name}" not found in workspace config. Run \`gut entity list\` to see available entities.`);
70
+ }
71
+ selectedEntities.push(entity);
72
+ if (spec.branch) {
73
+ branchOverrides.set(entity.name, spec.branch);
74
+ }
75
+ }
76
+ }
77
+ else {
78
+ selectedEntities = await this.focusService.getFocusedEntities();
79
+ if (selectedEntities.length === 0) {
80
+ this.error('No entities focused and no --entity flag provided. Use "gut focus <entity>" first, or pass --entity <name> (repeatable).');
81
+ }
42
82
  }
43
83
  // --- Create worktrees with atomic rollback (AC: 1, 2, 9) ---
44
84
  const createdWorktrees = [];
@@ -49,14 +89,18 @@ export default class WorktreeCreate extends BaseCommand {
49
89
  createdWorktrees.push({ repoPath: workspaceRoot, wtPath });
50
90
  this.log(chalk.green('āœ“ Super-repo worktree created at ' + wtPath));
51
91
  // Per-entity worktrees (AC: 2)
52
- for (const entity of focusedEntities) {
92
+ for (const entity of selectedEntities) {
53
93
  const entityRelativePath = entity.path.replace(/^\.\//, '');
54
94
  const entityWtPath = path.join(wtPath, entityRelativePath);
55
95
  const entityMainPath = path.join(workspaceRoot, entityRelativePath);
56
- // Always use the entity's current branch as base — the super-repo branch
57
- // may exist but be stale (e.g., api has master but works on develop)
58
- const entityBaseBranch = await this.gitService.getCurrentBranch(entityMainPath);
59
- if (entityBaseBranch !== baseBranch) {
96
+ // Branch override from --entity name:branch wins; otherwise use entity's
97
+ // current branch in the main repo.
98
+ const override = branchOverrides.get(entity.name);
99
+ const entityBaseBranch = override ?? await this.gitService.getCurrentBranch(entityMainPath);
100
+ if (override) {
101
+ this.log(chalk.cyan(` Branch override: ${entity.name} → ${override}`));
102
+ }
103
+ else if (entityBaseBranch !== baseBranch) {
60
104
  this.log(chalk.yellow(`⚠ Entity "${entity.name}" is on "${entityBaseBranch}" (super-repo: "${baseBranch}")`));
61
105
  }
62
106
  // Remove submodule stub
@@ -64,7 +108,7 @@ export default class WorktreeCreate extends BaseCommand {
64
108
  // Create entity worktree
65
109
  await this.gitService.worktreeAdd(entityMainPath, entityWtPath, args.name, entityBaseBranch);
66
110
  createdWorktrees.push({ repoPath: entityMainPath, wtPath: entityWtPath });
67
- this.log(chalk.green(`āœ“ Entity worktree: ${entity.name} → ${args.name}`));
111
+ this.log(chalk.green(`āœ“ Entity worktree: ${entity.name} → ${args.name} (from ${entityBaseBranch})`));
68
112
  entityRecords.push({
69
113
  branch: args.name,
70
114
  entityName: entity.name,
@@ -79,7 +123,7 @@ export default class WorktreeCreate extends BaseCommand {
79
123
  await this.gitService.worktreeRemove(entry.repoPath, entry.wtPath, true).catch(() => { });
80
124
  }
81
125
  await this.gitService.worktreePrune(workspaceRoot).catch(() => { });
82
- for (const entity of focusedEntities) {
126
+ for (const entity of selectedEntities) {
83
127
  const entityRelativePath = entity.path.replace(/^\.\//, '');
84
128
  const entityMainPath = path.join(workspaceRoot, entityRelativePath);
85
129
  await this.gitService.worktreePrune(entityMainPath).catch(() => { });
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Parses `--entity` flag values for `gut worktree create`.
3
+ *
4
+ * Each spec is either a bare entity name (`serverless-api`) or a pinned
5
+ * spec (`serverless-api:feature/seo-lake`). The first `:` separates the
6
+ * entity name from the branch; the branch itself may contain `/` or `-`.
7
+ *
8
+ * Invalid shapes throw with a descriptive message so callers can surface
9
+ * the error to the user.
10
+ */
11
+ export interface EntitySpec {
12
+ branch?: string;
13
+ name: string;
14
+ }
15
+ export declare function parseEntitySpecs(specs: string[] | undefined): EntitySpec[];
@@ -0,0 +1,29 @@
1
+ export function parseEntitySpecs(specs) {
2
+ if (!specs || specs.length === 0)
3
+ return [];
4
+ const parsed = [];
5
+ for (const raw of specs) {
6
+ const trimmed = raw.trim();
7
+ if (!trimmed)
8
+ continue;
9
+ const colonIdx = trimmed.indexOf(':');
10
+ if (colonIdx === -1) {
11
+ parsed.push({ name: trimmed });
12
+ continue;
13
+ }
14
+ const name = trimmed.slice(0, colonIdx).trim();
15
+ const branch = trimmed.slice(colonIdx + 1).trim();
16
+ if (!name) {
17
+ throw new Error(`Invalid --entity spec "${raw}": missing entity name before ":"`);
18
+ }
19
+ if (branch) {
20
+ parsed.push({ branch, name });
21
+ }
22
+ else {
23
+ // "name:" is tolerated — same as bare name. Useful if a caller builds
24
+ // specs programmatically and omits the branch for some entities.
25
+ parsed.push({ name });
26
+ }
27
+ }
28
+ return parsed;
29
+ }
@@ -301,9 +301,24 @@
301
301
  "args": {},
302
302
  "description": "Show current focus context with entity details",
303
303
  "examples": [
304
- "<%= config.bin %> <%= command.id %>"
304
+ "<%= config.bin %> <%= command.id %>",
305
+ "<%= config.bin %> <%= command.id %> --json",
306
+ "<%= config.bin %> <%= command.id %> --json --all"
305
307
  ],
306
- "flags": {},
308
+ "flags": {
309
+ "all": {
310
+ "description": "Include all registered entities, not just focused ones (implies --json or adds to text output)",
311
+ "name": "all",
312
+ "allowNo": false,
313
+ "type": "boolean"
314
+ },
315
+ "json": {
316
+ "description": "Emit structured JSON for programmatic consumption (includes per-entity branch + hasUncommitted)",
317
+ "name": "json",
318
+ "allowNo": false,
319
+ "type": "boolean"
320
+ }
321
+ },
307
322
  "hasDynamicHelp": false,
308
323
  "hiddenAliases": [],
309
324
  "id": "context",
@@ -2186,17 +2201,26 @@
2186
2201
  "examples": [
2187
2202
  "<%= config.bin %> worktree create workflow/deploy-batch",
2188
2203
  "<%= config.bin %> worktree create workflow/deploy-batch --from master --install",
2189
- "<%= config.bin %> worktree create feature/story-42 --base-dir /home/user/worktrees"
2204
+ "<%= config.bin %> worktree create feature/story-42 --base-dir /home/user/worktrees",
2205
+ "<%= config.bin %> worktree create seo-lake --entity serverless-api:feature/seo-lake --entity sign",
2206
+ "GUT_WORKTREE_DIR=/tmp/gut-worktrees <%= config.bin %> worktree create feature/ci-run"
2190
2207
  ],
2191
2208
  "flags": {
2192
2209
  "base-dir": {
2193
- "description": "Root directory for worktrees",
2210
+ "description": "Root directory for worktrees (default: ~/.local/share/gut/worktrees, override via GUT_WORKTREE_DIR env var; explicit --base-dir wins)",
2194
2211
  "name": "base-dir",
2195
- "default": "/tmp/gut-worktrees",
2212
+ "default": "/root/.local/share/gut/worktrees",
2196
2213
  "hasDynamicHelp": false,
2197
2214
  "multiple": false,
2198
2215
  "type": "option"
2199
2216
  },
2217
+ "entity": {
2218
+ "description": "Entity to include, optionally pinned to a branch via \"name:branch\". Repeatable. Overrides current focus when provided.",
2219
+ "name": "entity",
2220
+ "hasDynamicHelp": false,
2221
+ "multiple": true,
2222
+ "type": "option"
2223
+ },
2200
2224
  "from": {
2201
2225
  "description": "Base branch to create from (defaults to current branch)",
2202
2226
  "name": "from",
@@ -2227,5 +2251,5 @@
2227
2251
  ]
2228
2252
  }
2229
2253
  },
2230
- "version": "0.1.12"
2254
+ "version": "0.1.13"
2231
2255
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hyperdrive.bot/gut",
3
- "version": "0.1.12",
3
+ "version": "0.1.13",
4
4
  "description": "Git Unified Tooling - Enhanced git with workspace intelligence for entity-based organization",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",