@nemus-cli/nemus 0.10.0 → 0.11.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.
- package/CHANGELOG.md +14 -0
- package/README.md +13 -0
- package/dist/commands/prune.js +196 -0
- package/dist/program.js +2 -0
- package/dist/utils/prune.js +70 -0
- package/package.json +1 -1
- package/scripts/release-notes.mjs +54 -0
- package/skills/config.md +17 -0
- package/skills/nemus/SKILL.md +7 -2
- package/skills/nemus/references/completion.md +22 -0
- package/skills/nemus/references/config.md +32 -0
- package/skills/nemus/references/prune.md +44 -0
- package/skills/nemus/references/reflect.md +43 -0
- package/skills/nemus/references/save-context.md +25 -0
- package/skills/prune-workspaces.md +23 -0
- package/skills/reflect.md +21 -0
- package/src/commands/prune.ts +183 -0
- package/src/program.ts +2 -0
- package/src/utils/prune.test.ts +121 -0
- package/src/utils/prune.ts +109 -0
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [0.11.0] - 2026-09-02
|
|
11
|
+
|
|
12
|
+
### Added
|
|
13
|
+
|
|
14
|
+
- **`nemus prune`** — bulk-delete workspaces with no recent activity, **safe by
|
|
15
|
+
default.** It selects workspaces whose most recent agent session (or, absent
|
|
16
|
+
any session, whose `createdAt`) is older than `--days` (default 30), and
|
|
17
|
+
**holds back any workspace with uncommitted or unpushed changes** — listing
|
|
18
|
+
each protected one and why. Preview with `--dry-run` or `--json` (both never
|
|
19
|
+
delete); otherwise it deletes after a confirmation (`-y/--yes` to skip).
|
|
20
|
+
`--include-dirty` overrides the safety guard. Deletions go through the same
|
|
21
|
+
validated `safeWorkspacePath()` choke point as `nemus delete`. The
|
|
22
|
+
stale/protected decision logic is pure and unit-tested.
|
|
23
|
+
|
|
10
24
|
## [0.10.0] - 2026-09-01
|
|
11
25
|
|
|
12
26
|
### Changed
|
package/README.md
CHANGED
|
@@ -202,9 +202,22 @@ nemus create # (c) interactive create
|
|
|
202
202
|
nemus list # (l) list workspaces
|
|
203
203
|
nemus update # (u) add repos to a workspace
|
|
204
204
|
nemus delete # (del) delete a workspace
|
|
205
|
+
nemus prune # delete workspaces with no recent activity (safe by default)
|
|
205
206
|
nemus go [name] # jump to a workspace directory
|
|
206
207
|
```
|
|
207
208
|
|
|
209
|
+
> **`prune`** clears out workspaces you've finished with. It selects those with
|
|
210
|
+
> no agent session (or, failing that, no `createdAt`) in the last **N days**
|
|
211
|
+
> (`--days`, default 30) and — crucially — **protects any workspace with
|
|
212
|
+
> uncommitted or unpushed work**, listing why it was skipped. Preview with
|
|
213
|
+
> `--dry-run` (or `--json`), then delete after a confirmation (`--yes` to skip).
|
|
214
|
+
> `--include-dirty` overrides the safety guard. Example:
|
|
215
|
+
>
|
|
216
|
+
> ```bash
|
|
217
|
+
> nemus prune --days 30 --dry-run # see what would go, nothing deleted
|
|
218
|
+
> nemus prune --days 30 # prune stale + clean workspaces, with a prompt
|
|
219
|
+
> ```
|
|
220
|
+
|
|
208
221
|
### Operate across all repos
|
|
209
222
|
|
|
210
223
|
```bash
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
+
exports.registerPruneCommand = registerPruneCommand;
|
|
37
|
+
exports.handlePrune = handlePrune;
|
|
38
|
+
const fs = __importStar(require("fs/promises"));
|
|
39
|
+
const validation_1 = require("../utils/validation");
|
|
40
|
+
const workspace_meta_1 = require("../utils/workspace-meta");
|
|
41
|
+
const claude_sessions_1 = require("../utils/claude-sessions");
|
|
42
|
+
const git_status_1 = require("../utils/git-status");
|
|
43
|
+
const logger_1 = require("../utils/logger");
|
|
44
|
+
const colors_1 = require("../utils/colors");
|
|
45
|
+
const prompt_1 = require("../utils/prompt");
|
|
46
|
+
const command_helpers_1 = require("../utils/command-helpers");
|
|
47
|
+
const output_1 = require("../utils/output");
|
|
48
|
+
const prune_1 = require("../utils/prune");
|
|
49
|
+
const DEFAULT_DAYS = 30;
|
|
50
|
+
function registerPruneCommand(parent) {
|
|
51
|
+
parent
|
|
52
|
+
.command('prune')
|
|
53
|
+
.description('Delete workspaces with no recent activity (safe by default)')
|
|
54
|
+
.option('-d, --days <n>', `Consider a workspace stale after N days of inactivity (default ${DEFAULT_DAYS})`)
|
|
55
|
+
.option('--include-dirty', 'Also prune workspaces with uncommitted/unpushed changes (default: protected)')
|
|
56
|
+
.option('--dry-run', 'Show what would be pruned without deleting anything')
|
|
57
|
+
.option('-y, --yes', 'Skip the confirmation prompt')
|
|
58
|
+
.option('--json', 'Output the prune plan as JSON (never deletes)')
|
|
59
|
+
.action(async (opts, cmd) => {
|
|
60
|
+
const globalOpts = (0, command_helpers_1.getGlobalOpts)(cmd);
|
|
61
|
+
await handlePrune({ ...opts, ...globalOpts });
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
function parseDays(raw) {
|
|
65
|
+
if (raw === undefined)
|
|
66
|
+
return DEFAULT_DAYS;
|
|
67
|
+
const n = Number(raw);
|
|
68
|
+
if (!Number.isFinite(n) || n < 0)
|
|
69
|
+
return null;
|
|
70
|
+
return Math.floor(n);
|
|
71
|
+
}
|
|
72
|
+
async function handlePrune(opts) {
|
|
73
|
+
const json = !!opts.json;
|
|
74
|
+
const days = parseDays(opts.days);
|
|
75
|
+
if (days === null) {
|
|
76
|
+
if (json)
|
|
77
|
+
(0, output_1.outputJsonError)('--days must be a non-negative number');
|
|
78
|
+
else
|
|
79
|
+
(0, logger_1.logError)('--days must be a non-negative number');
|
|
80
|
+
process.exit(1);
|
|
81
|
+
}
|
|
82
|
+
try {
|
|
83
|
+
const [workspaces, sessions] = await Promise.all([(0, workspace_meta_1.listWorkspaces)(), (0, claude_sessions_1.getWorkspaceSessions)()]);
|
|
84
|
+
const sessionMap = new Map(sessions.map((s) => [s.workspaceName, s]));
|
|
85
|
+
const now = Date.now();
|
|
86
|
+
const candidates = workspaces.map((ws) => {
|
|
87
|
+
const session = sessionMap.get(ws.name);
|
|
88
|
+
const createdRaw = ws.metadata?.createdAt ? Date.parse(ws.metadata.createdAt) : NaN;
|
|
89
|
+
const forPrune = {
|
|
90
|
+
name: ws.name,
|
|
91
|
+
path: ws.path,
|
|
92
|
+
repoDirNames: (ws.metadata?.repositories ?? []).map((r) => r.directoryName),
|
|
93
|
+
lastActiveAt: session ? session.lastActiveAt.getTime() : 0,
|
|
94
|
+
createdAt: Number.isFinite(createdRaw) ? createdRaw : 0,
|
|
95
|
+
};
|
|
96
|
+
return (0, prune_1.toCandidate)(forPrune, now);
|
|
97
|
+
});
|
|
98
|
+
const stale = candidates.filter((c) => (0, prune_1.isStale)(c, days));
|
|
99
|
+
if (stale.length === 0) {
|
|
100
|
+
if (json) {
|
|
101
|
+
(0, output_1.outputJson)({ ok: true, days, prunable: [], protected: [], scanned: workspaces.length });
|
|
102
|
+
}
|
|
103
|
+
else {
|
|
104
|
+
(0, logger_1.logInfo)(`No workspaces inactive for ${days}+ days (scanned ${workspaces.length}).`);
|
|
105
|
+
}
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
// Compute the plan. The git safety check only runs for stale workspaces.
|
|
109
|
+
const plan = await (0, prune_1.planPrune)(stale, (c) => (0, git_status_1.getAllReposStatus)(c.path, c.repoDirNames, 3), !!opts.includeDirty);
|
|
110
|
+
if (json) {
|
|
111
|
+
(0, output_1.outputJson)({
|
|
112
|
+
ok: true,
|
|
113
|
+
days,
|
|
114
|
+
scanned: workspaces.length,
|
|
115
|
+
prunable: plan.prunable.map((c) => ({ name: c.name, path: c.path, ageDays: c.ageDays, repos: c.repoDirNames.length })),
|
|
116
|
+
protected: plan.protected.map((p) => ({ name: p.candidate.name, ageDays: p.candidate.ageDays, reason: p.reason })),
|
|
117
|
+
});
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
// Human report.
|
|
121
|
+
console.log('\n' + '='.repeat(60));
|
|
122
|
+
console.log((0, colors_1.colorize)(`Prune — workspaces inactive for ${days}+ days`, 'bright'));
|
|
123
|
+
console.log('='.repeat(60) + '\n');
|
|
124
|
+
if (plan.protected.length > 0) {
|
|
125
|
+
(0, logger_1.logWarning)(`Protected (${plan.protected.length}) — skipped due to unsaved work:`);
|
|
126
|
+
for (const p of plan.protected) {
|
|
127
|
+
console.log(` ${(0, colors_1.colorize)('•', 'yellow')} ${(0, colors_1.colorize)(p.candidate.name, 'cyan')} — ${p.reason} ${(0, colors_1.colorize)(`(${ageLabel(p.candidate)})`, 'gray')}`);
|
|
128
|
+
}
|
|
129
|
+
console.log('');
|
|
130
|
+
}
|
|
131
|
+
if (plan.prunable.length === 0) {
|
|
132
|
+
(0, logger_1.logInfo)('Nothing safe to prune.');
|
|
133
|
+
if (plan.protected.length > 0)
|
|
134
|
+
(0, logger_1.logInfo)('Re-run with --include-dirty to include the protected ones (careful).');
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
console.log(`${(0, colors_1.colorize)('Prunable', 'bright')} (${plan.prunable.length}):`);
|
|
138
|
+
for (const c of plan.prunable) {
|
|
139
|
+
const repoLabel = c.repoDirNames.length === 1 ? '1 repo' : `${c.repoDirNames.length} repos`;
|
|
140
|
+
console.log(` ${(0, colors_1.colorize)('✗', 'red')} ${(0, colors_1.colorize)(c.name, 'cyan')} ${(0, colors_1.colorize)(`(${ageLabel(c)}, ${repoLabel})`, 'gray')}`);
|
|
141
|
+
}
|
|
142
|
+
console.log('');
|
|
143
|
+
if (opts.dryRun) {
|
|
144
|
+
(0, logger_1.logInfo)(`Dry run — nothing deleted. ${plan.prunable.length} workspace(s) would be pruned.`);
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
(0, logger_1.logWarning)('This permanently deletes the selected workspaces and every cloned repo inside them!');
|
|
148
|
+
if (!opts.yes) {
|
|
149
|
+
const confirmed = await (0, prompt_1.confirm)({
|
|
150
|
+
message: plan.prunable.length === 1
|
|
151
|
+
? `Prune workspace ${plan.prunable[0].name}?`
|
|
152
|
+
: `Prune these ${plan.prunable.length} workspaces?`,
|
|
153
|
+
default: false,
|
|
154
|
+
});
|
|
155
|
+
if (!confirmed) {
|
|
156
|
+
(0, logger_1.logInfo)('Prune cancelled');
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
let deleted = 0;
|
|
161
|
+
for (const c of plan.prunable) {
|
|
162
|
+
let target;
|
|
163
|
+
try {
|
|
164
|
+
// Re-validate through the same choke point delete uses: enforces the
|
|
165
|
+
// name allowlist and pins the path inside WORKSPACES_DIR.
|
|
166
|
+
target = (0, validation_1.safeWorkspacePath)(c.name);
|
|
167
|
+
}
|
|
168
|
+
catch (error) {
|
|
169
|
+
(0, logger_1.logError)(error instanceof Error ? error.message : `Invalid workspace name "${c.name}"`);
|
|
170
|
+
continue;
|
|
171
|
+
}
|
|
172
|
+
try {
|
|
173
|
+
await fs.rm(target, { recursive: true, force: true });
|
|
174
|
+
(0, logger_1.logSuccess)(`Pruned "${(0, colors_1.colorize)(c.name, 'cyan')}"`);
|
|
175
|
+
deleted++;
|
|
176
|
+
}
|
|
177
|
+
catch (error) {
|
|
178
|
+
(0, logger_1.logError)(`Failed to prune "${c.name}"`);
|
|
179
|
+
if (error instanceof Error)
|
|
180
|
+
(0, logger_1.logError)(error.message);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
(0, logger_1.logStep)(`Pruned ${deleted} of ${plan.prunable.length} workspace(s).`);
|
|
184
|
+
}
|
|
185
|
+
catch (error) {
|
|
186
|
+
if (json)
|
|
187
|
+
(0, output_1.outputJsonError)(error instanceof Error ? error.message : 'prune failed');
|
|
188
|
+
else
|
|
189
|
+
(0, logger_1.logError)(error instanceof Error ? error.message : 'prune failed');
|
|
190
|
+
process.exit(1);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
function ageLabel(c) {
|
|
194
|
+
const base = c.ageDays === 1 ? '1 day' : `${c.ageDays} days`;
|
|
195
|
+
return c.fromSession ? `${base} since last session` : `${base} since created, no sessions`;
|
|
196
|
+
}
|
package/dist/program.js
CHANGED
|
@@ -70,6 +70,7 @@ const create_1 = require("./commands/create");
|
|
|
70
70
|
const list_1 = require("./commands/list");
|
|
71
71
|
const update_1 = require("./commands/update");
|
|
72
72
|
const delete_1 = require("./commands/delete");
|
|
73
|
+
const prune_1 = require("./commands/prune");
|
|
73
74
|
const sync_1 = require("./commands/sync");
|
|
74
75
|
const status_1 = require("./commands/status");
|
|
75
76
|
const diff_1 = require("./commands/diff");
|
|
@@ -96,6 +97,7 @@ const reflect_1 = require("./commands/reflect");
|
|
|
96
97
|
(0, list_1.registerListCommand)(exports.program);
|
|
97
98
|
(0, update_1.registerUpdateCommand)(exports.program);
|
|
98
99
|
(0, delete_1.registerDeleteCommand)(exports.program);
|
|
100
|
+
(0, prune_1.registerPruneCommand)(exports.program);
|
|
99
101
|
(0, sync_1.registerSyncCommand)(exports.program);
|
|
100
102
|
(0, status_1.registerStatusCommand)(exports.program);
|
|
101
103
|
(0, diff_1.registerDiffCommand)(exports.program);
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.toCandidate = toCandidate;
|
|
4
|
+
exports.isStale = isStale;
|
|
5
|
+
exports.protectionReason = protectionReason;
|
|
6
|
+
exports.planPrune = planPrune;
|
|
7
|
+
const MS_PER_DAY = 24 * 60 * 60 * 1000;
|
|
8
|
+
/** Build a dated candidate for a workspace. `now` is injected for testability. */
|
|
9
|
+
function toCandidate(ws, now) {
|
|
10
|
+
const referenceAt = ws.lastActiveAt > 0 ? ws.lastActiveAt : ws.createdAt;
|
|
11
|
+
const undatable = !(referenceAt > 0);
|
|
12
|
+
const ageDays = undatable ? 0 : Math.floor((now - referenceAt) / MS_PER_DAY);
|
|
13
|
+
return {
|
|
14
|
+
name: ws.name,
|
|
15
|
+
path: ws.path,
|
|
16
|
+
repoDirNames: ws.repoDirNames,
|
|
17
|
+
referenceAt,
|
|
18
|
+
fromSession: ws.lastActiveAt > 0,
|
|
19
|
+
ageDays,
|
|
20
|
+
undatable,
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* A workspace is a prune candidate when it is datable and its age meets the
|
|
25
|
+
* threshold. Undatable workspaces are never auto-selected — we won't delete
|
|
26
|
+
* something we can't put a date on. A future `referenceAt` (clock skew) yields
|
|
27
|
+
* a negative age and is therefore not stale.
|
|
28
|
+
*/
|
|
29
|
+
function isStale(c, days) {
|
|
30
|
+
return !c.undatable && c.ageDays >= days;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Why a stale workspace should be held back from deletion, or null if it's safe.
|
|
34
|
+
* Unsafe = any repo has uncommitted changes (`!clean`) or unpushed commits
|
|
35
|
+
* (`ahead > 0`). With `includeDirty`, nothing is held back. An empty workspace
|
|
36
|
+
* (no repos) is always safe.
|
|
37
|
+
*/
|
|
38
|
+
function protectionReason(statuses, includeDirty) {
|
|
39
|
+
if (includeDirty)
|
|
40
|
+
return null;
|
|
41
|
+
const dirty = statuses.filter((s) => !s.clean).length;
|
|
42
|
+
const unpushed = statuses.filter((s) => s.ahead > 0).length;
|
|
43
|
+
if (dirty === 0 && unpushed === 0)
|
|
44
|
+
return null;
|
|
45
|
+
const parts = [];
|
|
46
|
+
if (dirty > 0)
|
|
47
|
+
parts.push(`${dirty} repo${dirty === 1 ? '' : 's'} with uncommitted changes`);
|
|
48
|
+
if (unpushed > 0)
|
|
49
|
+
parts.push(`${unpushed} repo${unpushed === 1 ? '' : 's'} with unpushed commits`);
|
|
50
|
+
return parts.join(', ');
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Partition stale candidates into prunable vs. protected, given a resolver that
|
|
54
|
+
* returns each workspace's per-repo git status. The resolver is only invoked
|
|
55
|
+
* for workspaces that actually have repos, so empty stale workspaces cost no git
|
|
56
|
+
* calls. Injecting the resolver keeps this function pure and unit-testable.
|
|
57
|
+
*/
|
|
58
|
+
async function planPrune(staleCandidates, getStatuses, includeDirty) {
|
|
59
|
+
const prunable = [];
|
|
60
|
+
const protectedList = [];
|
|
61
|
+
for (const c of staleCandidates) {
|
|
62
|
+
const statuses = c.repoDirNames.length > 0 ? await getStatuses(c) : [];
|
|
63
|
+
const reason = protectionReason(statuses, includeDirty);
|
|
64
|
+
if (reason)
|
|
65
|
+
protectedList.push({ candidate: c, reason });
|
|
66
|
+
else
|
|
67
|
+
prunable.push(c);
|
|
68
|
+
}
|
|
69
|
+
return { prunable, protected: protectedList };
|
|
70
|
+
}
|
package/package.json
CHANGED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Emit GitHub Release notes for a given version by extracting that version's
|
|
3
|
+
// section from CHANGELOG.md (newest-first "Keep a Changelog" format), prepended
|
|
4
|
+
// with an install snippet and followed by a compare link to the previous tag.
|
|
5
|
+
//
|
|
6
|
+
// Usage: node scripts/release-notes.mjs <version> [repo]
|
|
7
|
+
// repo defaults to $GITHUB_REPOSITORY or "me-public/nemus".
|
|
8
|
+
//
|
|
9
|
+
// If the version has no CHANGELOG section, prints a minimal fallback (so a
|
|
10
|
+
// release is never blocked on a missing entry). Dependency-free; prints to
|
|
11
|
+
// stdout so the workflow can redirect it into `gh release --notes-file`.
|
|
12
|
+
import { readFileSync } from 'node:fs';
|
|
13
|
+
|
|
14
|
+
const version = (process.argv[2] || '').trim();
|
|
15
|
+
const repo = (process.argv[3] || process.env.GITHUB_REPOSITORY || 'me-public/nemus').trim();
|
|
16
|
+
if (!version) {
|
|
17
|
+
process.stderr.write('usage: release-notes.mjs <version> [repo]\n');
|
|
18
|
+
process.exit(2);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const install = `\`\`\`bash\nnpm install -g @nemus-cli/nemus@${version}\n\`\`\``;
|
|
22
|
+
|
|
23
|
+
let body = '';
|
|
24
|
+
let prev = null;
|
|
25
|
+
try {
|
|
26
|
+
const changelog = readFileSync(new URL('../CHANGELOG.md', import.meta.url), 'utf8');
|
|
27
|
+
const lines = changelog.split('\n');
|
|
28
|
+
// Collect version headers in file order (newest first) with their line index.
|
|
29
|
+
const heads = [];
|
|
30
|
+
lines.forEach((line, i) => {
|
|
31
|
+
const m = line.match(/^## \[(\d+\.\d+\.\d+)\]/);
|
|
32
|
+
if (m) heads.push({ version: m[1], line: i });
|
|
33
|
+
});
|
|
34
|
+
const idx = heads.findIndex((h) => h.version === version);
|
|
35
|
+
if (idx !== -1) {
|
|
36
|
+
const start = heads[idx].line + 1;
|
|
37
|
+
const end = idx + 1 < heads.length ? heads[idx + 1].line : lines.length;
|
|
38
|
+
body = lines.slice(start, end).join('\n').trim();
|
|
39
|
+
// Newest-first: the NEXT header in the file is the previous release.
|
|
40
|
+
prev = idx + 1 < heads.length ? heads[idx + 1].version : null;
|
|
41
|
+
}
|
|
42
|
+
} catch {
|
|
43
|
+
// fall through to fallback
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const compare = prev
|
|
47
|
+
? `[\`v${prev}...v${version}\`](https://github.com/${repo}/compare/v${prev}...v${version})`
|
|
48
|
+
: `[\`v${version}\`](https://github.com/${repo}/releases/tag/v${version})`;
|
|
49
|
+
|
|
50
|
+
const parts = [`## Nemus v${version}`, '', install];
|
|
51
|
+
if (body) parts.push('', body);
|
|
52
|
+
parts.push('', '---', '', `**Full diff:** ${compare} · [Full changelog](https://github.com/${repo}/blob/main/CHANGELOG.md)`);
|
|
53
|
+
|
|
54
|
+
process.stdout.write(parts.join('\n') + '\n');
|
package/skills/config.md
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: config
|
|
3
|
+
description: Read and write Nemus configuration non-interactively (get/set/unset/list/path/edit)
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
Non-interactive configuration in `~/.nemus/config.json` (no wizard):
|
|
7
|
+
```bash
|
|
8
|
+
nemus config list # all keys + resolved values (alias: ls; --json)
|
|
9
|
+
nemus config get <key> # print one value (--json)
|
|
10
|
+
nemus config set <key> <value> # set + validate + persist
|
|
11
|
+
nemus config unset <key> # revert a key to its default
|
|
12
|
+
nemus config path # print the config file path
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
- Values are validated/coerced per key: booleans accept `true/false/yes/no/on/off/1/0`; enums (e.g. `cloneProtocol=ssh|https`) are checked. Invalid key/value exits non-zero.
|
|
16
|
+
- Common keys: `workspacesDir`, `githubOrg`, `cloneProtocol`, `aiAgent`, `primaryAgent`. Run `nemus config list` to see all.
|
|
17
|
+
- For a guided first-time setup, use `nemus configure` instead.
|
package/skills/nemus/SKILL.md
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: nemus
|
|
3
3
|
description: Manage multi-repo development workspaces — create, sync, branch, diff, clone, archive, analyze dependencies, run commands across repos, check status, clean up, delete, list org repos, search repos, list suites, remove repo, cache, suite management, sessions, history, generate docs, configure, MCP server, AI prompt. Use when working with workspaces, repos, branches, git operations across multiple repos, or the `nemus` CLI tool. NEVER use `git clone` directly — always use `nemus update` to add repos and `nemus create` to create workspaces.
|
|
4
|
-
bashPattern: "\\bnemus\\s+(create|list|update|delete|sync|status|diff|run|go|doctor|analyze-deps|history|cleanup|remove-repo|archive|sessions|generate-docs|configure|configure-claude|ghq-status|tui|dashboard|dash|branch|suite|cache|mcp|--)\\b"
|
|
4
|
+
bashPattern: "\\bnemus\\s+(create|list|update|delete|prune|sync|status|diff|run|go|doctor|analyze-deps|reflect|retro|history|cleanup|remove-repo|archive|sessions|save-context|ctx|generate-docs|configure|config|configure-claude|ghq-status|completion|tui|dashboard|dash|branch|suite|cache|mcp|--)\\b"
|
|
5
5
|
---
|
|
6
6
|
|
|
7
7
|
# Nemus
|
|
@@ -33,6 +33,7 @@ Global flags: `-f/--force-refresh` (skip repo cache), `-y/--yes` (skip prompts),
|
|
|
33
33
|
| Create new workspace | [create-workspace](references/create-workspace.md) | `nemus create` | `c` |
|
|
34
34
|
| Add repos to workspace | [update-workspace](references/update-workspace.md) | `nemus update` | `u` |
|
|
35
35
|
| Delete workspace permanently | [delete-workspace](references/delete-workspace.md) | `nemus delete` | `d` |
|
|
36
|
+
| Prune inactive workspaces (safe) | [prune](references/prune.md) | `nemus prune` | — |
|
|
36
37
|
| Archive / unarchive workspace | [archive-workspace](references/archive-workspace.md) | `nemus archive` | `a` |
|
|
37
38
|
| List all workspaces | [list-workspaces](references/list-workspaces.md) | `nemus list` | `l` |
|
|
38
39
|
| Navigate to workspace | [go](references/go.md) | `nemus go [name]` | — |
|
|
@@ -88,14 +89,18 @@ Global flags: `-f/--force-refresh` (skip repo cache), `-y/--yes` (skip prompts),
|
|
|
88
89
|
| Resume Claude session | [sessions](references/sessions.md) | `nemus sessions` | `ses` |
|
|
89
90
|
| Agent management dashboard | [dashboard](references/dashboard.md) | `nemus dashboard` | `dash` |
|
|
90
91
|
| View operation history | [history](references/history.md) | `nemus history` | `h` |
|
|
92
|
+
| Save progress/context to a workspace | [save-context](references/save-context.md) | `nemus save-context` | `ctx` |
|
|
93
|
+
| Retrospective on recent sessions | [reflect](references/reflect.md) | `nemus reflect` | `retro` |
|
|
91
94
|
|
|
92
95
|
### Configuration & MCP
|
|
93
96
|
|
|
94
97
|
| Intent | Reference | CLI |
|
|
95
98
|
|---|---|---|
|
|
96
|
-
| Configure Nemus | [configure](references/configure.md) | `nemus configure` |
|
|
99
|
+
| Configure Nemus (interactive wizard) | [configure](references/configure.md) | `nemus configure` |
|
|
100
|
+
| Get/set config non-interactively | [config](references/config.md) | `nemus config get\|set\|list\|edit` |
|
|
97
101
|
| Configure Claude integration | [configure-claude](references/configure-claude.md) | `nemus configure-claude` |
|
|
98
102
|
| Check ghq status | [ghq-status](references/ghq-status.md) | `nemus ghq-status` |
|
|
103
|
+
| Shell completions (bash/zsh/fish) | [completion](references/completion.md) | `nemus completion <shell>` |
|
|
99
104
|
| Install / manage MCP server | [mcp](references/mcp.md) | `nemus mcp install\|status\|upgrade\|uninstall` |
|
|
100
105
|
|
|
101
106
|
### AI Assistant & TUI
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
# Shell Completions
|
|
2
|
+
|
|
3
|
+
`nemus completion <shell>` prints a completion script for `bash`, `zsh`, or
|
|
4
|
+
`fish`. It completes subcommands and, for workspace-scoped commands, live
|
|
5
|
+
workspace names (the script calls back into `nemus completion --workspaces`, so
|
|
6
|
+
completions stay fresh without regenerating). Registered for both `nemus` and
|
|
7
|
+
`nem`.
|
|
8
|
+
|
|
9
|
+
Install (pick your shell):
|
|
10
|
+
```bash
|
|
11
|
+
# bash
|
|
12
|
+
nemus completion bash > /etc/bash_completion.d/nemus # or: >> ~/.bashrc
|
|
13
|
+
|
|
14
|
+
# zsh — save on your $fpath as _nemus
|
|
15
|
+
nemus completion zsh > "${fpath[1]}/_nemus"
|
|
16
|
+
|
|
17
|
+
# fish
|
|
18
|
+
nemus completion fish > ~/.config/fish/completions/nemus.fish
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
Then restart the shell (or `source` the file). Requires a shell argument —
|
|
22
|
+
one of `bash|zsh|fish`.
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
# Config — non-interactive configuration
|
|
2
|
+
|
|
3
|
+
`nemus config` reads and writes `~/.nemus/config.json` without the interactive
|
|
4
|
+
`nemus configure` wizard. Ideal for scripting and for setting one value.
|
|
5
|
+
|
|
6
|
+
```bash
|
|
7
|
+
nemus config list # show all keys + resolved values (alias: ls)
|
|
8
|
+
nemus config list --json # machine-readable
|
|
9
|
+
nemus config get <key> # print one value (--json for structured)
|
|
10
|
+
nemus config set <key> <value> # set + validate + persist
|
|
11
|
+
nemus config unset <key> # remove a key (revert to default)
|
|
12
|
+
nemus config path # print the config file path
|
|
13
|
+
nemus config edit # open the file in $VISUAL/$EDITOR (needs a TTY)
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
Values are validated and coerced per key: booleans accept
|
|
17
|
+
`true/false/yes/no/on/off/1/0`; enums (e.g. `cloneProtocol` = `ssh|https`) are
|
|
18
|
+
checked. An unknown key or invalid value exits non-zero with a clear message.
|
|
19
|
+
|
|
20
|
+
Common keys: `workspacesDir`, `githubOrg`, `cloneProtocol`, `aiAgent`,
|
|
21
|
+
`primaryAgent`, `autoLaunchClaude`, `generateClaudeContext`, `installMcp`.
|
|
22
|
+
Run `nemus config list` to see them all.
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
# examples
|
|
26
|
+
nemus config set githubOrg acme
|
|
27
|
+
nemus config set cloneProtocol https
|
|
28
|
+
nemus config get workspacesDir --json
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
Pairs well with `--quiet` for scripts. For a guided first-time setup, use
|
|
32
|
+
`nemus configure` instead.
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
# Prune Inactive Workspaces
|
|
2
|
+
|
|
3
|
+
Bulk-delete workspaces with no recent activity. **Safe by default** — it holds
|
|
4
|
+
back any workspace with uncommitted or unpushed work.
|
|
5
|
+
|
|
6
|
+
1. **Always preview first.** Show the user exactly what would be deleted (and
|
|
7
|
+
what is protected) before removing anything:
|
|
8
|
+
```bash
|
|
9
|
+
nemus prune --days <n> --dry-run
|
|
10
|
+
```
|
|
11
|
+
A workspace is *stale* when its most recent agent session — or, if it has no
|
|
12
|
+
session, its `createdAt` — is older than `--days` (default 30). Workspaces
|
|
13
|
+
with no date at all are never selected.
|
|
14
|
+
|
|
15
|
+
2. **Review the two lists.** `prune` prints:
|
|
16
|
+
- **Protected** — stale workspaces skipped because a repo has uncommitted
|
|
17
|
+
changes or unpushed commits (with the reason). These are NOT deleted.
|
|
18
|
+
- **Prunable** — stale workspaces that are safe to remove.
|
|
19
|
+
|
|
20
|
+
3. **Confirm with the user, then prune.** This permanently deletes the
|
|
21
|
+
workspace directories and every cloned repo inside them:
|
|
22
|
+
```bash
|
|
23
|
+
nemus prune --days <n> # prompts for confirmation (default: No)
|
|
24
|
+
nemus prune --days <n> --yes # non-interactive (only when the user is sure)
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
4. **`--json`** gives a machine-readable plan (`{ prunable, protected }`) and,
|
|
28
|
+
like `--dry-run`, never deletes.
|
|
29
|
+
|
|
30
|
+
Deletions go through the same validated path as `nemus delete` (name allowlist +
|
|
31
|
+
path pinned inside the workspaces directory).
|
|
32
|
+
|
|
33
|
+
## Flags
|
|
34
|
+
|
|
35
|
+
| Flag | Short | Description |
|
|
36
|
+
|---|---|---|
|
|
37
|
+
| `--days <n>` | `-d` | Stale after N days of inactivity (default 30) |
|
|
38
|
+
| `--dry-run` | | Show the plan without deleting anything |
|
|
39
|
+
| `--json` | | Output the plan as JSON (never deletes) |
|
|
40
|
+
| `--yes` | `-y` | Skip the confirmation prompt |
|
|
41
|
+
| `--include-dirty` | | Also prune workspaces with uncommitted/unpushed work (overrides the safety guard — use with care) |
|
|
42
|
+
|
|
43
|
+
> **Only** pass `--include-dirty` when the user has explicitly accepted losing
|
|
44
|
+
> uncommitted/unpushed work in the protected workspaces.
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
# Reflect — retrospective on recent sessions
|
|
2
|
+
|
|
3
|
+
`nemus reflect` (alias `retro`) reads your recent workspaces' agent session
|
|
4
|
+
transcripts and asks *your own* configured agent (claude/pi/opencode — no API key
|
|
5
|
+
of Nemus's) to recommend concrete setup improvements: skills to add, missing
|
|
6
|
+
`AGENTS.md`/context rules, missing connectivity/smoke tests, and prompt/workflow
|
|
7
|
+
habits — each with a priority and an example.
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
nemus reflect # analyze the most recent workspaces (default 10)
|
|
11
|
+
nemus reflect --limit 20 # widen the window
|
|
12
|
+
nemus reflect --workspace <name> # analyze a single workspace
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
Output / sharing:
|
|
16
|
+
```bash
|
|
17
|
+
nemus reflect --json # structured report ({ ok:false, error } on failure)
|
|
18
|
+
nemus reflect --markdown > reflection.md # paste into an issue/PR
|
|
19
|
+
nemus reflect --group-by kind # group recommendations by kind (default: priority)
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
Review saved reports (each run is saved under `~/.nemus/reflect/` unless
|
|
23
|
+
`--no-save`):
|
|
24
|
+
```bash
|
|
25
|
+
nemus reflect history # list saved reports
|
|
26
|
+
nemus reflect show [id] # show one (id or id-prefix; defaults to latest)
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
## Flags
|
|
30
|
+
|
|
31
|
+
| Flag | Description |
|
|
32
|
+
|---|---|
|
|
33
|
+
| `--limit <n>` / `-n` | How many recent workspaces to analyze (default 10) |
|
|
34
|
+
| `--workspace <name>` / `-w` | Analyze a single workspace (ignores `--limit`) |
|
|
35
|
+
| `--json` | Structured JSON report to stdout |
|
|
36
|
+
| `--markdown` | Markdown report to stdout |
|
|
37
|
+
| `--group-by <how>` | `priority` (default) or `kind` |
|
|
38
|
+
| `--no-save` | Don't save the report to `~/.nemus/reflect/` |
|
|
39
|
+
| `--model` / `--thinking` | Judge model / pi thinking-level overrides |
|
|
40
|
+
| `--dry-run` | Print the assembled corpus + judge prompt without calling the agent |
|
|
41
|
+
|
|
42
|
+
Read-only and safe — it analyzes transcripts and prints advice; it changes no
|
|
43
|
+
repos. Use it to coach setup, not to modify anything.
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
# Save Context
|
|
2
|
+
|
|
3
|
+
`nemus save-context` (alias `ctx`) writes a progress summary to the workspace's
|
|
4
|
+
`CONTEXT.md`, so work survives `/clear` or a new session. Read `CONTEXT.md` back
|
|
5
|
+
at the start of a session to resume. The workspace defaults to the current
|
|
6
|
+
directory; pass `-w` to target another.
|
|
7
|
+
|
|
8
|
+
```bash
|
|
9
|
+
nemus save-context -m "…" # save to the current workspace
|
|
10
|
+
nemus save-context -w <name> -m "…" # target a specific workspace
|
|
11
|
+
nemus save-context # interactive: prompts for the summary
|
|
12
|
+
nemus save-context -f notes.md --append # read from a file, append (don't replace)
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
Use it to capture: what was done, what's in progress, key decisions, and the
|
|
16
|
+
next steps — before a context reset or when handing off.
|
|
17
|
+
|
|
18
|
+
## Flags
|
|
19
|
+
|
|
20
|
+
| Flag | Short | Description |
|
|
21
|
+
|---|---|---|
|
|
22
|
+
| `--workspace <name>` | `-w` | Workspace name (default: current directory) |
|
|
23
|
+
| `--message <text>` | `-m` | Summary text to save (skips the prompt) |
|
|
24
|
+
| `--file <path>` | `-f` | Read the summary from a file |
|
|
25
|
+
| `--append` | | Append to existing context instead of replacing |
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: prune-workspaces
|
|
3
|
+
description: Bulk-delete workspaces with no recent activity, safe by default (protects uncommitted/unpushed work)
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
Preview first — never delete without showing the user the plan:
|
|
7
|
+
```bash
|
|
8
|
+
nemus prune --days 30 --dry-run
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
Then prune after confirming with the user:
|
|
12
|
+
```bash
|
|
13
|
+
nemus prune --days 30 # prompts (default: No)
|
|
14
|
+
nemus prune --days 30 --yes # non-interactive — only when the user is sure
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
- **Stale** = no agent session (or, failing that, no `createdAt`) in the last N
|
|
18
|
+
days (`--days`, default 30). Undatable workspaces are never selected.
|
|
19
|
+
- **Safe by default:** workspaces with uncommitted or unpushed changes are
|
|
20
|
+
**protected** and listed with the reason — not deleted. `--include-dirty`
|
|
21
|
+
overrides this (only with explicit user consent to lose that work).
|
|
22
|
+
- `--json` and `--dry-run` never delete.
|
|
23
|
+
- Deletion is permanent — repos must be re-cloned. Always confirm first.
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: reflect
|
|
3
|
+
description: Retrospective on recent agent sessions — get concrete tips to improve skills, context, and prompts
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
Analyze recent workspaces' agent sessions and get setup improvement tips (read-only; changes no repos):
|
|
7
|
+
```bash
|
|
8
|
+
nemus reflect # most recent workspaces (default 10)
|
|
9
|
+
nemus reflect --workspace <name> # a single workspace
|
|
10
|
+
nemus reflect --markdown > reflection.md # shareable report
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Review saved reports (saved under `~/.nemus/reflect/` unless `--no-save`):
|
|
14
|
+
```bash
|
|
15
|
+
nemus reflect history # list past reports
|
|
16
|
+
nemus reflect show [id] # show one (defaults to latest)
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
- Uses *your own* configured agent (claude/pi/opencode) as the judge — no API key of Nemus's.
|
|
20
|
+
- `--json` / `--markdown` for machine or shareable output; `--group-by kind|priority`.
|
|
21
|
+
- Safe: it reads transcripts and prints advice, nothing is modified.
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
import { Command } from 'commander';
|
|
2
|
+
import * as fs from 'fs/promises';
|
|
3
|
+
import { safeWorkspacePath } from '../utils/validation';
|
|
4
|
+
import { listWorkspaces } from '../utils/workspace-meta';
|
|
5
|
+
import { getWorkspaceSessions } from '../utils/claude-sessions';
|
|
6
|
+
import { getAllReposStatus } from '../utils/git-status';
|
|
7
|
+
import { logInfo, logSuccess, logError, logWarning, logStep } from '../utils/logger';
|
|
8
|
+
import { colorize } from '../utils/colors';
|
|
9
|
+
import { confirm } from '../utils/prompt';
|
|
10
|
+
import { getGlobalOpts } from '../utils/command-helpers';
|
|
11
|
+
import { outputJson, outputJsonError } from '../utils/output';
|
|
12
|
+
import {
|
|
13
|
+
toCandidate,
|
|
14
|
+
isStale,
|
|
15
|
+
planPrune,
|
|
16
|
+
type WorkspaceForPrune,
|
|
17
|
+
type PruneCandidate,
|
|
18
|
+
} from '../utils/prune';
|
|
19
|
+
|
|
20
|
+
const DEFAULT_DAYS = 30;
|
|
21
|
+
|
|
22
|
+
export function registerPruneCommand(parent: Command) {
|
|
23
|
+
parent
|
|
24
|
+
.command('prune')
|
|
25
|
+
.description('Delete workspaces with no recent activity (safe by default)')
|
|
26
|
+
.option('-d, --days <n>', `Consider a workspace stale after N days of inactivity (default ${DEFAULT_DAYS})`)
|
|
27
|
+
.option('--include-dirty', 'Also prune workspaces with uncommitted/unpushed changes (default: protected)')
|
|
28
|
+
.option('--dry-run', 'Show what would be pruned without deleting anything')
|
|
29
|
+
.option('-y, --yes', 'Skip the confirmation prompt')
|
|
30
|
+
.option('--json', 'Output the prune plan as JSON (never deletes)')
|
|
31
|
+
.action(async (opts, cmd) => {
|
|
32
|
+
const globalOpts = getGlobalOpts(cmd);
|
|
33
|
+
await handlePrune({ ...opts, ...globalOpts });
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function parseDays(raw: unknown): number | null {
|
|
38
|
+
if (raw === undefined) return DEFAULT_DAYS;
|
|
39
|
+
const n = Number(raw);
|
|
40
|
+
if (!Number.isFinite(n) || n < 0) return null;
|
|
41
|
+
return Math.floor(n);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export async function handlePrune(opts: {
|
|
45
|
+
days?: string;
|
|
46
|
+
includeDirty?: boolean;
|
|
47
|
+
dryRun?: boolean;
|
|
48
|
+
yes?: boolean;
|
|
49
|
+
json?: boolean;
|
|
50
|
+
}) {
|
|
51
|
+
const json = !!opts.json;
|
|
52
|
+
const days = parseDays(opts.days);
|
|
53
|
+
if (days === null) {
|
|
54
|
+
if (json) outputJsonError('--days must be a non-negative number');
|
|
55
|
+
else logError('--days must be a non-negative number');
|
|
56
|
+
process.exit(1);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
try {
|
|
60
|
+
const [workspaces, sessions] = await Promise.all([listWorkspaces(), getWorkspaceSessions()]);
|
|
61
|
+
const sessionMap = new Map(sessions.map((s) => [s.workspaceName, s]));
|
|
62
|
+
const now = Date.now();
|
|
63
|
+
|
|
64
|
+
const candidates: PruneCandidate[] = workspaces.map((ws) => {
|
|
65
|
+
const session = sessionMap.get(ws.name);
|
|
66
|
+
const createdRaw = ws.metadata?.createdAt ? Date.parse(ws.metadata.createdAt) : NaN;
|
|
67
|
+
const forPrune: WorkspaceForPrune = {
|
|
68
|
+
name: ws.name,
|
|
69
|
+
path: ws.path,
|
|
70
|
+
repoDirNames: (ws.metadata?.repositories ?? []).map((r) => r.directoryName),
|
|
71
|
+
lastActiveAt: session ? session.lastActiveAt.getTime() : 0,
|
|
72
|
+
createdAt: Number.isFinite(createdRaw) ? createdRaw : 0,
|
|
73
|
+
};
|
|
74
|
+
return toCandidate(forPrune, now);
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
const stale = candidates.filter((c) => isStale(c, days));
|
|
78
|
+
|
|
79
|
+
if (stale.length === 0) {
|
|
80
|
+
if (json) {
|
|
81
|
+
outputJson({ ok: true, days, prunable: [], protected: [], scanned: workspaces.length });
|
|
82
|
+
} else {
|
|
83
|
+
logInfo(`No workspaces inactive for ${days}+ days (scanned ${workspaces.length}).`);
|
|
84
|
+
}
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// Compute the plan. The git safety check only runs for stale workspaces.
|
|
89
|
+
const plan = await planPrune(
|
|
90
|
+
stale,
|
|
91
|
+
(c) => getAllReposStatus(c.path, c.repoDirNames, 3),
|
|
92
|
+
!!opts.includeDirty,
|
|
93
|
+
);
|
|
94
|
+
|
|
95
|
+
if (json) {
|
|
96
|
+
outputJson({
|
|
97
|
+
ok: true,
|
|
98
|
+
days,
|
|
99
|
+
scanned: workspaces.length,
|
|
100
|
+
prunable: plan.prunable.map((c) => ({ name: c.name, path: c.path, ageDays: c.ageDays, repos: c.repoDirNames.length })),
|
|
101
|
+
protected: plan.protected.map((p) => ({ name: p.candidate.name, ageDays: p.candidate.ageDays, reason: p.reason })),
|
|
102
|
+
});
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// Human report.
|
|
107
|
+
console.log('\n' + '='.repeat(60));
|
|
108
|
+
console.log(colorize(`Prune — workspaces inactive for ${days}+ days`, 'bright'));
|
|
109
|
+
console.log('='.repeat(60) + '\n');
|
|
110
|
+
|
|
111
|
+
if (plan.protected.length > 0) {
|
|
112
|
+
logWarning(`Protected (${plan.protected.length}) — skipped due to unsaved work:`);
|
|
113
|
+
for (const p of plan.protected) {
|
|
114
|
+
console.log(` ${colorize('•', 'yellow')} ${colorize(p.candidate.name, 'cyan')} — ${p.reason} ${colorize(`(${ageLabel(p.candidate)})`, 'gray')}`);
|
|
115
|
+
}
|
|
116
|
+
console.log('');
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
if (plan.prunable.length === 0) {
|
|
120
|
+
logInfo('Nothing safe to prune.');
|
|
121
|
+
if (plan.protected.length > 0) logInfo('Re-run with --include-dirty to include the protected ones (careful).');
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
console.log(`${colorize('Prunable', 'bright')} (${plan.prunable.length}):`);
|
|
126
|
+
for (const c of plan.prunable) {
|
|
127
|
+
const repoLabel = c.repoDirNames.length === 1 ? '1 repo' : `${c.repoDirNames.length} repos`;
|
|
128
|
+
console.log(` ${colorize('✗', 'red')} ${colorize(c.name, 'cyan')} ${colorize(`(${ageLabel(c)}, ${repoLabel})`, 'gray')}`);
|
|
129
|
+
}
|
|
130
|
+
console.log('');
|
|
131
|
+
|
|
132
|
+
if (opts.dryRun) {
|
|
133
|
+
logInfo(`Dry run — nothing deleted. ${plan.prunable.length} workspace(s) would be pruned.`);
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
logWarning('This permanently deletes the selected workspaces and every cloned repo inside them!');
|
|
138
|
+
|
|
139
|
+
if (!opts.yes) {
|
|
140
|
+
const confirmed = await confirm({
|
|
141
|
+
message: plan.prunable.length === 1
|
|
142
|
+
? `Prune workspace ${plan.prunable[0].name}?`
|
|
143
|
+
: `Prune these ${plan.prunable.length} workspaces?`,
|
|
144
|
+
default: false,
|
|
145
|
+
});
|
|
146
|
+
if (!confirmed) {
|
|
147
|
+
logInfo('Prune cancelled');
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
let deleted = 0;
|
|
153
|
+
for (const c of plan.prunable) {
|
|
154
|
+
let target: string;
|
|
155
|
+
try {
|
|
156
|
+
// Re-validate through the same choke point delete uses: enforces the
|
|
157
|
+
// name allowlist and pins the path inside WORKSPACES_DIR.
|
|
158
|
+
target = safeWorkspacePath(c.name);
|
|
159
|
+
} catch (error) {
|
|
160
|
+
logError(error instanceof Error ? error.message : `Invalid workspace name "${c.name}"`);
|
|
161
|
+
continue;
|
|
162
|
+
}
|
|
163
|
+
try {
|
|
164
|
+
await fs.rm(target, { recursive: true, force: true });
|
|
165
|
+
logSuccess(`Pruned "${colorize(c.name, 'cyan')}"`);
|
|
166
|
+
deleted++;
|
|
167
|
+
} catch (error) {
|
|
168
|
+
logError(`Failed to prune "${c.name}"`);
|
|
169
|
+
if (error instanceof Error) logError(error.message);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
logStep(`Pruned ${deleted} of ${plan.prunable.length} workspace(s).`);
|
|
173
|
+
} catch (error) {
|
|
174
|
+
if (json) outputJsonError(error instanceof Error ? error.message : 'prune failed');
|
|
175
|
+
else logError(error instanceof Error ? error.message : 'prune failed');
|
|
176
|
+
process.exit(1);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function ageLabel(c: PruneCandidate): string {
|
|
181
|
+
const base = c.ageDays === 1 ? '1 day' : `${c.ageDays} days`;
|
|
182
|
+
return c.fromSession ? `${base} since last session` : `${base} since created, no sessions`;
|
|
183
|
+
}
|
package/src/program.ts
CHANGED
|
@@ -39,6 +39,7 @@ import { registerCreateCommand } from './commands/create';
|
|
|
39
39
|
import { registerListCommand } from './commands/list';
|
|
40
40
|
import { registerUpdateCommand } from './commands/update';
|
|
41
41
|
import { registerDeleteCommand } from './commands/delete';
|
|
42
|
+
import { registerPruneCommand } from './commands/prune';
|
|
42
43
|
import { registerSyncCommand } from './commands/sync';
|
|
43
44
|
import { registerStatusCommand } from './commands/status';
|
|
44
45
|
import { registerDiffCommand } from './commands/diff';
|
|
@@ -66,6 +67,7 @@ registerCreateCommand(program);
|
|
|
66
67
|
registerListCommand(program);
|
|
67
68
|
registerUpdateCommand(program);
|
|
68
69
|
registerDeleteCommand(program);
|
|
70
|
+
registerPruneCommand(program);
|
|
69
71
|
registerSyncCommand(program);
|
|
70
72
|
registerStatusCommand(program);
|
|
71
73
|
registerDiffCommand(program);
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { describe, it, expect } from 'vitest';
|
|
2
|
+
import {
|
|
3
|
+
toCandidate,
|
|
4
|
+
isStale,
|
|
5
|
+
protectionReason,
|
|
6
|
+
planPrune,
|
|
7
|
+
type WorkspaceForPrune,
|
|
8
|
+
type PruneCandidate,
|
|
9
|
+
} from './prune';
|
|
10
|
+
import type { GitStatus } from '../types';
|
|
11
|
+
|
|
12
|
+
const NOW = Date.parse('2026-09-01T00:00:00Z');
|
|
13
|
+
const daysAgo = (n: number) => NOW - n * 24 * 60 * 60 * 1000;
|
|
14
|
+
|
|
15
|
+
function ws(over: Partial<WorkspaceForPrune> = {}): WorkspaceForPrune {
|
|
16
|
+
return { name: 'w', path: '/w', repoDirNames: [], lastActiveAt: 0, createdAt: 0, ...over };
|
|
17
|
+
}
|
|
18
|
+
function status(over: Partial<GitStatus> = {}): GitStatus {
|
|
19
|
+
return {
|
|
20
|
+
repo: 'r', branch: 'main', clean: true, ahead: 0, behind: 0,
|
|
21
|
+
modifiedFiles: 0, untrackedFiles: 0, hasRemote: true, detachedHead: false, ...over,
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
describe('toCandidate', () => {
|
|
26
|
+
it('prefers lastActive over createdAt and marks fromSession', () => {
|
|
27
|
+
const c = toCandidate(ws({ lastActiveAt: daysAgo(5), createdAt: daysAgo(40) }), NOW);
|
|
28
|
+
expect(c.fromSession).toBe(true);
|
|
29
|
+
expect(c.ageDays).toBe(5);
|
|
30
|
+
expect(c.undatable).toBe(false);
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
it('falls back to createdAt when there is no session', () => {
|
|
34
|
+
const c = toCandidate(ws({ lastActiveAt: 0, createdAt: daysAgo(40) }), NOW);
|
|
35
|
+
expect(c.fromSession).toBe(false);
|
|
36
|
+
expect(c.ageDays).toBe(40);
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
it('is undatable when neither timestamp is present', () => {
|
|
40
|
+
const c = toCandidate(ws({ lastActiveAt: 0, createdAt: 0 }), NOW);
|
|
41
|
+
expect(c.undatable).toBe(true);
|
|
42
|
+
expect(c.ageDays).toBe(0);
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
it('floors a future reference to a negative age (clock skew) without marking undatable', () => {
|
|
46
|
+
const c = toCandidate(ws({ lastActiveAt: NOW + 60_000 }), NOW);
|
|
47
|
+
expect(c.undatable).toBe(false);
|
|
48
|
+
expect(c.ageDays).toBeLessThan(0);
|
|
49
|
+
});
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
describe('isStale', () => {
|
|
53
|
+
const c = (over: Partial<WorkspaceForPrune>) => toCandidate(ws(over), NOW);
|
|
54
|
+
|
|
55
|
+
it('is true at or beyond the threshold', () => {
|
|
56
|
+
expect(isStale(c({ lastActiveAt: daysAgo(30) }), 30)).toBe(true);
|
|
57
|
+
expect(isStale(c({ lastActiveAt: daysAgo(31) }), 30)).toBe(true);
|
|
58
|
+
});
|
|
59
|
+
it('is false below the threshold', () => {
|
|
60
|
+
expect(isStale(c({ lastActiveAt: daysAgo(29) }), 30)).toBe(false);
|
|
61
|
+
});
|
|
62
|
+
it('never selects an undatable workspace', () => {
|
|
63
|
+
expect(isStale(c({ lastActiveAt: 0, createdAt: 0 }), 0)).toBe(false);
|
|
64
|
+
});
|
|
65
|
+
it('never selects a future-dated (skewed) workspace', () => {
|
|
66
|
+
expect(isStale(c({ lastActiveAt: NOW + 86_400_000 }), 0)).toBe(false);
|
|
67
|
+
});
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
describe('protectionReason', () => {
|
|
71
|
+
it('returns null for an all-clean workspace', () => {
|
|
72
|
+
expect(protectionReason([status(), status()], false)).toBeNull();
|
|
73
|
+
});
|
|
74
|
+
it('returns null for an empty workspace', () => {
|
|
75
|
+
expect(protectionReason([], false)).toBeNull();
|
|
76
|
+
});
|
|
77
|
+
it('flags uncommitted changes', () => {
|
|
78
|
+
expect(protectionReason([status({ clean: false })], false)).toBe('1 repo with uncommitted changes');
|
|
79
|
+
});
|
|
80
|
+
it('flags unpushed commits', () => {
|
|
81
|
+
expect(protectionReason([status({ ahead: 2 })], false)).toBe('1 repo with unpushed commits');
|
|
82
|
+
});
|
|
83
|
+
it('combines both reasons and pluralizes', () => {
|
|
84
|
+
expect(
|
|
85
|
+
protectionReason([status({ clean: false }), status({ clean: false }), status({ ahead: 1 })], false),
|
|
86
|
+
).toBe('2 repos with uncommitted changes, 1 repo with unpushed commits');
|
|
87
|
+
});
|
|
88
|
+
it('returns null when includeDirty overrides protection', () => {
|
|
89
|
+
expect(protectionReason([status({ clean: false, ahead: 3 })], true)).toBeNull();
|
|
90
|
+
});
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
describe('planPrune', () => {
|
|
94
|
+
const mk = (name: string, repos: string[]): PruneCandidate =>
|
|
95
|
+
toCandidate(ws({ name, path: `/w/${name}`, repoDirNames: repos, lastActiveAt: daysAgo(40) }), NOW);
|
|
96
|
+
|
|
97
|
+
it('partitions prunable vs protected and skips git calls for empty workspaces', async () => {
|
|
98
|
+
const empty = mk('empty', []);
|
|
99
|
+
const clean = mk('clean', ['a']);
|
|
100
|
+
const dirty = mk('dirty', ['b']);
|
|
101
|
+
let calls = 0;
|
|
102
|
+
const resolver = async (c: PruneCandidate): Promise<GitStatus[]> => {
|
|
103
|
+
calls++;
|
|
104
|
+
return c.name === 'dirty' ? [status({ clean: false })] : [status()];
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
const plan = await planPrune([empty, clean, dirty], resolver, false);
|
|
108
|
+
|
|
109
|
+
expect(plan.prunable.map((c) => c.name)).toEqual(['empty', 'clean']);
|
|
110
|
+
expect(plan.protected.map((p) => p.candidate.name)).toEqual(['dirty']);
|
|
111
|
+
expect(plan.protected[0].reason).toBe('1 repo with uncommitted changes');
|
|
112
|
+
expect(calls).toBe(2); // empty workspace incurred no status call
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
it('includeDirty moves everything to prunable', async () => {
|
|
116
|
+
const dirty = mk('dirty', ['b']);
|
|
117
|
+
const plan = await planPrune([dirty], async () => [status({ clean: false, ahead: 2 })], true);
|
|
118
|
+
expect(plan.prunable.map((c) => c.name)).toEqual(['dirty']);
|
|
119
|
+
expect(plan.protected).toHaveLength(0);
|
|
120
|
+
});
|
|
121
|
+
});
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
// Pure logic for `nemus prune` — deciding which workspaces are stale and which
|
|
2
|
+
// are unsafe to delete. Kept free of I/O so it can be unit-tested exhaustively;
|
|
3
|
+
// the command layer (src/commands/prune.ts) does the filesystem/git work and
|
|
4
|
+
// feeds the results in here.
|
|
5
|
+
import type { GitStatus } from '../types';
|
|
6
|
+
|
|
7
|
+
const MS_PER_DAY = 24 * 60 * 60 * 1000;
|
|
8
|
+
|
|
9
|
+
export interface WorkspaceForPrune {
|
|
10
|
+
name: string;
|
|
11
|
+
path: string;
|
|
12
|
+
/** Repo directory names inside the workspace (for the git safety check). */
|
|
13
|
+
repoDirNames: string[];
|
|
14
|
+
/** Epoch ms of the most recent agent session, or 0 if none. */
|
|
15
|
+
lastActiveAt: number;
|
|
16
|
+
/** Epoch ms parsed from metadata.createdAt, or 0 if absent/unparseable. */
|
|
17
|
+
createdAt: number;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface PruneCandidate {
|
|
21
|
+
name: string;
|
|
22
|
+
path: string;
|
|
23
|
+
repoDirNames: string[];
|
|
24
|
+
/** The timestamp staleness is measured from (lastActive, else createdAt). */
|
|
25
|
+
referenceAt: number;
|
|
26
|
+
/** Whether the reference came from a real session (vs. createdAt fallback). */
|
|
27
|
+
fromSession: boolean;
|
|
28
|
+
/** Whole days since referenceAt (floored). */
|
|
29
|
+
ageDays: number;
|
|
30
|
+
/** True when we have no date at all to judge age. */
|
|
31
|
+
undatable: boolean;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface ProtectedWorkspace {
|
|
35
|
+
candidate: PruneCandidate;
|
|
36
|
+
reason: string;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface PrunePlan {
|
|
40
|
+
/** Stale + safe to delete. */
|
|
41
|
+
prunable: PruneCandidate[];
|
|
42
|
+
/** Stale but held back (uncommitted/unpushed work), unless includeDirty. */
|
|
43
|
+
protected: ProtectedWorkspace[];
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Build a dated candidate for a workspace. `now` is injected for testability. */
|
|
47
|
+
export function toCandidate(ws: WorkspaceForPrune, now: number): PruneCandidate {
|
|
48
|
+
const referenceAt = ws.lastActiveAt > 0 ? ws.lastActiveAt : ws.createdAt;
|
|
49
|
+
const undatable = !(referenceAt > 0);
|
|
50
|
+
const ageDays = undatable ? 0 : Math.floor((now - referenceAt) / MS_PER_DAY);
|
|
51
|
+
return {
|
|
52
|
+
name: ws.name,
|
|
53
|
+
path: ws.path,
|
|
54
|
+
repoDirNames: ws.repoDirNames,
|
|
55
|
+
referenceAt,
|
|
56
|
+
fromSession: ws.lastActiveAt > 0,
|
|
57
|
+
ageDays,
|
|
58
|
+
undatable,
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* A workspace is a prune candidate when it is datable and its age meets the
|
|
64
|
+
* threshold. Undatable workspaces are never auto-selected — we won't delete
|
|
65
|
+
* something we can't put a date on. A future `referenceAt` (clock skew) yields
|
|
66
|
+
* a negative age and is therefore not stale.
|
|
67
|
+
*/
|
|
68
|
+
export function isStale(c: PruneCandidate, days: number): boolean {
|
|
69
|
+
return !c.undatable && c.ageDays >= days;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Why a stale workspace should be held back from deletion, or null if it's safe.
|
|
74
|
+
* Unsafe = any repo has uncommitted changes (`!clean`) or unpushed commits
|
|
75
|
+
* (`ahead > 0`). With `includeDirty`, nothing is held back. An empty workspace
|
|
76
|
+
* (no repos) is always safe.
|
|
77
|
+
*/
|
|
78
|
+
export function protectionReason(statuses: GitStatus[], includeDirty: boolean): string | null {
|
|
79
|
+
if (includeDirty) return null;
|
|
80
|
+
const dirty = statuses.filter((s) => !s.clean).length;
|
|
81
|
+
const unpushed = statuses.filter((s) => s.ahead > 0).length;
|
|
82
|
+
if (dirty === 0 && unpushed === 0) return null;
|
|
83
|
+
const parts: string[] = [];
|
|
84
|
+
if (dirty > 0) parts.push(`${dirty} repo${dirty === 1 ? '' : 's'} with uncommitted changes`);
|
|
85
|
+
if (unpushed > 0) parts.push(`${unpushed} repo${unpushed === 1 ? '' : 's'} with unpushed commits`);
|
|
86
|
+
return parts.join(', ');
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Partition stale candidates into prunable vs. protected, given a resolver that
|
|
91
|
+
* returns each workspace's per-repo git status. The resolver is only invoked
|
|
92
|
+
* for workspaces that actually have repos, so empty stale workspaces cost no git
|
|
93
|
+
* calls. Injecting the resolver keeps this function pure and unit-testable.
|
|
94
|
+
*/
|
|
95
|
+
export async function planPrune(
|
|
96
|
+
staleCandidates: PruneCandidate[],
|
|
97
|
+
getStatuses: (c: PruneCandidate) => Promise<GitStatus[]>,
|
|
98
|
+
includeDirty: boolean,
|
|
99
|
+
): Promise<PrunePlan> {
|
|
100
|
+
const prunable: PruneCandidate[] = [];
|
|
101
|
+
const protectedList: ProtectedWorkspace[] = [];
|
|
102
|
+
for (const c of staleCandidates) {
|
|
103
|
+
const statuses = c.repoDirNames.length > 0 ? await getStatuses(c) : [];
|
|
104
|
+
const reason = protectionReason(statuses, includeDirty);
|
|
105
|
+
if (reason) protectedList.push({ candidate: c, reason });
|
|
106
|
+
else prunable.push(c);
|
|
107
|
+
}
|
|
108
|
+
return { prunable, protected: protectedList };
|
|
109
|
+
}
|