cc4pm 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/.claude-plugin/README.md +17 -0
  2. package/.claude-plugin/plugin.json +25 -0
  3. package/LICENSE +21 -0
  4. package/README.md +157 -0
  5. package/README.zh-CN.md +134 -0
  6. package/contexts/dev.md +20 -0
  7. package/contexts/research.md +26 -0
  8. package/contexts/review.md +22 -0
  9. package/examples/CLAUDE.md +100 -0
  10. package/examples/statusline.json +19 -0
  11. package/examples/user-CLAUDE.md +109 -0
  12. package/install.sh +17 -0
  13. package/manifests/install-components.json +173 -0
  14. package/manifests/install-modules.json +335 -0
  15. package/manifests/install-profiles.json +75 -0
  16. package/package.json +117 -0
  17. package/schemas/ecc-install-config.schema.json +58 -0
  18. package/schemas/hooks.schema.json +197 -0
  19. package/schemas/install-components.schema.json +56 -0
  20. package/schemas/install-modules.schema.json +105 -0
  21. package/schemas/install-profiles.schema.json +45 -0
  22. package/schemas/install-state.schema.json +210 -0
  23. package/schemas/package-manager.schema.json +23 -0
  24. package/schemas/plugin.schema.json +58 -0
  25. package/scripts/ci/catalog.js +83 -0
  26. package/scripts/ci/validate-agents.js +81 -0
  27. package/scripts/ci/validate-commands.js +135 -0
  28. package/scripts/ci/validate-hooks.js +239 -0
  29. package/scripts/ci/validate-install-manifests.js +211 -0
  30. package/scripts/ci/validate-no-personal-paths.js +63 -0
  31. package/scripts/ci/validate-rules.js +81 -0
  32. package/scripts/ci/validate-skills.js +54 -0
  33. package/scripts/claw.js +468 -0
  34. package/scripts/doctor.js +110 -0
  35. package/scripts/ecc.js +194 -0
  36. package/scripts/hooks/auto-tmux-dev.js +88 -0
  37. package/scripts/hooks/check-console-log.js +71 -0
  38. package/scripts/hooks/check-hook-enabled.js +12 -0
  39. package/scripts/hooks/cost-tracker.js +78 -0
  40. package/scripts/hooks/doc-file-warning.js +63 -0
  41. package/scripts/hooks/evaluate-session.js +100 -0
  42. package/scripts/hooks/insaits-security-monitor.py +269 -0
  43. package/scripts/hooks/insaits-security-wrapper.js +88 -0
  44. package/scripts/hooks/post-bash-build-complete.js +27 -0
  45. package/scripts/hooks/post-bash-pr-created.js +36 -0
  46. package/scripts/hooks/post-edit-console-warn.js +54 -0
  47. package/scripts/hooks/post-edit-format.js +109 -0
  48. package/scripts/hooks/post-edit-typecheck.js +96 -0
  49. package/scripts/hooks/pre-bash-dev-server-block.js +187 -0
  50. package/scripts/hooks/pre-bash-git-push-reminder.js +28 -0
  51. package/scripts/hooks/pre-bash-tmux-reminder.js +33 -0
  52. package/scripts/hooks/pre-compact.js +48 -0
  53. package/scripts/hooks/pre-write-doc-warn.js +9 -0
  54. package/scripts/hooks/quality-gate.js +168 -0
  55. package/scripts/hooks/run-with-flags-shell.sh +32 -0
  56. package/scripts/hooks/run-with-flags.js +120 -0
  57. package/scripts/hooks/session-end-marker.js +15 -0
  58. package/scripts/hooks/session-end.js +299 -0
  59. package/scripts/hooks/session-start.js +97 -0
  60. package/scripts/hooks/suggest-compact.js +80 -0
  61. package/scripts/install-apply.js +137 -0
  62. package/scripts/install-plan.js +254 -0
  63. package/scripts/lib/hook-flags.js +74 -0
  64. package/scripts/lib/install/apply.js +23 -0
  65. package/scripts/lib/install/config.js +82 -0
  66. package/scripts/lib/install/request.js +113 -0
  67. package/scripts/lib/install/runtime.js +42 -0
  68. package/scripts/lib/install-executor.js +605 -0
  69. package/scripts/lib/install-lifecycle.js +763 -0
  70. package/scripts/lib/install-manifests.js +305 -0
  71. package/scripts/lib/install-state.js +120 -0
  72. package/scripts/lib/install-targets/antigravity-project.js +9 -0
  73. package/scripts/lib/install-targets/claude-home.js +10 -0
  74. package/scripts/lib/install-targets/codex-home.js +10 -0
  75. package/scripts/lib/install-targets/cursor-project.js +10 -0
  76. package/scripts/lib/install-targets/helpers.js +89 -0
  77. package/scripts/lib/install-targets/opencode-home.js +10 -0
  78. package/scripts/lib/install-targets/registry.js +64 -0
  79. package/scripts/lib/orchestration-session.js +299 -0
  80. package/scripts/lib/package-manager.d.ts +119 -0
  81. package/scripts/lib/package-manager.js +431 -0
  82. package/scripts/lib/project-detect.js +428 -0
  83. package/scripts/lib/resolve-formatter.js +185 -0
  84. package/scripts/lib/session-adapters/canonical-session.js +138 -0
  85. package/scripts/lib/session-adapters/claude-history.js +149 -0
  86. package/scripts/lib/session-adapters/dmux-tmux.js +80 -0
  87. package/scripts/lib/session-adapters/registry.js +111 -0
  88. package/scripts/lib/session-aliases.d.ts +136 -0
  89. package/scripts/lib/session-aliases.js +481 -0
  90. package/scripts/lib/session-manager.d.ts +131 -0
  91. package/scripts/lib/session-manager.js +464 -0
  92. package/scripts/lib/shell-split.js +86 -0
  93. package/scripts/lib/skill-improvement/amendify.js +89 -0
  94. package/scripts/lib/skill-improvement/evaluate.js +59 -0
  95. package/scripts/lib/skill-improvement/health.js +118 -0
  96. package/scripts/lib/skill-improvement/observations.js +108 -0
  97. package/scripts/lib/tmux-worktree-orchestrator.js +491 -0
  98. package/scripts/lib/utils.d.ts +183 -0
  99. package/scripts/lib/utils.js +543 -0
  100. package/scripts/list-installed.js +90 -0
  101. package/scripts/orchestrate-codex-worker.sh +92 -0
  102. package/scripts/orchestrate-worktrees.js +108 -0
  103. package/scripts/orchestration-status.js +62 -0
  104. package/scripts/repair.js +97 -0
  105. package/scripts/session-inspect.js +150 -0
  106. package/scripts/setup-package-manager.js +204 -0
  107. package/scripts/skill-create-output.js +244 -0
  108. package/scripts/uninstall.js +96 -0
