@monoes/monodesign 1.2.18 → 1.2.22

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 (104) hide show
  1. package/README.md +3 -3
  2. package/cli/engine/design-system-checks.mjs +381 -0
  3. package/cli/engine/design-system-parse.mjs +433 -0
  4. package/cli/engine/design-system.mjs +20 -736
  5. package/cli/engine/detect-antipatterns-browser.js +12 -1
  6. package/cli/engine/engines/regex/detect-text-matchers.mjs +371 -0
  7. package/cli/engine/engines/regex/detect-text-run.mjs +186 -0
  8. package/cli/engine/engines/regex/detect-text.mjs +11 -523
  9. package/cli/engine/engines/static-html/css-cascade-color.mjs +219 -0
  10. package/cli/engine/engines/static-html/css-cascade-static-data.mjs +138 -0
  11. package/cli/engine/engines/static-html/css-cascade-static-dom.mjs +132 -0
  12. package/cli/engine/engines/static-html/css-cascade-static-parse.mjs +393 -0
  13. package/cli/engine/engines/static-html/css-cascade.mjs +24 -837
  14. package/cli/engine/registry/antipatterns-provider.mjs +60 -0
  15. package/cli/engine/registry/antipatterns-quality.mjs +218 -0
  16. package/cli/engine/registry/antipatterns-slop.mjs +226 -0
  17. package/cli/engine/registry/antipatterns.mjs +7 -494
  18. package/cli/engine/rules/checks-background.mjs +155 -0
  19. package/cli/engine/rules/checks-css-values.mjs +137 -0
  20. package/cli/engine/rules/checks-dom-effects.mjs +243 -0
  21. package/cli/engine/rules/checks-dom.mjs +148 -0
  22. package/cli/engine/rules/checks-element.mjs +286 -0
  23. package/cli/engine/rules/checks-html.mjs +204 -0
  24. package/cli/engine/rules/checks-overflow.mjs +263 -0
  25. package/cli/engine/rules/checks-page.mjs +465 -0
  26. package/cli/engine/rules/checks-pure.mjs +453 -0
  27. package/cli/engine/rules/checks-quality.mjs +447 -0
  28. package/cli/engine/rules/checks-stylesheet.mjs +324 -0
  29. package/cli/engine/rules/checks.mjs +98 -2939
  30. package/cli/lib/monodesign-config-consent.mjs +93 -0
  31. package/cli/lib/monodesign-config-core.mjs +37 -0
  32. package/cli/lib/monodesign-config-detection.mjs +133 -0
  33. package/cli/lib/monodesign-config-filter.mjs +198 -0
  34. package/cli/lib/monodesign-config-ignore-value.mjs +212 -0
  35. package/cli/lib/monodesign-config.mjs +21 -623
  36. package/package.json +2 -2
  37. package/skill/scripts/context-fields.mjs +65 -0
  38. package/skill/scripts/context-resolve.mjs +425 -0
  39. package/skill/scripts/context-update.mjs +151 -0
  40. package/skill/scripts/context-utils.mjs +68 -0
  41. package/skill/scripts/context-workspace.mjs +245 -0
  42. package/skill/scripts/context.mjs +17 -891
  43. package/skill/scripts/hook-admin-config.mjs +152 -0
  44. package/skill/scripts/hook-admin-ignore.mjs +131 -0
  45. package/skill/scripts/hook-admin-manifest.mjs +292 -0
  46. package/skill/scripts/hook-admin.mjs +8 -541
  47. package/skill/scripts/hook-before-edit-shell.mjs +184 -0
  48. package/skill/scripts/hook-before-edit.mjs +9 -165
  49. package/skill/scripts/hook-lib-cache.mjs +145 -0
  50. package/skill/scripts/hook-lib-config.mjs +292 -0
  51. package/skill/scripts/hook-lib-detector.mjs +72 -0
  52. package/skill/scripts/hook-lib-events.mjs +182 -0
  53. package/skill/scripts/hook-lib-findings.mjs +201 -0
  54. package/skill/scripts/hook-lib-ignore.mjs +205 -0
  55. package/skill/scripts/hook-lib-render.mjs +273 -0
  56. package/skill/scripts/hook-lib-run.mjs +281 -0
  57. package/skill/scripts/hook-lib-scan-targets.mjs +128 -0
  58. package/skill/scripts/hook-lib.mjs +71 -1747
  59. package/skill/scripts/lib/design-parser-colors.mjs +182 -0
  60. package/skill/scripts/lib/design-parser-extract.mjs +333 -0
  61. package/skill/scripts/lib/design-parser-sections.mjs +214 -0
  62. package/skill/scripts/lib/design-parser-yaml.mjs +135 -0
  63. package/skill/scripts/lib/design-parser.mjs +10 -783
  64. package/skill/scripts/live/manual-apply-chunk.mjs +151 -0
  65. package/skill/scripts/live/manual-apply-compact.mjs +122 -0
  66. package/skill/scripts/live/manual-apply-evidence.mjs +115 -0
  67. package/skill/scripts/live/manual-apply-log.mjs +179 -0
  68. package/skill/scripts/live/manual-apply-transaction.mjs +122 -0
  69. package/skill/scripts/live/manual-apply.mjs +65 -640
  70. package/skill/scripts/live/svelte-component-accept.mjs +248 -0
  71. package/skill/scripts/live/svelte-component-css.mjs +230 -0
  72. package/skill/scripts/live/svelte-component-markup.mjs +104 -0
  73. package/skill/scripts/live/svelte-component-scaffold.mjs +118 -0
  74. package/skill/scripts/live/svelte-component-session.mjs +158 -0
  75. package/skill/scripts/live/svelte-component.mjs +32 -792
  76. package/skill/scripts/live-accept-mutate.mjs +152 -0
  77. package/skill/scripts/live-accept-parse.mjs +370 -0
  78. package/skill/scripts/live-accept-scrub.mjs +59 -0
  79. package/skill/scripts/live-accept-search.mjs +58 -0
  80. package/skill/scripts/live-accept.mjs +15 -631
  81. package/skill/scripts/live-commit-manual-edits-paths.mjs +27 -0
  82. package/skill/scripts/live-commit-manual-edits-repair.mjs +166 -0
  83. package/skill/scripts/live-commit-manual-edits-rollback.mjs +231 -0
  84. package/skill/scripts/live-commit-manual-edits-utils.mjs +167 -0
  85. package/skill/scripts/live-commit-manual-edits-verify.mjs +356 -0
  86. package/skill/scripts/live-commit-manual-edits.mjs +24 -881
  87. package/skill/scripts/live-copy-edit-agent.mjs +16 -551
  88. package/skill/scripts/live-copy-edit-compact.mjs +137 -0
  89. package/skill/scripts/live-copy-edit-post-apply.mjs +175 -0
  90. package/skill/scripts/live-copy-edit-runners.mjs +297 -0
  91. package/skill/scripts/live-inject-csp.mjs +132 -0
  92. package/skill/scripts/live-inject-files.mjs +229 -0
  93. package/skill/scripts/live-inject-tag.mjs +114 -0
  94. package/skill/scripts/live-inject.mjs +13 -440
  95. package/skill/scripts/live-server-poll.mjs +232 -0
  96. package/skill/scripts/live-server-routes.mjs +449 -0
  97. package/skill/scripts/live-server-state.mjs +361 -0
  98. package/skill/scripts/live-server.mjs +10 -946
  99. package/skill/scripts/live-wrap-css.mjs +132 -0
  100. package/skill/scripts/live-wrap-manual-edit.mjs +153 -0
  101. package/skill/scripts/live-wrap-search.mjs +247 -0
  102. package/skill/scripts/live-wrap.mjs +21 -484
  103. package/skill/scripts/palette-seeds.mjs +401 -0
  104. package/skill/scripts/palette.mjs +1 -395
