a2acalling 0.6.56 → 0.6.58

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,251 @@
1
+ // ============================================================================
2
+ // Shared cleanup function used by both:
3
+ // 1. npm preuninstall hook (scripts/preuninstall.js)
4
+ // 2. `a2a uninstall` CLI command (bin/cli.js)
5
+ //
6
+ // Reads .a2a-manifest.json to determine which files to remove.
7
+ // CLAUDE.md section removal uses the same boundary markers as the
8
+ // merge logic in installSkills() — "# A2A Calling" start marker
9
+ // and "<!-- END A2A CALLING SECTION -->" end marker.
10
+ //
11
+ // Returns { removed: string[], preserved: string[], errors: string[] }
12
+ // so callers can print a meaningful summary.
13
+ // ============================================================================
14
+
15
+ const fs = require('fs');
16
+ const path = require('path');
17
+
18
+ // These markers must match the ones used in install-skills.js merge logic.
19
+ // If they diverge, cleanup will fail to find the section boundaries.
20
+ const A2A_SECTION_START = '# A2A Calling';
21
+ const A2A_SECTION_END = '<!-- END A2A CALLING SECTION -->';
22
+
23
+ /**
24
+ * cleanupProjectFiles — manifest-driven removal of all postinstall artifacts
25
+ *
26
+ * Reads .a2a-manifest.json from targetDir, then removes every file listed in
27
+ * the manifest. CLAUDE.md gets special handling: only the A2A section is
28
+ * removed, preserving any user content before/after. Empty directories
29
+ * (.claude/commands/, .claude/) are cleaned up if no non-a2a files remain.
30
+ *
31
+ * @param {string} targetDir - The project directory containing .a2a-manifest.json
32
+ * @returns {{ removed: string[], preserved: string[], errors: string[] }}
33
+ */
34
+ function cleanupProjectFiles(targetDir) {
35
+ const result = { removed: [], preserved: [], errors: [] };
36
+ const manifestPath = path.join(targetDir, '.a2a-manifest.json');
37
+
38
+ // If manifest doesn't exist, skip cleanup gracefully.
39
+ // This happens for manual installs, old versions, or projects where the
40
+ // manifest was already cleaned up. Better to leave files than crash.
41
+ if (!fs.existsSync(manifestPath)) {
42
+ return result;
43
+ }
44
+
45
+ let manifest;
46
+ try {
47
+ manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
48
+ } catch (err) {
49
+ // Corrupt or unreadable manifest — can't determine what to clean up.
50
+ // Return gracefully so npm uninstall doesn't fail.
51
+ result.errors.push(`.a2a-manifest.json: could not parse (${err.message})`);
52
+ return result;
53
+ }
54
+
55
+ const files = manifest.files || [];
56
+
57
+ for (const entry of files) {
58
+ // Skip the manifest itself — we remove it last, after all other files
59
+ if (entry.path === '.a2a-manifest.json') continue;
60
+
61
+ const filePath = path.join(targetDir, entry.path);
62
+
63
+ // If a file listed in manifest doesn't exist on disk, skip it silently.
64
+ // This handles cases where the user manually deleted files, or a previous
65
+ // partial cleanup already removed some files.
66
+ if (!fs.existsSync(filePath)) continue;
67
+
68
+ // ── CLAUDE.md: section removal, not whole-file deletion ──────────────
69
+ //
70
+ // The user may have their own project-specific content in CLAUDE.md.
71
+ // We only remove the A2A section (bounded by start/end markers), leaving
72
+ // everything else intact.
73
+ if (entry.path === 'CLAUDE.md') {
74
+ try {
75
+ const cleaned = removeA2ASectionFromClaudeMd(filePath);
76
+ if (cleaned === 'deleted') {
77
+ result.removed.push('CLAUDE.md (was A2A-only, deleted entirely)');
78
+ } else if (cleaned === 'trimmed') {
79
+ result.preserved.push('CLAUDE.md (A2A section removed, user content preserved)');
80
+ } else {
81
+ // 'no-section' — CLAUDE.md exists but has no A2A section.
82
+ // This shouldn't happen if the manifest says it was installed, but
83
+ // could occur if the user manually edited it. Leave it alone.
84
+ result.preserved.push('CLAUDE.md (no A2A section found, left unchanged)');
85
+ }
86
+ } catch (err) {
87
+ result.errors.push(`CLAUDE.md: ${err.message}`);
88
+ }
89
+ continue;
90
+ }
91
+
92
+ // ── All other files: delete entirely ─────────────────────────────────
93
+ try {
94
+ fs.rmSync(filePath, { force: true });
95
+ result.removed.push(entry.path);
96
+ } catch (err) {
97
+ // If file permissions prevent deletion, log warning and continue.
98
+ // We don't want a single permission error to abort the entire cleanup.
99
+ result.errors.push(`${entry.path}: ${err.message}`);
100
+ }
101
+ }
102
+
103
+ // ── Empty directory cleanup ──────────────────────────────────────────────
104
+ //
105
+ // After removing .claude/commands/a2a-*.md and .claude/a2a-skill-reference.md,
106
+ // the directories may be empty. We clean them up to avoid leaving empty dirs,
107
+ // but ONLY if they contain no non-a2a files (user's own commands, settings, etc.).
108
+ cleanupEmptyDir(path.join(targetDir, '.claude', 'commands'), result);
109
+ cleanupEmptyDir(path.join(targetDir, '.claude'), result);
110
+ cleanupEmptyDir(path.join(targetDir, '.codex'), result);
111
+
112
+ // ── Remove the install log ───────────────────────────────────────────────
113
+ //
114
+ // .a2a-install.log is written by postinstall.js as a convenience log.
115
+ // It's listed in the manifest but we also try to remove it explicitly
116
+ // in case the manifest entry was missing (belt and suspenders).
117
+ const logPath = path.join(targetDir, '.a2a-install.log');
118
+ if (fs.existsSync(logPath)) {
119
+ try {
120
+ fs.rmSync(logPath, { force: true });
121
+ // Only add to removed list if not already tracked from manifest iteration
122
+ if (!result.removed.includes('.a2a-install.log')) {
123
+ result.removed.push('.a2a-install.log');
124
+ }
125
+ } catch (err) {
126
+ result.errors.push(`.a2a-install.log: ${err.message}`);
127
+ }
128
+ }
129
+
130
+ // ── Remove the manifest itself last ──────────────────────────────────────
131
+ //
132
+ // The manifest is the cleanup driver, so we remove it after everything else.
133
+ // If this fails, the manifest is left behind — which is acceptable since
134
+ // a stale manifest is harmless and helps debug failed cleanups.
135
+ try {
136
+ fs.rmSync(manifestPath, { force: true });
137
+ result.removed.push('.a2a-manifest.json');
138
+ } catch (err) {
139
+ result.errors.push(`.a2a-manifest.json: ${err.message}`);
140
+ }
141
+
142
+ return result;
143
+ }
144
+
145
+ /**
146
+ * removeA2ASectionFromClaudeMd — surgically removes the A2A section from CLAUDE.md
147
+ *
148
+ * Three outcomes:
149
+ * - 'deleted' : File was entirely A2A content, deleted the file
150
+ * - 'trimmed' : A2A section removed, remaining user content preserved
151
+ * - 'no-section' : No A2A section found (file left unchanged)
152
+ *
153
+ * Edge case: CLAUDE.md becomes empty after A2A section removal.
154
+ * If the only content was the A2A section, the file would be left as
155
+ * whitespace-only, which is confusing. Delete it entirely instead.
156
+ *
157
+ * Edge case: Legacy installs without end marker.
158
+ * Pre-A2A-34 installs wrote the A2A section without the
159
+ * <!-- END A2A CALLING SECTION --> marker. For these, we fall back
160
+ * to removing from "# A2A Calling" to EOF, same as the old merge
161
+ * replacement behavior. This means any user content added after the
162
+ * A2A section in a legacy install will be lost — but this is the
163
+ * same behavior they already had on upgrade, so it's not a regression.
164
+ */
165
+ function removeA2ASectionFromClaudeMd(filePath) {
166
+ const content = fs.readFileSync(filePath, 'utf8');
167
+
168
+ // If the A2A section start marker isn't present, nothing to remove
169
+ if (!content.includes(A2A_SECTION_START)) {
170
+ return 'no-section';
171
+ }
172
+
173
+ const sectionStart = content.indexOf(A2A_SECTION_START);
174
+ const endMarkerIndex = content.indexOf(A2A_SECTION_END, sectionStart);
175
+
176
+ let before, after;
177
+
178
+ if (endMarkerIndex !== -1) {
179
+ // End marker found — extract content before and after the bounded section.
180
+ // trimEnd/trimStart collapse the whitespace gap left by the removed section.
181
+ const sectionEnd = endMarkerIndex + A2A_SECTION_END.length;
182
+ before = content.slice(0, sectionStart).trimEnd();
183
+ after = content.slice(sectionEnd).trimStart();
184
+ } else {
185
+ // Legacy install without end marker — remove from header to EOF.
186
+ // Everything after "# A2A Calling" is considered part of the A2A section.
187
+ before = content.slice(0, sectionStart).trimEnd();
188
+ after = '';
189
+ }
190
+
191
+ // Reassemble the file from the non-A2A portions
192
+ let cleaned;
193
+ if (before && after) {
194
+ // Content exists both before and after — join with double newline
195
+ cleaned = before + '\n\n' + after;
196
+ } else if (before) {
197
+ cleaned = before;
198
+ } else if (after) {
199
+ cleaned = after;
200
+ } else {
201
+ cleaned = '';
202
+ }
203
+
204
+ // Collapse any triple+ blank lines into double blank lines.
205
+ // This prevents ugly whitespace gaps where the A2A section used to be.
206
+ cleaned = cleaned.replace(/\n{3,}/g, '\n\n');
207
+
208
+ // Edge case: CLAUDE.md becomes empty after A2A section removal.
209
+ // If the only content was the A2A section, the file would be left as
210
+ // whitespace-only, which is confusing. Delete it entirely instead.
211
+ if (!cleaned.trim()) {
212
+ fs.rmSync(filePath, { force: true });
213
+ return 'deleted';
214
+ }
215
+
216
+ // Write the cleaned content back, ensuring the file ends with a newline
217
+ fs.writeFileSync(filePath, cleaned.trimEnd() + '\n');
218
+ return 'trimmed';
219
+ }
220
+
221
+ /**
222
+ * cleanupEmptyDir — removes a directory if it exists and contains no files.
223
+ *
224
+ * After removing A2A skill files, directories like .claude/commands/ may be
225
+ * empty. We remove them to avoid clutter, but ONLY if no user files remain.
226
+ * This prevents accidentally deleting directories that contain the user's
227
+ * own Claude Code commands or settings.
228
+ */
229
+ function cleanupEmptyDir(dirPath, result) {
230
+ try {
231
+ if (!fs.existsSync(dirPath)) return;
232
+
233
+ // Check if directory stat confirms it's actually a directory
234
+ const stat = fs.statSync(dirPath);
235
+ if (!stat.isDirectory()) return;
236
+
237
+ const entries = fs.readdirSync(dirPath);
238
+
239
+ // Only remove if the directory is completely empty.
240
+ // Any remaining files (user's own commands, .gitkeep, etc.) mean we keep it.
241
+ if (entries.length === 0) {
242
+ fs.rmdirSync(dirPath);
243
+ result.removed.push(dirPath.split(path.sep).slice(-2).join('/') + '/ (empty directory)');
244
+ }
245
+ } catch (err) {
246
+ // Directory cleanup is best-effort. Failures here are non-fatal —
247
+ // an empty directory is harmless, just slightly untidy.
248
+ }
249
+ }
250
+
251
+ module.exports = { cleanupProjectFiles };
@@ -0,0 +1,68 @@
1
+ #!/usr/bin/env node
2
+
3
+ // ============================================================================
4
+ // npm preuninstall hook — manifest-driven cleanup
5
+ //
6
+ // When `npm uninstall a2acalling` runs, npm calls this script BEFORE
7
+ // removing the package from node_modules. We read .a2a-manifest.json
8
+ // to find every file our postinstall created and remove them cleanly.
9
+ //
10
+ // CLAUDE.md gets special handling: we only remove the A2A section
11
+ // (between "# A2A Calling" and "<!-- END A2A CALLING SECTION -->"),
12
+ // preserving any project-specific content the user added before/after.
13
+ //
14
+ // If the manifest doesn't exist (manual install, old version), we
15
+ // skip cleanup gracefully — better to leave files than crash the uninstall.
16
+ // ============================================================================
17
+
18
+ // Skip in CI environments — cleanup is not needed in ephemeral containers
19
+ if (process.env.CI || process.env.CONTINUOUS_INTEGRATION) process.exit(0);
20
+ if (process.env.DOCKER) process.exit(0);
21
+
22
+ try {
23
+ const path = require('path');
24
+ const { cleanupProjectFiles } = require('./cleanup');
25
+
26
+ // INIT_CWD is set by npm to the directory where `npm uninstall` was run.
27
+ // This is the project root where postinstall placed the skill files.
28
+ // Falls back to cwd() which should also be the project root during npm lifecycle.
29
+ const targetDir = process.env.INIT_CWD || process.cwd();
30
+
31
+ const result = cleanupProjectFiles(targetDir);
32
+
33
+ // Print a short summary so the user (or agent) knows what was cleaned up.
34
+ // This output may be suppressed by npm v7+ unless --foreground-scripts is used,
35
+ // but it's still useful for debugging and for agents that capture stderr.
36
+ if (result.removed.length > 0) {
37
+ console.error(`a2acalling: cleaned up ${result.removed.length} file(s):`);
38
+ for (const f of result.removed) {
39
+ console.error(` - ${f}`);
40
+ }
41
+ }
42
+ if (result.preserved.length > 0) {
43
+ for (const f of result.preserved) {
44
+ console.error(` ~ ${f}`);
45
+ }
46
+ }
47
+ if (result.errors.length > 0) {
48
+ console.error(` Warnings (${result.errors.length}):`);
49
+ for (const e of result.errors) {
50
+ console.error(` ! ${e}`);
51
+ }
52
+ }
53
+ if (result.removed.length === 0 && result.preserved.length === 0 && result.errors.length === 0) {
54
+ // No manifest found or manifest was empty — nothing to clean up.
55
+ // This is expected for fresh installs that never ran postinstall,
56
+ // or for projects where cleanup was already done via `a2a uninstall`.
57
+ console.error('a2acalling: no install manifest found, skipping project cleanup.');
58
+ console.error(' Tip: run `a2a uninstall` to also remove server config and database.');
59
+ }
60
+ } catch (err) {
61
+ // CRITICAL: Never crash the npm uninstall process.
62
+ // If our cleanup fails for any reason, npm should still be able to remove
63
+ // the package from node_modules. A failed cleanup leaves orphaned files,
64
+ // which is annoying but not harmful. A crashed uninstall is much worse.
65
+ console.error(`a2acalling: cleanup warning — ${err.message}`);
66
+ }
67
+
68
+ process.exit(0);