@@ -0,0 +1,464 @@
1
+ /**
2
+ * Session Manager Library for Claude Code
3
+ * Provides core session CRUD operations for listing, loading, and managing sessions
4
+ *
5
+ * Sessions are stored as markdown files in ~/.claude/sessions/ with format:
6
+ * - YYYY-MM-DD-session.tmp (old format)
7
+ * - YYYY-MM-DD-<short-id>-session.tmp (new format)
8
+ */
9
+
10
+ const fs = require('fs');
11
+ const path = require('path');
12
+
13
+ const {
14
+ getSessionsDir,
15
+ readFile,
16
+ log
17
+ } = require('./utils');
18
+
19
+ // Session filename pattern: YYYY-MM-DD-[session-id]-session.tmp
20
+ // The session-id is optional (old format) and can include letters, digits,
21
+ // underscores, and hyphens, but must not start with a hyphen.
22
+ // Matches: "2026-02-01-session.tmp", "2026-02-01-a1b2c3d4-session.tmp",
23
+ // "2026-02-01-frontend-worktree-1-session.tmp", and
24
+ // "2026-02-01-ChezMoi_2-session.tmp"
25
+ const SESSION_FILENAME_REGEX = /^(\d{4}-\d{2}-\d{2})(?:-([a-zA-Z0-9_][a-zA-Z0-9_-]*))?-session\.tmp$/;
26
+
27
+ /**
28
+ * Parse session filename to extract metadata
29
+ * @param {string} filename - Session filename (e.g., "2026-01-17-abc123-session.tmp" or "2026-01-17-session.tmp")
30
+ * @returns {object|null} Parsed metadata or null if invalid
31
+ */
32
+ function parseSessionFilename(filename) {
33
+ const match = filename.match(SESSION_FILENAME_REGEX);
34
+ if (!match) return null;
35
+
36
+ const dateStr = match[1];
37
+
38
+ // Validate date components are calendar-accurate (not just format)
39
+ const [year, month, day] = dateStr.split('-').map(Number);
40
+ if (month < 1 || month > 12 || day < 1 || day > 31) return null;
41
+ // Reject impossible dates like Feb 31, Apr 31 — Date constructor rolls
42
+ // over invalid days (e.g., Feb 31 → Mar 3), so check month roundtrips
43
+ const d = new Date(year, month - 1, day);
44
+ if (d.getMonth() !== month - 1 || d.getDate() !== day) return null;
45
+
46
+ // match[2] is undefined for old format (no ID)
47
+ const shortId = match[2] || 'no-id';
48
+
49
+ return {
50
+ filename,
51
+ shortId,
52
+ date: dateStr,
53
+ // Use local-time constructor (consistent with validation on line 40)
54
+ // new Date(dateStr) interprets YYYY-MM-DD as UTC midnight which shows
55
+ // as the previous day in negative UTC offset timezones
56
+ datetime: new Date(year, month - 1, day)
57
+ };
58
+ }
59
+
60
+ /**
61
+ * Get the full path to a session file
62
+ * @param {string} filename - Session filename
63
+ * @returns {string} Full path to session file
64
+ */
65
+ function getSessionPath(filename) {
66
+ return path.join(getSessionsDir(), filename);
67
+ }
68
+
69
+ /**
70
+ * Read and parse session markdown content
71
+ * @param {string} sessionPath - Full path to session file
72
+ * @returns {string|null} Session content or null if not found
73
+ */
74
+ function getSessionContent(sessionPath) {
75
+ return readFile(sessionPath);
76
+ }
77
+
78
+ /**
79
+ * Parse session metadata from markdown content
80
+ * @param {string} content - Session markdown content
81
+ * @returns {object} Parsed metadata
82
+ */
83
+ function parseSessionMetadata(content) {
84
+ const metadata = {
85
+ title: null,
86
+ date: null,
87
+ started: null,
88
+ lastUpdated: null,
89
+ project: null,
90
+ branch: null,
91
+ worktree: null,
92
+ completed: [],
93
+ inProgress: [],
94
+ notes: '',
95
+ context: ''
96
+ };
97
+
98
+ if (!content) return metadata;
99
+
100
+ // Extract title from first heading
101
+ const titleMatch = content.match(/^#\s+(.+)$/m);
102
+ if (titleMatch) {
103
+ metadata.title = titleMatch[1].trim();
104
+ }
105
+
106
+ // Extract date
107
+ const dateMatch = content.match(/\*\*Date:\*\*\s*(\d{4}-\d{2}-\d{2})/);
108
+ if (dateMatch) {
109
+ metadata.date = dateMatch[1];
110
+ }
111
+
112
+ // Extract started time
113
+ const startedMatch = content.match(/\*\*Started:\*\*\s*([\d:]+)/);
114
+ if (startedMatch) {
115
+ metadata.started = startedMatch[1];
116
+ }
117
+
118
+ // Extract last updated
119
+ const updatedMatch = content.match(/\*\*Last Updated:\*\*\s*([\d:]+)/);
120
+ if (updatedMatch) {
121
+ metadata.lastUpdated = updatedMatch[1];
122
+ }
123
+
124
+ // Extract control-plane metadata
125
+ const projectMatch = content.match(/\*\*Project:\*\*\s*(.+)$/m);
126
+ if (projectMatch) {
127
+ metadata.project = projectMatch[1].trim();
128
+ }
129
+
130
+ const branchMatch = content.match(/\*\*Branch:\*\*\s*(.+)$/m);
131
+ if (branchMatch) {
132
+ metadata.branch = branchMatch[1].trim();
133
+ }
134
+
135
+ const worktreeMatch = content.match(/\*\*Worktree:\*\*\s*(.+)$/m);
136
+ if (worktreeMatch) {
137
+ metadata.worktree = worktreeMatch[1].trim();
138
+ }
139
+
140
+ // Extract completed items
141
+ const completedSection = content.match(/### Completed\s*\n([\s\S]*?)(?=###|\n\n|$)/);
142
+ if (completedSection) {
143
+ const items = completedSection[1].match(/- \[x\]\s*(.+)/g);
144
+ if (items) {
145
+ metadata.completed = items.map(item => item.replace(/- \[x\]\s*/, '').trim());
146
+ }
147
+ }
148
+
149
+ // Extract in-progress items
150
+ const progressSection = content.match(/### In Progress\s*\n([\s\S]*?)(?=###|\n\n|$)/);
151
+ if (progressSection) {
152
+ const items = progressSection[1].match(/- \[ \]\s*(.+)/g);
153
+ if (items) {
154
+ metadata.inProgress = items.map(item => item.replace(/- \[ \]\s*/, '').trim());
155
+ }
156
+ }
157
+
158
+ // Extract notes
159
+ const notesSection = content.match(/### Notes for Next Session\s*\n([\s\S]*?)(?=###|\n\n|$)/);
160
+ if (notesSection) {
161
+ metadata.notes = notesSection[1].trim();
162
+ }
163
+
164
+ // Extract context to load
165
+ const contextSection = content.match(/### Context to Load\s*\n```\n([\s\S]*?)```/);
166
+ if (contextSection) {
167
+ metadata.context = contextSection[1].trim();
168
+ }
169
+
170
+ return metadata;
171
+ }
172
+
173
+ /**
174
+ * Calculate statistics for a session
175
+ * @param {string} sessionPathOrContent - Full path to session file, OR
176
+ * the pre-read content string (to avoid redundant disk reads when
177
+ * the caller already has the content loaded).
178
+ * @returns {object} Statistics object
179
+ */
180
+ function getSessionStats(sessionPathOrContent) {
181
+ // Accept pre-read content string to avoid redundant file reads.
182
+ // If the argument looks like a file path (no newlines, ends with .tmp,
183
+ // starts with / on Unix or drive letter on Windows), read from disk.
184
+ // Otherwise treat it as content.
185
+ const looksLikePath = typeof sessionPathOrContent === 'string' &&
186
+ !sessionPathOrContent.includes('\n') &&
187
+ sessionPathOrContent.endsWith('.tmp') &&
188
+ (sessionPathOrContent.startsWith('/') || /^[A-Za-z]:[/\\]/.test(sessionPathOrContent));
189
+ const content = looksLikePath
190
+ ? getSessionContent(sessionPathOrContent)
191
+ : sessionPathOrContent;
192
+
193
+ const metadata = parseSessionMetadata(content);
194
+
195
+ return {
196
+ totalItems: metadata.completed.length + metadata.inProgress.length,
197
+ completedItems: metadata.completed.length,
198
+ inProgressItems: metadata.inProgress.length,
199
+ lineCount: content ? content.split('\n').length : 0,
200
+ hasNotes: !!metadata.notes,
201
+ hasContext: !!metadata.context
202
+ };
203
+ }
204
+
205
+ /**
206
+ * Get all sessions with optional filtering and pagination
207
+ * @param {object} options - Options object
208
+ * @param {number} options.limit - Maximum number of sessions to return
209
+ * @param {number} options.offset - Number of sessions to skip
210
+ * @param {string} options.date - Filter by date (YYYY-MM-DD format)
211
+ * @param {string} options.search - Search in short ID
212
+ * @returns {object} Object with sessions array and pagination info
213
+ */
214
+ function getAllSessions(options = {}) {
215
+ const {
216
+ limit: rawLimit = 50,
217
+ offset: rawOffset = 0,
218
+ date = null,
219
+ search = null
220
+ } = options;
221
+
222
+ // Clamp offset and limit to safe non-negative integers.
223
+ // Without this, negative offset causes slice() to count from the end,
224
+ // and NaN values cause slice() to return empty or unexpected results.
225
+ // Note: cannot use `|| default` because 0 is falsy — use isNaN instead.
226
+ const offsetNum = Number(rawOffset);
227
+ const offset = Number.isNaN(offsetNum) ? 0 : Math.max(0, Math.floor(offsetNum));
228
+ const limitNum = Number(rawLimit);
229
+ const limit = Number.isNaN(limitNum) ? 50 : Math.max(1, Math.floor(limitNum));
230
+
231
+ const sessionsDir = getSessionsDir();
232
+
233
+ if (!fs.existsSync(sessionsDir)) {
234
+ return { sessions: [], total: 0, offset, limit, hasMore: false };
235
+ }
236
+
237
+ const entries = fs.readdirSync(sessionsDir, { withFileTypes: true });
238
+ const sessions = [];
239
+
240
+ for (const entry of entries) {
241
+ // Skip non-files (only process .tmp files)
242
+ if (!entry.isFile() || !entry.name.endsWith('.tmp')) continue;
243
+
244
+ const filename = entry.name;
245
+ const metadata = parseSessionFilename(filename);
246
+
247
+ if (!metadata) continue;
248
+
249
+ // Apply date filter
250
+ if (date && metadata.date !== date) {
251
+ continue;
252
+ }
253
+
254
+ // Apply search filter (search in short ID)
255
+ if (search && !metadata.shortId.includes(search)) {
256
+ continue;
257
+ }
258
+
259
+ const sessionPath = path.join(sessionsDir, filename);
260
+
261
+ // Get file stats (wrapped in try-catch to handle TOCTOU race where
262
+ // file is deleted between readdirSync and statSync)
263
+ let stats;
264
+ try {
265
+ stats = fs.statSync(sessionPath);
266
+ } catch {
267
+ continue; // File was deleted between readdir and stat
268
+ }
269
+
270
+ sessions.push({
271
+ ...metadata,
272
+ sessionPath,
273
+ hasContent: stats.size > 0,
274
+ size: stats.size,
275
+ modifiedTime: stats.mtime,
276
+ createdTime: stats.birthtime || stats.ctime
277
+ });
278
+ }
279
+
280
+ // Sort by modified time (newest first)
281
+ sessions.sort((a, b) => b.modifiedTime - a.modifiedTime);
282
+
283
+ // Apply pagination
284
+ const paginatedSessions = sessions.slice(offset, offset + limit);
285
+
286
+ return {
287
+ sessions: paginatedSessions,
288
+ total: sessions.length,
289
+ offset,
290
+ limit,
291
+ hasMore: offset + limit < sessions.length
292
+ };
293
+ }
294
+
295
+ /**
296
+ * Get a single session by ID (short ID or full path)
297
+ * @param {string} sessionId - Short ID or session filename
298
+ * @param {boolean} includeContent - Include session content
299
+ * @returns {object|null} Session object or null if not found
300
+ */
301
+ function getSessionById(sessionId, includeContent = false) {
302
+ const sessionsDir = getSessionsDir();
303
+
304
+ if (!fs.existsSync(sessionsDir)) {
305
+ return null;
306
+ }
307
+
308
+ const entries = fs.readdirSync(sessionsDir, { withFileTypes: true });
309
+
310
+ for (const entry of entries) {
311
+ if (!entry.isFile() || !entry.name.endsWith('.tmp')) continue;
312
+
313
+ const filename = entry.name;
314
+ const metadata = parseSessionFilename(filename);
315
+
316
+ if (!metadata) continue;
317
+
318
+ // Check if session ID matches (short ID or full filename without .tmp)
319
+ const shortIdMatch = sessionId.length > 0 && metadata.shortId !== 'no-id' && metadata.shortId.startsWith(sessionId);
320
+ const filenameMatch = filename === sessionId || filename === `${sessionId}.tmp`;
321
+ const noIdMatch = metadata.shortId === 'no-id' && filename === `${sessionId}-session.tmp`;
322
+
323
+ if (!shortIdMatch && !filenameMatch && !noIdMatch) {
324
+ continue;
325
+ }
326
+
327
+ const sessionPath = path.join(sessionsDir, filename);
328
+ let stats;
329
+ try {
330
+ stats = fs.statSync(sessionPath);
331
+ } catch {
332
+ return null; // File was deleted between readdir and stat
333
+ }
334
+
335
+ const session = {
336
+ ...metadata,
337
+ sessionPath,
338
+ size: stats.size,
339
+ modifiedTime: stats.mtime,
340
+ createdTime: stats.birthtime || stats.ctime
341
+ };
342
+
343
+ if (includeContent) {
344
+ session.content = getSessionContent(sessionPath);
345
+ session.metadata = parseSessionMetadata(session.content);
346
+ // Pass pre-read content to avoid a redundant disk read
347
+ session.stats = getSessionStats(session.content || '');
348
+ }
349
+
350
+ return session;
351
+ }
352
+
353
+ return null;
354
+ }
355
+
356
+ /**
357
+ * Get session title from content
358
+ * @param {string} sessionPath - Full path to session file
359
+ * @returns {string} Title or default text
360
+ */
361
+ function getSessionTitle(sessionPath) {
362
+ const content = getSessionContent(sessionPath);
363
+ const metadata = parseSessionMetadata(content);
364
+
365
+ return metadata.title || 'Untitled Session';
366
+ }
367
+
368
+ /**
369
+ * Format session size in human-readable format
370
+ * @param {string} sessionPath - Full path to session file
371
+ * @returns {string} Formatted size (e.g., "1.2 KB")
372
+ */
373
+ function getSessionSize(sessionPath) {
374
+ let stats;
375
+ try {
376
+ stats = fs.statSync(sessionPath);
377
+ } catch {
378
+ return '0 B';
379
+ }
380
+ const size = stats.size;
381
+
382
+ if (size < 1024) return `${size} B`;
383
+ if (size < 1024 * 1024) return `${(size / 1024).toFixed(1)} KB`;
384
+ return `${(size / (1024 * 1024)).toFixed(1)} MB`;
385
+ }
386
+
387
+ /**
388
+ * Write session content to file
389
+ * @param {string} sessionPath - Full path to session file
390
+ * @param {string} content - Markdown content to write
391
+ * @returns {boolean} Success status
392
+ */
393
+ function writeSessionContent(sessionPath, content) {
394
+ try {
395
+ fs.writeFileSync(sessionPath, content, 'utf8');
396
+ return true;
397
+ } catch (err) {
398
+ log(`[SessionManager] Error writing session: ${err.message}`);
399
+ return false;
400
+ }
401
+ }
402
+
403
+ /**
404
+ * Append content to a session
405
+ * @param {string} sessionPath - Full path to session file
406
+ * @param {string} content - Content to append
407
+ * @returns {boolean} Success status
408
+ */
409
+ function appendSessionContent(sessionPath, content) {
410
+ try {
411
+ fs.appendFileSync(sessionPath, content, 'utf8');
412
+ return true;
413
+ } catch (err) {
414
+ log(`[SessionManager] Error appending to session: ${err.message}`);
415
+ return false;
416
+ }
417
+ }
418
+
419
+ /**
420
+ * Delete a session file
421
+ * @param {string} sessionPath - Full path to session file
422
+ * @returns {boolean} Success status
423
+ */
424
+ function deleteSession(sessionPath) {
425
+ try {
426
+ if (fs.existsSync(sessionPath)) {
427
+ fs.unlinkSync(sessionPath);
428
+ return true;
429
+ }
430
+ return false;
431
+ } catch (err) {
432
+ log(`[SessionManager] Error deleting session: ${err.message}`);
433
+ return false;
434
+ }
435
+ }
436
+
437
+ /**
438
+ * Check if a session exists
439
+ * @param {string} sessionPath - Full path to session file
440
+ * @returns {boolean} True if session exists
441
+ */
442
+ function sessionExists(sessionPath) {
443
+ try {
444
+ return fs.statSync(sessionPath).isFile();
445
+ } catch {
446
+ return false;
447
+ }
448
+ }
449
+
450
+ module.exports = {
451
+ parseSessionFilename,
452
+ getSessionPath,
453
+ getSessionContent,
454
+ parseSessionMetadata,
455
+ getSessionStats,
456
+ getSessionTitle,
457
+ getSessionSize,
458
+ getAllSessions,
459
+ getSessionById,
460
+ writeSessionContent,
461
+ appendSessionContent,
462
+ deleteSession,
463
+ sessionExists
464
+ };
@@ -0,0 +1,86 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Split a shell command into segments by operators (&&, ||, ;, &)
5
+ * while respecting quoting (single/double) and escaped characters.
6
+ * Redirection operators (&>, >&, 2>&1) are NOT treated as separators.
7
+ */
8
+ function splitShellSegments(command) {
9
+ const segments = [];
10
+ let current = '';
11
+ let quote = null;
12
+
13
+ for (let i = 0; i < command.length; i++) {
14
+ const ch = command[i];
15
+
16
+ // Inside quotes: handle escapes and closing quote
17
+ if (quote) {
18
+ if (ch === '\\' && i + 1 < command.length) {
19
+ current += ch + command[i + 1];
20
+ i++;
21
+ continue;
22
+ }
23
+ if (ch === quote) quote = null;
24
+ current += ch;
25
+ continue;
26
+ }
27
+
28
+ // Backslash escape outside quotes
29
+ if (ch === '\\' && i + 1 < command.length) {
30
+ current += ch + command[i + 1];
31
+ i++;
32
+ continue;
33
+ }
34
+
35
+ // Opening quote
36
+ if (ch === '"' || ch === "'") {
37
+ quote = ch;
38
+ current += ch;
39
+ continue;
40
+ }
41
+
42
+ const next = command[i + 1] || '';
43
+ const prev = i > 0 ? command[i - 1] : '';
44
+
45
+ // && operator
46
+ if (ch === '&' && next === '&') {
47
+ if (current.trim()) segments.push(current.trim());
48
+ current = '';
49
+ i++;
50
+ continue;
51
+ }
52
+
53
+ // || operator
54
+ if (ch === '|' && next === '|') {
55
+ if (current.trim()) segments.push(current.trim());
56
+ current = '';
57
+ i++;
58
+ continue;
59
+ }
60
+
61
+ // ; separator
62
+ if (ch === ';') {
63
+ if (current.trim()) segments.push(current.trim());
64
+ current = '';
65
+ continue;
66
+ }
67
+
68
+ // Single & — but skip redirection patterns (&>, >&, digit>&)
69
+ if (ch === '&' && next !== '&') {
70
+ if (next === '>' || prev === '>') {
71
+ current += ch;
72
+ continue;
73
+ }
74
+ if (current.trim()) segments.push(current.trim());
75
+ current = '';
76
+ continue;
77
+ }
78
+
79
+ current += ch;
80
+ }
81
+
82
+ if (current.trim()) segments.push(current.trim());
83
+ return segments;
84
+ }
85
+
86
+ module.exports = { splitShellSegments };
@@ -0,0 +1,89 @@
1
+ 'use strict';
2
+
3
+ const { buildSkillHealthReport } = require('./health');
4
+
5
+ const AMENDMENT_SCHEMA_VERSION = 'ecc.skill-amendment-proposal.v1';
6
+
7
+ function createProposalId(skillId) {
8
+ return `amend-${skillId}-${Date.now()}`;
9
+ }
10
+
11
+ function summarizePatchPreview(skillId, health) {
12
+ const lines = [
13
+ '## Failure-Driven Amendments',
14
+ '',
15
+ `- Focus skill routing for \`${skillId}\` when tasks match the proven success cases.`,
16
+ ];
17
+
18
+ if (health.recurringErrors[0]) {
19
+ lines.push(`- Add explicit guardrails for recurring failure: ${health.recurringErrors[0].error}.`);
20
+ }
21
+
22
+ if (health.recurringTasks[0]) {
23
+ lines.push(`- Add an example workflow for task pattern: ${health.recurringTasks[0].task}.`);
24
+ }
25
+
26
+ if (health.recurringFeedback[0]) {
27
+ lines.push(`- Address repeated user feedback: ${health.recurringFeedback[0].feedback}.`);
28
+ }
29
+
30
+ lines.push('- Add a verification checklist before declaring the skill output complete.');
31
+ return lines.join('\n');
32
+ }
33
+
34
+ function proposeSkillAmendment(skillId, records, options = {}) {
35
+ const report = buildSkillHealthReport(records, {
36
+ ...options,
37
+ skillId,
38
+ minFailureCount: options.minFailureCount || 1
39
+ });
40
+ const [health] = report.skills;
41
+
42
+ if (!health || health.failures === 0) {
43
+ return {
44
+ schemaVersion: AMENDMENT_SCHEMA_VERSION,
45
+ skill: {
46
+ id: skillId,
47
+ path: null
48
+ },
49
+ status: 'insufficient-evidence',
50
+ rationale: ['No failed observations were available for this skill.'],
51
+ patch: null
52
+ };
53
+ }
54
+
55
+ const preview = summarizePatchPreview(skillId, health);
56
+
57
+ return {
58
+ schemaVersion: AMENDMENT_SCHEMA_VERSION,
59
+ proposalId: createProposalId(skillId),
60
+ generatedAt: new Date().toISOString(),
61
+ status: 'proposed',
62
+ skill: {
63
+ id: skillId,
64
+ path: health.skill.path || null
65
+ },
66
+ evidence: {
67
+ totalRuns: health.totalRuns,
68
+ failures: health.failures,
69
+ successRate: health.successRate,
70
+ recurringErrors: health.recurringErrors,
71
+ recurringTasks: health.recurringTasks,
72
+ recurringFeedback: health.recurringFeedback
73
+ },
74
+ rationale: [
75
+ 'Proposals are generated from repeated failed runs rather than a single anecdotal error.',
76
+ 'The suggested patch is additive so the original SKILL.md intent remains auditable.'
77
+ ],
78
+ patch: {
79
+ format: 'markdown-fragment',
80
+ targetPath: health.skill.path || `skills/${skillId}/SKILL.md`,
81
+ preview
82
+ }
83
+ };
84
+ }
85
+
86
+ module.exports = {
87
+ AMENDMENT_SCHEMA_VERSION,
88
+ proposeSkillAmendment
89
+ };
@@ -0,0 +1,59 @@
1
+ 'use strict';
2
+
3
+ const EVALUATION_SCHEMA_VERSION = 'ecc.skill-evaluation.v1';
4
+
5
+ function roundRate(value) {
6
+ return Math.round(value * 1000) / 1000;
7
+ }
8
+
9
+ function summarize(records) {
10
+ const runs = records.length;
11
+ const successes = records.filter(record => record.outcome && record.outcome.success).length;
12
+ const failures = runs - successes;
13
+ return {
14
+ runs,
15
+ successes,
16
+ failures,
17
+ successRate: runs > 0 ? roundRate(successes / runs) : 0
18
+ };
19
+ }
20
+
21
+ function buildSkillEvaluationScaffold(skillId, records, options = {}) {
22
+ const minimumRunsPerVariant = options.minimumRunsPerVariant || 2;
23
+ const amendmentId = options.amendmentId || null;
24
+ const filtered = records.filter(record => record.skill && record.skill.id === skillId);
25
+ const baseline = filtered.filter(record => !record.run || record.run.variant !== 'amended');
26
+ const amended = filtered.filter(record => record.run && record.run.variant === 'amended')
27
+ .filter(record => !amendmentId || record.run.amendmentId === amendmentId);
28
+
29
+ const baselineSummary = summarize(baseline);
30
+ const amendedSummary = summarize(amended);
31
+ const delta = {
32
+ successRate: roundRate(amendedSummary.successRate - baselineSummary.successRate),
33
+ failures: amendedSummary.failures - baselineSummary.failures
34
+ };
35
+
36
+ let recommendation = 'insufficient-data';
37
+ if (baselineSummary.runs >= minimumRunsPerVariant && amendedSummary.runs >= minimumRunsPerVariant) {
38
+ recommendation = delta.successRate > 0 ? 'promote-amendment' : 'keep-baseline';
39
+ }
40
+
41
+ return {
42
+ schemaVersion: EVALUATION_SCHEMA_VERSION,
43
+ generatedAt: new Date().toISOString(),
44
+ skillId,
45
+ amendmentId,
46
+ gate: {
47
+ minimumRunsPerVariant
48
+ },
49
+ baseline: baselineSummary,
50
+ amended: amendedSummary,
51
+ delta,
52
+ recommendation
53
+ };
54
+ }
55
+
56
+ module.exports = {
57
+ EVALUATION_SCHEMA_VERSION,
58
+ buildSkillEvaluationScaffold
59
+ };