@@ -0,0 +1,151 @@
1
+ /**
2
+ * Splitting a staged manual-edit batch into op-count-bounded chunks for
3
+ * manual-apply.mjs, and normalizing/aggregating chunked-apply results.
4
+ *
5
+ * Split out of manual-apply.mjs. See that file for context.
6
+ */
7
+
8
+ const DEFAULT_MANUAL_EDIT_APPLY_CHUNK_SIZE = 3;
9
+ const MIN_MANUAL_EDIT_APPLY_CHUNK_SIZE = 1;
10
+ const MAX_MANUAL_EDIT_APPLY_CHUNK_SIZE = 20;
11
+
12
+ export function manualEditApplyChunkSize(env = process.env) {
13
+ const raw = Number(env.MONODESIGN_LIVE_MANUAL_EDIT_CHUNK_SIZE);
14
+ if (!Number.isFinite(raw)) return DEFAULT_MANUAL_EDIT_APPLY_CHUNK_SIZE;
15
+ const size = Math.trunc(raw);
16
+ return Math.max(MIN_MANUAL_EDIT_APPLY_CHUNK_SIZE, Math.min(MAX_MANUAL_EDIT_APPLY_CHUNK_SIZE, size));
17
+ }
18
+
19
+ export function countManualApplyOps(entriesOrBatch) {
20
+ const entries = Array.isArray(entriesOrBatch)
21
+ ? entriesOrBatch
22
+ : Array.isArray(entriesOrBatch?.entries) ? entriesOrBatch.entries : [];
23
+ let count = 0;
24
+ for (const entry of entries) count += Array.isArray(entry.ops) ? entry.ops.length : 0;
25
+ return count;
26
+ }
27
+
28
+ export function normalizeApplyChunkResult(result) {
29
+ const status = result?.status === 'partial' ? 'partial' : result?.status === 'error' ? 'error' : 'done';
30
+ return {
31
+ status,
32
+ message: typeof result?.message === 'string' ? result.message : null,
33
+ appliedEntryIds: Array.isArray(result?.appliedEntryIds) ? result.appliedEntryIds.filter((id) => typeof id === 'string') : [],
34
+ failed: Array.isArray(result?.failed) ? result.failed.filter(Boolean) : [],
35
+ files: Array.isArray(result?.files) ? result.files.filter((file) => typeof file === 'string') : [],
36
+ notes: Array.isArray(result?.notes) ? result.notes.filter((note) => typeof note === 'string') : [],
37
+ };
38
+ }
39
+
40
+ export function firstFailureReason(result) {
41
+ const first = Array.isArray(result?.failed) ? result.failed.find(Boolean) : null;
42
+ return first?.reason || first?.message || null;
43
+ }
44
+
45
+ export function markChunkEntriesFailed(failedByEntry, chunk, reason) {
46
+ for (const entryId of chunk.entryIds) {
47
+ if (failedByEntry.has(entryId)) continue;
48
+ failedByEntry.set(entryId, { entryId, reason, candidates: [] });
49
+ }
50
+ }
51
+
52
+ export function splitManualApplyBatch(batch, maxOps) {
53
+ const totalOpCount = countManualApplyOps(batch);
54
+ if (totalOpCount <= maxOps) {
55
+ return [{
56
+ batch,
57
+ meta: null,
58
+ entryIds: new Set((batch?.entries || []).map((entry) => entry.id).filter(Boolean)),
59
+ opCountsByEntry: new Map((batch?.entries || []).map((entry) => [entry.id, Array.isArray(entry.ops) ? entry.ops.length : 0])),
60
+ }];
61
+ }
62
+
63
+ const rawChunks = [];
64
+ let current = createManualApplyChunkBuilder();
65
+ for (const entry of batch?.entries || []) {
66
+ const ops = entry.ops || [];
67
+ if (ops.length <= maxOps) {
68
+ if (current.opCount > 0 && current.opCount + ops.length > maxOps) {
69
+ rawChunks.push(current);
70
+ current = createManualApplyChunkBuilder();
71
+ }
72
+ for (const op of ops) addOpToManualApplyChunk(current, entry, op);
73
+ continue;
74
+ }
75
+ if (current.opCount > 0) {
76
+ rawChunks.push(current);
77
+ current = createManualApplyChunkBuilder();
78
+ }
79
+ for (const op of ops) {
80
+ if (current.opCount >= maxOps) {
81
+ rawChunks.push(current);
82
+ current = createManualApplyChunkBuilder();
83
+ }
84
+ addOpToManualApplyChunk(current, entry, op);
85
+ }
86
+ }
87
+ if (current.opCount > 0) rawChunks.push(current);
88
+
89
+ return rawChunks.map((chunk, index) => ({
90
+ batch: {
91
+ ...batch,
92
+ count: chunk.opCount,
93
+ entries: chunk.entries,
94
+ ops: chunk.ops,
95
+ candidates: filterManualApplyChunkCandidates(batch, chunk.refsByEntry),
96
+ context: {
97
+ ...(batch?.context || {}),
98
+ totalEntries: chunk.entries.length,
99
+ totalOps: chunk.opCount,
100
+ chunkIndex: index + 1,
101
+ chunkTotal: rawChunks.length,
102
+ totalApplyOps: totalOpCount,
103
+ },
104
+ },
105
+ meta: {
106
+ index: index + 1,
107
+ total: rawChunks.length,
108
+ opCount: chunk.opCount,
109
+ totalOpCount,
110
+ },
111
+ entryIds: new Set(chunk.entries.map((entry) => entry.id).filter(Boolean)),
112
+ opCountsByEntry: chunk.opCountsByEntry,
113
+ }));
114
+ }
115
+
116
+ function createManualApplyChunkBuilder() {
117
+ return {
118
+ entries: [],
119
+ entryById: new Map(),
120
+ entryIds: new Set(),
121
+ ops: [],
122
+ refsByEntry: new Map(),
123
+ opCountsByEntry: new Map(),
124
+ opCount: 0,
125
+ };
126
+ }
127
+
128
+ function addOpToManualApplyChunk(chunk, entry, op) {
129
+ let chunkEntry = chunk.entryById.get(entry.id);
130
+ if (!chunkEntry) {
131
+ chunkEntry = { ...entry, ops: [] };
132
+ chunk.entryById.set(entry.id, chunkEntry);
133
+ chunk.entryIds.add(entry.id);
134
+ chunk.entries.push(chunkEntry);
135
+ }
136
+ chunkEntry.ops.push(op);
137
+ chunk.ops.push({ ...op, entryId: op.entryId || entry.id });
138
+ if (!chunk.refsByEntry.has(entry.id)) chunk.refsByEntry.set(entry.id, new Set());
139
+ if (op.ref) chunk.refsByEntry.get(entry.id).add(op.ref);
140
+ chunk.opCountsByEntry.set(entry.id, (chunk.opCountsByEntry.get(entry.id) || 0) + 1);
141
+ chunk.opCount += 1;
142
+ }
143
+
144
+ function filterManualApplyChunkCandidates(batch, refsByEntry) {
145
+ return (batch?.candidates || []).filter((candidate) => {
146
+ const refs = refsByEntry.get(candidate.entryId);
147
+ if (!refs) return false;
148
+ if (!candidate.ref) return true;
149
+ return refs.has(candidate.ref);
150
+ });
151
+ }
@@ -0,0 +1,122 @@
1
+ /**
2
+ * Compacting a staged manual-edit batch into the smaller shape sent to the
3
+ * chat agent (dropping evidence the agent doesn't need, truncating long
4
+ * text) for manual-apply.mjs.
5
+ *
6
+ * Split out of manual-apply.mjs. See that file for context.
7
+ */
8
+ import { summarizeManualLogFile } from './manual-apply-log.mjs';
9
+
10
+ const MANUAL_APPLY_COMPACT_TEXT_LIMIT = 240;
11
+ const MANUAL_APPLY_COMPACT_NEARBY_LIMIT = 4;
12
+
13
+ export function compactManualApplyBatch(batch = {}, cwd = process.cwd()) {
14
+ const entries = (batch.entries || []).map(compactManualApplyEntry);
15
+ const candidates = compactManualApplyCandidates(batch.candidates || [], cwd);
16
+ return {
17
+ version: batch.version,
18
+ pageUrl: batch.pageUrl || null,
19
+ count: batch.count,
20
+ entries,
21
+ ops: entries.flatMap((entry) => entry.ops.map((op) => ({ ...op, entryId: entry.id }))),
22
+ candidates: candidates.length > 0 ? candidates : undefined,
23
+ context: batch.context ? {
24
+ bufferPath: batch.context.bufferPath,
25
+ totalEntries: batch.context.totalEntries,
26
+ totalOps: batch.context.totalOps,
27
+ chunkIndex: batch.context.chunkIndex,
28
+ chunkTotal: batch.context.chunkTotal,
29
+ totalApplyOps: batch.context.totalApplyOps,
30
+ } : undefined,
31
+ };
32
+ }
33
+
34
+ export function compactManualApplyCandidates(candidates, cwd = process.cwd()) {
35
+ return (Array.isArray(candidates) ? candidates : [])
36
+ .slice(0, 24)
37
+ .map((candidate) => ({
38
+ entryId: candidate.entryId,
39
+ ref: candidate.ref,
40
+ sourceHint: compactManualApplySourceMatch(candidate.sourceHint, cwd),
41
+ textMatches: compactManualApplySourceMatches(candidate.textMatches, 8, cwd),
42
+ objectKeyMatches: compactManualApplySourceMatches(candidate.objectKeyMatches, 8, cwd),
43
+ contextTextMatches: compactManualApplySourceMatches(candidate.contextTextMatches, 8, cwd),
44
+ locatorMatches: compactManualApplySourceMatches(candidate.locatorMatches, 6, cwd),
45
+ }));
46
+ }
47
+
48
+ function compactManualApplySourceMatches(matches, limit, cwd) {
49
+ return (Array.isArray(matches) ? matches : [])
50
+ .slice(0, limit)
51
+ .map((match) => compactManualApplySourceMatch(match, cwd))
52
+ .filter(Boolean);
53
+ }
54
+
55
+ function compactManualApplySourceMatch(match, cwd) {
56
+ if (!match || typeof match !== 'object') return null;
57
+ const file = match.relativeFile || match.file;
58
+ if (!file && !match.line) return null;
59
+ return {
60
+ file: summarizeManualLogFile(file, cwd),
61
+ line: match.line || null,
62
+ column: match.column || null,
63
+ reason: match.reason || match.kind || undefined,
64
+ status: match.status || undefined,
65
+ };
66
+ }
67
+
68
+ function compactManualApplyEntry(entry = {}) {
69
+ return {
70
+ id: entry.id,
71
+ pageUrl: entry.pageUrl,
72
+ stagedAt: entry.stagedAt || null,
73
+ element: compactManualApplyContext(entry.element),
74
+ ops: (entry.ops || []).map(compactManualApplyOp),
75
+ };
76
+ }
77
+
78
+ function compactManualApplyOp(op = {}) {
79
+ return {
80
+ entryId: op.entryId,
81
+ ref: op.ref,
82
+ contextRef: op.contextRef,
83
+ tag: op.tag,
84
+ elementId: op.elementId,
85
+ classes: Array.isArray(op.classes) ? op.classes : [],
86
+ originalText: op.originalText,
87
+ newText: op.newText,
88
+ deleted: op.deleted === true || undefined,
89
+ sourceHint: op.sourceHint || null,
90
+ leaf: compactManualApplyContext(op.leaf),
91
+ nearbyEditableTexts: compactNearbyManualEditTexts(op.nearbyEditableTexts),
92
+ container: compactManualApplyContext(op.container),
93
+ contextHints: Array.isArray(op.contextHints) ? op.contextHints.slice(0, 8) : undefined,
94
+ };
95
+ }
96
+
97
+ function compactManualApplyContext(value) {
98
+ if (!value || typeof value !== 'object') return null;
99
+ return {
100
+ ref: value.ref,
101
+ tagName: value.tagName || value.tag || null,
102
+ id: value.id || null,
103
+ classes: Array.isArray(value.classes) ? value.classes : [],
104
+ textContent: truncateManualApplyText(value.textContent, MANUAL_APPLY_COMPACT_TEXT_LIMIT),
105
+ };
106
+ }
107
+
108
+ function compactNearbyManualEditTexts(items) {
109
+ return (Array.isArray(items) ? items : [])
110
+ .slice(0, MANUAL_APPLY_COMPACT_NEARBY_LIMIT)
111
+ .map((item) => typeof item === 'string' ? { text: truncateManualApplyText(item, MANUAL_APPLY_COMPACT_TEXT_LIMIT) } : {
112
+ ref: item?.ref,
113
+ tag: item?.tag,
114
+ classes: Array.isArray(item?.classes) ? item.classes : [],
115
+ text: truncateManualApplyText(item?.text, MANUAL_APPLY_COMPACT_TEXT_LIMIT),
116
+ });
117
+ }
118
+
119
+ function truncateManualApplyText(value, max) {
120
+ if (typeof value !== 'string') return value || null;
121
+ return value.length > max ? value.slice(0, max) : value;
122
+ }
@@ -0,0 +1,115 @@
1
+ /**
2
+ * Evidence-file and rollback-snapshot helpers for manual-apply.mjs: writing
3
+ * the staged batch to disk for the chat agent to read, collecting the source
4
+ * files a batch touches, and snapshotting/restoring them around an Apply
5
+ * attempt.
6
+ *
7
+ * Split out of manual-apply.mjs. See that file for context.
8
+ */
9
+ import fs from 'node:fs';
10
+ import path from 'node:path';
11
+ import { getLiveDir } from '../lib/monodesign-paths.mjs';
12
+
13
+ export function writeManualApplyEvidence(eventId, batch, cwd = process.cwd()) {
14
+ const dir = manualApplyEvidenceDir(cwd);
15
+ fs.mkdirSync(dir, { recursive: true });
16
+ const evidencePath = path.join(dir, `${eventId}.json`);
17
+ fs.writeFileSync(evidencePath, `${JSON.stringify(batch, null, 2)}\n`, 'utf-8');
18
+ return evidencePath;
19
+ }
20
+
21
+ export function manualApplyEvidenceDir(cwd = process.cwd()) {
22
+ return path.join(getLiveDir(cwd), 'manual-edit-evidence');
23
+ }
24
+
25
+ export function normalizeManualApplyEvidencePath(evidencePath, cwd = process.cwd()) {
26
+ if (!evidencePath || typeof evidencePath !== 'string') return null;
27
+ const fullPath = path.isAbsolute(evidencePath) ? evidencePath : path.resolve(cwd, evidencePath);
28
+ const evidenceDir = manualApplyEvidenceDir(cwd);
29
+ const relative = path.relative(evidenceDir, fullPath).split(path.sep).join('/');
30
+ if (!relative || relative.startsWith('..') || path.isAbsolute(relative)) return null;
31
+ if (path.extname(relative) !== '.json') return null;
32
+ return fullPath;
33
+ }
34
+
35
+ export function removeManualApplyEvidence(evidencePath, cwd = process.cwd()) {
36
+ const fullPath = normalizeManualApplyEvidencePath(evidencePath, cwd);
37
+ if (!fullPath) return false;
38
+ try {
39
+ fs.unlinkSync(fullPath);
40
+ return true;
41
+ } catch {
42
+ return false;
43
+ }
44
+ }
45
+
46
+ export function collectManualApplyFiles(batch, extraFiles = [], cwd = process.cwd()) {
47
+ const files = [];
48
+ for (const entry of batch?.entries || []) {
49
+ for (const op of entry.ops || []) files.push(op.sourceHint?.file);
50
+ }
51
+ for (const candidate of batch?.candidates || []) {
52
+ files.push(candidate.sourceHint?.relativeFile, candidate.sourceHint?.file);
53
+ for (const item of candidate.textMatches || []) files.push(item.file);
54
+ for (const item of candidate.objectKeyMatches || []) files.push(item.file);
55
+ for (const item of candidate.locatorMatches || []) files.push(item.file);
56
+ for (const item of candidate.contextTextMatches || []) files.push(item.file);
57
+ }
58
+ files.push(...(extraFiles || []));
59
+ return [...new Set(files)]
60
+ .map((file) => normalizeProjectFile(file, cwd))
61
+ .filter(Boolean);
62
+ }
63
+
64
+ export function normalizeProjectFile(file, cwd = process.cwd()) {
65
+ if (!file || typeof file !== 'string') return null;
66
+ const absolute = path.isAbsolute(file) ? file : path.resolve(cwd, file);
67
+ const relative = path.relative(cwd, absolute).split(path.sep).join('/');
68
+ if (!relative || relative.startsWith('..') || path.isAbsolute(relative)) return null;
69
+ return relative;
70
+ }
71
+
72
+ export function rollbackApplySnapshot(
73
+ batch,
74
+ rollbackSnapshot,
75
+ extraFiles = [],
76
+ _reason = 'manual_edit_apply_snapshot_rollback',
77
+ cwd = process.cwd(),
78
+ ) {
79
+ const scope = collectManualApplyFiles(batch, extraFiles, cwd);
80
+ const rolledBackFiles = [];
81
+ const rollbackFailures = [];
82
+ for (const relativeFile of scope) {
83
+ const before = rollbackSnapshot?.get(relativeFile);
84
+ if (!before) continue;
85
+ const absolute = path.resolve(cwd, relativeFile);
86
+ try {
87
+ if (before.exists) {
88
+ fs.mkdirSync(path.dirname(absolute), { recursive: true });
89
+ fs.writeFileSync(absolute, before.content, 'utf-8');
90
+ } else if (fs.existsSync(absolute)) {
91
+ fs.rmSync(absolute);
92
+ }
93
+ rolledBackFiles.push(relativeFile);
94
+ } catch (err) {
95
+ rollbackFailures.push({ file: relativeFile, reason: 'restore_failed', message: err.message || String(err) });
96
+ }
97
+ }
98
+ return { rolledBackFiles, rollbackFailures };
99
+ }
100
+
101
+ export function snapshotApplyEventFiles(batch, cwd = process.cwd()) {
102
+ const snapshot = new Map();
103
+ for (const relativeFile of collectManualApplyFiles(batch, [], cwd)) {
104
+ const absolute = path.resolve(cwd, relativeFile);
105
+ try {
106
+ snapshot.set(relativeFile, {
107
+ exists: fs.existsSync(absolute),
108
+ content: fs.existsSync(absolute) ? fs.readFileSync(absolute, 'utf-8') : '',
109
+ });
110
+ } catch {
111
+ // If a file cannot be read before dispatch, do not attempt late rollback.
112
+ }
113
+ }
114
+ return snapshot;
115
+ }
@@ -0,0 +1,179 @@
1
+ /**
2
+ * Result validation and activity-log summarizing for manual-apply.mjs: the
3
+ * shape the chat agent's reply must match, and compacting file paths/text
4
+ * for readable activity log entries.
5
+ *
6
+ * Split out of manual-apply.mjs. See that file for context.
7
+ */
8
+ import path from 'node:path';
9
+ import { countManualApplyOps } from './manual-apply-chunk.mjs';
10
+ import { collectManualApplyFiles } from './manual-apply-evidence.mjs';
11
+
12
+ function manualApplyResultShapeHint(eventId = 'EVENT_ID') {
13
+ return `Use live-poll.mjs --reply ${eventId} done --data '{"status":"done","appliedEntryIds":["ENTRY_ID"],"failed":[],"files":["src/page.html"],"notes":[]}'`;
14
+ }
15
+
16
+ function invalidManualApplyResult(reason, eventId, extra = {}) {
17
+ return {
18
+ ok: false,
19
+ body: {
20
+ error: 'invalid_manual_apply_result',
21
+ reason,
22
+ hint: manualApplyResultShapeHint(eventId),
23
+ ...extra,
24
+ },
25
+ };
26
+ }
27
+
28
+ export function validateManualApplyResultMessage(msg, deferred) {
29
+ const data = msg?.data;
30
+ const eventId = msg?.id || deferred?.event?.id || 'EVENT_ID';
31
+ if (!data || typeof data !== 'object' || Array.isArray(data)) {
32
+ return invalidManualApplyResult('missing_result_data', eventId);
33
+ }
34
+ if ('entries' in data || 'ops' in data) {
35
+ return invalidManualApplyResult('summary_result_not_allowed', eventId);
36
+ }
37
+ if (!['done', 'partial', 'error'].includes(data.status)) {
38
+ return invalidManualApplyResult('invalid_status', eventId, { status: data.status ?? null });
39
+ }
40
+
41
+ for (const key of ['appliedEntryIds', 'failed', 'files', 'notes']) {
42
+ if (!Array.isArray(data[key])) {
43
+ return invalidManualApplyResult(`${key}_must_be_array`, eventId);
44
+ }
45
+ }
46
+
47
+ for (const [index, value] of data.appliedEntryIds.entries()) {
48
+ if (typeof value !== 'string' || !value) {
49
+ return invalidManualApplyResult('appliedEntryIds_must_contain_strings', eventId, { index });
50
+ }
51
+ }
52
+ for (const [index, value] of data.files.entries()) {
53
+ if (typeof value !== 'string' || !value) {
54
+ return invalidManualApplyResult('files_must_contain_strings', eventId, { index });
55
+ }
56
+ }
57
+ for (const [index, value] of data.notes.entries()) {
58
+ if (typeof value !== 'string') {
59
+ return invalidManualApplyResult('notes_must_contain_strings', eventId, { index });
60
+ }
61
+ }
62
+ for (const [index, item] of data.failed.entries()) {
63
+ if (!item || typeof item !== 'object' || Array.isArray(item)) {
64
+ return invalidManualApplyResult('failed_must_contain_objects', eventId, { index });
65
+ }
66
+ if (typeof item.entryId !== 'string' || !item.entryId) {
67
+ return invalidManualApplyResult('failed_entryId_required', eventId, { index });
68
+ }
69
+ if (typeof item.reason !== 'string' || !item.reason) {
70
+ return invalidManualApplyResult('failed_reason_required', eventId, { index });
71
+ }
72
+ }
73
+
74
+ const eventEntryIds = new Set((deferred?.batch?.entries || []).map((entry) => entry.id).filter(Boolean));
75
+ for (const entryId of data.appliedEntryIds) {
76
+ if (eventEntryIds.size > 0 && !eventEntryIds.has(entryId)) {
77
+ return invalidManualApplyResult('applied_entry_id_not_in_event', eventId, { entryId });
78
+ }
79
+ }
80
+ for (const item of data.failed) {
81
+ if (eventEntryIds.size > 0 && !eventEntryIds.has(item.entryId)) {
82
+ return invalidManualApplyResult('failed_entry_id_not_in_event', eventId, { entryId: item.entryId });
83
+ }
84
+ }
85
+
86
+ if (data.status === 'done') {
87
+ if (data.failed.length > 0) {
88
+ return invalidManualApplyResult('done_result_has_failed_entries', eventId);
89
+ }
90
+ if (countManualApplyOps(deferred?.batch) > 0 && data.appliedEntryIds.length === 0) {
91
+ return invalidManualApplyResult('done_result_missing_applied_entry_ids', eventId);
92
+ }
93
+ }
94
+ if (data.status === 'partial' && data.appliedEntryIds.length === 0 && data.failed.length === 0) {
95
+ return invalidManualApplyResult('partial_result_has_no_entries', eventId);
96
+ }
97
+ if (data.status === 'error' && data.appliedEntryIds.length > 0) {
98
+ return invalidManualApplyResult('error_result_has_applied_entries', eventId);
99
+ }
100
+
101
+ return {
102
+ ok: true,
103
+ result: {
104
+ status: data.status,
105
+ message: typeof data.message === 'string' ? data.message : undefined,
106
+ appliedEntryIds: data.appliedEntryIds,
107
+ failed: data.failed,
108
+ files: data.files,
109
+ notes: data.notes,
110
+ },
111
+ };
112
+ }
113
+
114
+ function manualApplyReplyCommand(eventOrId = 'EVENT_ID') {
115
+ const id = typeof eventOrId === 'string' ? eventOrId : eventOrId?.id || 'EVENT_ID';
116
+ return `live-poll.mjs --reply ${id} done --data '<json>'`;
117
+ }
118
+
119
+ export function buildManualApplyAgentAction(eventOrId = 'EVENT_ID') {
120
+ return {
121
+ kind: 'manual_edit_apply',
122
+ required: 'apply_source_edits_then_reply',
123
+ replyCommand: manualApplyReplyCommand(eventOrId),
124
+ warning: 'Polling only leases this work item; it does not commit source edits.',
125
+ };
126
+ }
127
+
128
+ export function summarizeManualApplyEvent(event = {}, batch = event.batch, cwd = process.cwd()) {
129
+ const entries = Array.isArray(batch?.entries) ? batch.entries : [];
130
+ const opCount = entries.reduce((sum, entry) => sum + (Array.isArray(entry.ops) ? entry.ops.length : 0), 0);
131
+ return {
132
+ pageUrl: event.pageUrl || null,
133
+ chunk: event.chunk || null,
134
+ entryCount: entries.length,
135
+ opCount,
136
+ files: collectManualApplyFiles(batch, [], cwd),
137
+ };
138
+ }
139
+
140
+ export function summarizeManualApplyFailures(failed, cwd = process.cwd()) {
141
+ if (!Array.isArray(failed)) return [];
142
+ return failed.slice(0, 20).map((item) => ({
143
+ id: item.id || item.entryId || null,
144
+ reason: item.reason || item.message || 'failed',
145
+ message: compactManualLogText(item.message, 300),
146
+ files: Array.isArray(item.files) ? item.files.slice(0, 12).map((file) => summarizeManualLogFile(file, cwd)).filter(Boolean) : undefined,
147
+ checks: summarizeManualDiagnostics(item.checks, cwd),
148
+ failures: summarizeManualDiagnostics(item.failures, cwd),
149
+ candidates: summarizeManualDiagnostics(item.candidates, cwd),
150
+ }));
151
+ }
152
+
153
+ export function summarizeManualDiagnostics(items, cwd = process.cwd()) {
154
+ if (!Array.isArray(items) || items.length === 0) return undefined;
155
+ return items.slice(0, 12).map((item) => ({
156
+ reason: item.reason || item.kind || undefined,
157
+ detail: compactManualLogText(item.detail, 220),
158
+ message: compactManualLogText(item.message, 300),
159
+ file: summarizeManualLogFile(item.file || item.relativeFile, cwd),
160
+ line: item.line || undefined,
161
+ ref: compactManualLogText(item.ref, 180),
162
+ marker: compactManualLogText(item.marker, 120),
163
+ files: Array.isArray(item.files) ? item.files.slice(0, 8).map((file) => summarizeManualLogFile(file, cwd)).filter(Boolean) : undefined,
164
+ }));
165
+ }
166
+
167
+ export function summarizeManualLogFile(file, cwd = process.cwd()) {
168
+ if (!file || typeof file !== 'string') return undefined;
169
+ if (!path.isAbsolute(file)) return file;
170
+ const relative = path.relative(cwd, file).split(path.sep).join('/');
171
+ return relative && !relative.startsWith('..') && !path.isAbsolute(relative) ? relative : file;
172
+ }
173
+
174
+ export function compactManualLogText(value, max = 200) {
175
+ if (typeof value !== 'string') return undefined;
176
+ const normalized = value.replace(/\s+/g, ' ').trim();
177
+ if (normalized.length <= max) return normalized;
178
+ return `${normalized.slice(0, max)}... [truncated ${normalized.length - max} chars]`;
179
+ }
@@ -0,0 +1,122 @@
1
+ /**
2
+ * Whole-batch rollback transaction for manual-apply.mjs: snapshotting every
3
+ * file a batch touches before dispatch and restoring them if the batch never
4
+ * gets fully applied (e.g. the live server restarts mid-Apply).
5
+ *
6
+ * Split out of manual-apply.mjs. See that file for context.
7
+ */
8
+ import { randomUUID } from 'node:crypto';
9
+ import fs from 'node:fs';
10
+ import path from 'node:path';
11
+ import { getLiveDir } from '../lib/monodesign-paths.mjs';
12
+ import { readBuffer as readManualEditsBuffer } from './manual-edits-buffer.mjs';
13
+ import { collectManualApplyFiles, normalizeProjectFile } from './manual-apply-evidence.mjs';
14
+ import { summarizeManualDiagnostics, summarizeManualLogFile } from './manual-apply-log.mjs';
15
+
16
+ export function manualApplyTransactionPath(cwd = process.cwd()) {
17
+ return path.join(getLiveDir(cwd), 'manual-edit-apply-transaction.json');
18
+ }
19
+
20
+ export function readManualApplyTransaction(cwd = process.cwd()) {
21
+ const file = manualApplyTransactionPath(cwd);
22
+ if (!fs.existsSync(file)) return null;
23
+ try {
24
+ return JSON.parse(fs.readFileSync(file, 'utf-8'));
25
+ } catch {
26
+ return null;
27
+ }
28
+ }
29
+
30
+ export function writeManualApplyTransaction({ cwd = process.cwd(), pageUrl = null, batch }) {
31
+ const file = manualApplyTransactionPath(cwd);
32
+ const files = collectManualApplyFiles(batch, [], cwd);
33
+ const transaction = {
34
+ version: 1,
35
+ id: randomUUID().replace(/-/g, '').slice(0, 8),
36
+ createdAt: new Date().toISOString(),
37
+ pageUrl,
38
+ entryIds: (batch?.entries || []).map((entry) => entry.id).filter(Boolean),
39
+ files: files.map((relativeFile) => {
40
+ const absolute = path.resolve(cwd, relativeFile);
41
+ const exists = fs.existsSync(absolute);
42
+ return {
43
+ file: relativeFile,
44
+ exists,
45
+ content: exists ? fs.readFileSync(absolute, 'utf-8') : '',
46
+ };
47
+ }),
48
+ };
49
+ fs.mkdirSync(path.dirname(file), { recursive: true });
50
+ fs.writeFileSync(`${file}.tmp`, `${JSON.stringify(transaction, null, 2)}\n`, 'utf-8');
51
+ fs.renameSync(`${file}.tmp`, file);
52
+ return transaction;
53
+ }
54
+
55
+ export function clearManualApplyTransaction(cwd = process.cwd(), transactionId = null) {
56
+ const file = manualApplyTransactionPath(cwd);
57
+ if (!fs.existsSync(file)) return false;
58
+ if (transactionId) {
59
+ const existing = readManualApplyTransaction(cwd);
60
+ if (existing?.id && existing.id !== transactionId) return false;
61
+ }
62
+ try {
63
+ fs.unlinkSync(file);
64
+ return true;
65
+ } catch {
66
+ return false;
67
+ }
68
+ }
69
+
70
+
71
+ export function rollbackManualApplyTransaction({
72
+ cwd = process.cwd(),
73
+ pageUrl = null,
74
+ reason = 'manual_edit_transaction_rollback',
75
+ recordManualEditActivity = null,
76
+ } = {}) {
77
+ const transaction = readManualApplyTransaction(cwd);
78
+ if (!transaction) return null;
79
+ if (pageUrl && transaction.pageUrl && transaction.pageUrl !== pageUrl) return null;
80
+
81
+ let pendingIds = new Set();
82
+ try {
83
+ const buffer = readManualEditsBuffer(cwd);
84
+ pendingIds = new Set((buffer.entries || []).map((entry) => entry.id).filter(Boolean));
85
+ } catch {
86
+ pendingIds = new Set(transaction.entryIds || []);
87
+ }
88
+ const shouldRollback = (transaction.entryIds || []).some((id) => pendingIds.has(id));
89
+ if (!shouldRollback) {
90
+ clearManualApplyTransaction(cwd, transaction.id);
91
+ return { id: transaction.id, reason, rolledBackFiles: [], rollbackFailures: [], skipped: 'entries_not_pending' };
92
+ }
93
+
94
+ const rolledBackFiles = [];
95
+ const rollbackFailures = [];
96
+ for (const item of transaction.files || []) {
97
+ const relativeFile = normalizeProjectFile(item.file, cwd);
98
+ if (!relativeFile) continue;
99
+ const absolute = path.resolve(cwd, relativeFile);
100
+ try {
101
+ if (item.exists) {
102
+ fs.mkdirSync(path.dirname(absolute), { recursive: true });
103
+ fs.writeFileSync(absolute, item.content || '', 'utf-8');
104
+ } else if (fs.existsSync(absolute)) {
105
+ fs.rmSync(absolute);
106
+ }
107
+ rolledBackFiles.push(relativeFile);
108
+ } catch (err) {
109
+ rollbackFailures.push({ file: relativeFile, reason: 'restore_failed', message: err.message || String(err) });
110
+ }
111
+ }
112
+ clearManualApplyTransaction(cwd, transaction.id);
113
+ recordManualEditActivity?.('manual_edit_transaction_rolled_back', {
114
+ id: transaction.id,
115
+ pageUrl: transaction.pageUrl || null,
116
+ reason,
117
+ entryIds: transaction.entryIds || [],
118
+ rolledBackFiles: rolledBackFiles.map((file) => summarizeManualLogFile(file, cwd)).filter(Boolean),
119
+ rollbackFailures: summarizeManualDiagnostics(rollbackFailures, cwd),
120
+ });
121
+ return { id: transaction.id, reason, rolledBackFiles, rollbackFailures };
122
+ }