bmad-plus 0.24.0 → 0.25.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 (87) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/README.md +26 -15
  3. package/SECURITY.md +2 -2
  4. package/package.json +2 -2
  5. package/readme-international/README.de.md +26 -15
  6. package/readme-international/README.es.md +26 -15
  7. package/readme-international/README.fr.md +26 -15
  8. package/src/bmad-plus/data/role-triggers.yaml +26 -0
  9. package/src/bmad-plus/module.yaml +34 -0
  10. package/src/bmad-plus/packs/pack-dev-studio/categories/analysis/tech-writer-agent.md +7 -0
  11. package/src/bmad-plus/packs/pack-ghostwriter/SKILL.md +23 -0
  12. package/src/bmad-plus/packs/pack-ghostwriter/bmad-skill-manifest.yaml +13 -0
  13. package/src/bmad-plus/packs/pack-ghostwriter/ghostwriter.md +28 -0
  14. package/src/bmad-plus/packs/pack-ghostwriter/intake.yaml +73 -0
  15. package/src/bmad-plus/packs/pack-ghostwriter/languages/en.md +11 -0
  16. package/src/bmad-plus/packs/pack-ghostwriter/languages/fr-FR.md +15 -0
  17. package/src/bmad-plus/packs/pack-ghostwriter/languages/glossary.md +14 -0
  18. package/src/bmad-plus/packs/pack-ghostwriter/languages/pt-BR.md +11 -0
  19. package/src/bmad-plus/packs/pack-ghostwriter/profiles/README.md +22 -0
  20. package/src/bmad-plus/packs/pack-ghostwriter/profiles/author-note-fr.yaml +20 -0
  21. package/src/bmad-plus/packs/pack-ghostwriter/profiles/character-dialogue-fr.yaml +20 -0
  22. package/src/bmad-plus/packs/pack-ghostwriter/profiles/customer-reply-pt-br.yaml +20 -0
  23. package/src/bmad-plus/packs/pack-ghostwriter/profiles/service-report-en.yaml +20 -0
  24. package/src/bmad-plus/packs/pack-ghostwriter/references/evaluation.md +5 -0
  25. package/src/bmad-plus/packs/pack-ghostwriter/references/provenance.md +32 -0
  26. package/src/bmad-plus/packs/pack-ghostwriter/schemas/config.schema.json +82 -0
  27. package/src/bmad-plus/packs/pack-ghostwriter/schemas/review-result.schema.json +212 -0
  28. package/src/bmad-plus/packs/pack-ghostwriter/schemas/run-manifest.schema.json +197 -0
  29. package/src/bmad-plus/packs/pack-ghostwriter/schemas/voice-profile.schema.json +55 -0
  30. package/src/bmad-plus/packs/pack-ghostwriter/shared/catalog.json +14 -0
  31. package/src/bmad-plus/packs/pack-ghostwriter/shared/editorial-contract.md +38 -0
  32. package/src/bmad-plus/packs/pack-ghostwriter/shared/execution.md +44 -0
  33. package/src/bmad-plus/packs/pack-ghostwriter/tools/inspect-typography.cjs +273 -0
  34. package/src/bmad-plus/packs/pack-ghostwriter/workflows/agent-output-review.md +25 -0
  35. package/src/bmad-plus/packs/pack-ghostwriter/workflows/draft.md +26 -0
  36. package/src/bmad-plus/packs/pack-ghostwriter/workflows/humanize.md +52 -0
  37. package/src/bmad-plus/packs/pack-ghostwriter/workflows/improve.md +26 -0
  38. package/src/bmad-plus/packs/pack-ghostwriter/workflows/localize.md +24 -0
  39. package/src/bmad-plus/packs/pack-ghostwriter/workflows/voice-profile.md +24 -0
  40. package/src/bmad-plus/packs/pack-ghostwriter/workshops/council/README.md +57 -0
  41. package/src/bmad-plus/packs/pack-ghostwriter/workshops/council/brief.md +23 -0
  42. package/src/bmad-plus/packs/pack-ghostwriter/workshops/council/check.cjs +128 -0
  43. package/src/bmad-plus/packs/pack-ghostwriter/workshops/council/jury.json +129 -0
  44. package/src/bmad-plus/packs/pack-ghostwriter/workshops/council/opening.md +1 -0
  45. package/src/bmad-plus/packs/pack-ghostwriter/workshops/council/select.cjs +54 -0
  46. package/src/bmad-plus/packs/pack-ghostwriter/workshops/freytag-pyramid/README.md +32 -0
  47. package/src/bmad-plus/packs/pack-ghostwriter/workshops/freytag-pyramid/specialist.md +12 -0
  48. package/src/bmad-plus/packs/pack-ghostwriter/workshops/hero-journey/README.md +44 -0
  49. package/src/bmad-plus/packs/pack-ghostwriter/workshops/hero-journey/specialist.md +17 -0
  50. package/src/bmad-plus/packs/pack-ghostwriter/workshops/in-medias-res/README.md +15 -0
  51. package/src/bmad-plus/packs/pack-ghostwriter/workshops/in-medias-res/specialist.md +15 -0
  52. package/src/bmad-plus/packs/pack-ghostwriter/workshops/kishotenketsu/README.md +26 -0
  53. package/src/bmad-plus/packs/pack-ghostwriter/workshops/kishotenketsu/specialist.md +10 -0
  54. package/src/bmad-plus/packs/pack-ghostwriter/workshops/narrative-arc/README.md +24 -0
  55. package/src/bmad-plus/packs/pack-ghostwriter/workshops/narrative-arc/specialist.md +9 -0
  56. package/src/bmad-plus/packs/pack-ghostwriter/workshops/snowflake-method/README.md +15 -0
  57. package/src/bmad-plus/packs/pack-ghostwriter/workshops/snowflake-method/specialist.md +15 -0
  58. package/src/bmad-plus/packs/pack-ghostwriter/workshops/story-circle/README.md +28 -0
  59. package/src/bmad-plus/packs/pack-ghostwriter/workshops/story-circle/specialist.md +10 -0
  60. package/src/bmad-plus/packs/pack-ghostwriter/workshops/story-spine/README.md +28 -0
  61. package/src/bmad-plus/packs/pack-ghostwriter/workshops/story-spine/specialist.md +9 -0
  62. package/src/bmad-plus/packs/pack-ghostwriter/workshops/three-act/README.md +39 -0
  63. package/src/bmad-plus/packs/pack-ghostwriter/workshops/three-act/briefs/objection.md +27 -0
  64. package/src/bmad-plus/packs/pack-ghostwriter/workshops/three-act/briefs/proposal.md +15 -0
  65. package/src/bmad-plus/packs/pack-ghostwriter/workshops/three-act/example.md +11 -0
  66. package/src/bmad-plus/packs/pack-ghostwriter/workshops/three-act/objections.json +103 -0
  67. package/src/bmad-plus/packs/pack-ghostwriter/workshops/three-act/proposals.json +79 -0
  68. package/src/bmad-plus/packs/pack-ghostwriter/workshops/three-act/specialist.md +9 -0
  69. package/src/bmad-plus/skills/ghostwriter-edit/SKILL.md +16 -0
  70. package/src/bmad-plus/skills/ghostwriter-humanize/SKILL.md +16 -0
  71. package/src/bmad-plus/skills/ghostwriter-localize/SKILL.md +16 -0
  72. package/src/bmad-plus/skills/ghostwriter-verify/SKILL.md +16 -0
  73. package/src/bmad-plus/skills/ghostwriter-voice/SKILL.md +16 -0
  74. package/src/bmad-plus/skills/ghostwriter-write/SKILL.md +16 -0
  75. package/tools/cli/bmad-plus-cli.js +1 -0
  76. package/tools/cli/commands/ghostwriter.js +76 -0
  77. package/tools/cli/commands/install.js +4 -0
  78. package/tools/cli/lib/ghostwriter-fidelity.js +352 -0
  79. package/tools/cli/lib/ghostwriter-manifest.js +238 -0
  80. package/tools/cli/lib/ghostwriter-nexus.js +542 -0
  81. package/tools/cli/lib/ghostwriter-project.js +304 -0
  82. package/tools/cli/lib/ghostwriter-quantities.js +239 -0
  83. package/tools/cli/lib/ghostwriter-structured.js +154 -0
  84. package/tools/cli/lib/ghostwriter.js +263 -0
  85. package/tools/cli/lib/nexus-process.js +44 -1
  86. package/tools/cli/lib/nexus.js +18 -0
  87. package/tools/cli/lib/packs.js +141 -6
@@ -0,0 +1,352 @@
1
+ /** Mechanical evidence on the supplied text. Semantic review and source checking run separately. */
2
+ const { projectStructured } = require('./ghostwriter-structured');
3
+ const { quantities } = require('./ghostwriter-quantities');
4
+
5
+ const QUALIFIERS = [
6
+ [
7
+ 'negative',
8
+ /(?:n['’]t|\b(?:not|never|no|none|neither|without|pas|jamais|aucun(?:e|s|es)?|sans|ni|não|nunca|nenhum[a]?|sem))\b/giu,
9
+ ],
10
+ [
11
+ 'possible',
12
+ /(?<![\p{L}])(?:may|might|could|can|peut|peuvent|pourrait|pourraient|possiblement|pode|podem|poderia|poderiam)(?![\p{L}])/giu,
13
+ ],
14
+ [
15
+ 'upper limit',
16
+ /(?<![\p{L}])(?:up to|at most|jusqu['’][aà]|au maximum|au plus|até|no máximo)(?![\p{L}])/giu,
17
+ ],
18
+ ['lower limit', /(?<![\p{L}])(?:at least|au moins|pelo menos|no mínimo)(?![\p{L}])/giu],
19
+ [
20
+ 'approximate',
21
+ /(?<![\p{L}])(?:about|around|approximately|environ|à peu près|cerca de|aproximadamente)(?![\p{L}])/giu,
22
+ ],
23
+ ['exception', /(?<![\p{L}])(?:unless|sauf|except|exceto)(?![\p{L}])/giu],
24
+ ['conditional', /(?<![\p{L}])(?:if|provided that|si|à condition que|se|desde que)(?![\p{L}])/giu],
25
+ [
26
+ 'obligation',
27
+ /(?<![\p{L}])(?:must|shall|doit|doivent|obligatoire|deve|devem|obrigatório)(?![\p{L}])/giu,
28
+ ],
29
+ [
30
+ 'guarantee',
31
+ /(?<![\p{L}])(?:guarantee[ds]?|garanti(?:e|t|s|es)?|garantid[oa]s?|sempre|always|toujours)(?![\p{L}])/giu,
32
+ ],
33
+ ];
34
+ const RULES = [
35
+ ['link', /(?:https?:\/\/|mailto:)[^\s<>"'`]+|[\w.+-]{1,64}@[\w.-]{1,253}\.[a-z]{2,63}/giu],
36
+ [
37
+ 'code',
38
+ /(?<![\w-])--[a-z][\w-]*(?:=[\w./:-]+)?|\b[A-Z][A-Z0-9]*_[A-Z0-9_]+\b|\b\w+(?:_\w+)+\b|(?:\.{1,2}\/|~\/|[A-Za-z]:\\|(?<![\p{L}0-9])\/(?=[\w.-]+\/))[^\s`<>"']+|(?<![\p{L}0-9])\$[A-Za-z_][\w]*/gu,
39
+ ],
40
+ ['placeholder', /%(?:\d+\$)?[sdif]|%[A-Z][A-Z_0-9]*%|:[a-z_]+:(?!\w)/g],
41
+ ];
42
+ const AUTHOR =
43
+ /(?<![\p{L}])(?:[Aa]ccording to|[Aa]ttributed to|[Dd]['’]après|[Ss]elon|[Aa]tribu[ií]d[ao] a|[Ss]egundo|[Cc]onforme)\s+([\p{Lu}][\p{L}\p{M}\d'’-]*(?:[ \t]+(?:d[aeo]s? |de la |van |von )?[\p{Lu}][\p{L}\p{M}\d'’-]*)*)/gu;
44
+ const MAX_BYTES = 1024 * 1024;
45
+ const FENCE = /^ {0,3}(`{3,}|~{3,})([^\r\n]*)$/;
46
+ const COMMAND =
47
+ /^\s*(?:\$ |PS [^>]*> |(?:npm|npx|pnpm|node|git|ssh|curl|docker|kubectl|bmad-plus)\s+[-\w./])/;
48
+
49
+ function matches(text, pattern) {
50
+ return Array.from(text.matchAll(pattern), (m) => m[0]);
51
+ }
52
+
53
+ function takeBalanced(text, start, open, close) {
54
+ let depth = 1;
55
+ for (let i = start + 1; i < text.length; i++) {
56
+ if (text[i] === '\\') {
57
+ i++;
58
+ continue;
59
+ }
60
+ if (text[i] === open) depth++;
61
+ if (text[i] === close && --depth === 0) return i + 1;
62
+ }
63
+ throw new Error('Unclosed protected expression.');
64
+ }
65
+
66
+ // Replace bounded protected regions with whitespace before running lexical checks.
67
+ // Store the exact region independently, including delimiters and original line endings.
68
+ function inspectLines(text, markdown, record) {
69
+ const lines = text.match(/[^\r\n]*(?:\r\n|\r|\n)|[^\r\n]+$/g) || [];
70
+ let fence = '';
71
+ let block = '';
72
+ let frontmatter = '';
73
+ const prose = [];
74
+ const hasFragment = markdown && /\]\(\s*#/.test(text);
75
+ for (const [i, line] of lines.entries()) {
76
+ const content = line.replace(/[\r\n]+$/, '');
77
+ if (i === 0 && markdown && /^(?:---|\+\+\+)$/.test(content)) frontmatter = content;
78
+ if (frontmatter) {
79
+ block += line;
80
+ if (i > 0 && (content === frontmatter || (frontmatter === '---' && content === '...'))) {
81
+ record('markup', block);
82
+ block = '';
83
+ frontmatter = '';
84
+ }
85
+ continue;
86
+ }
87
+ const delimiter = content.match(FENCE);
88
+ if (fence) {
89
+ block += line;
90
+ if (
91
+ delimiter &&
92
+ delimiter[1][0] === fence[0] &&
93
+ delimiter[1].length >= fence.length &&
94
+ !delimiter[2].trim()
95
+ ) {
96
+ record('code', block);
97
+ block = '';
98
+ fence = '';
99
+ }
100
+ continue;
101
+ }
102
+ if (delimiter) {
103
+ if (delimiter[1][0] === '`' && delimiter[2].includes('`'))
104
+ throw new Error('Ambiguous code fence.');
105
+ fence = delimiter[1];
106
+ block = line;
107
+ prose.push('\n');
108
+ } else if (
109
+ COMMAND.test(content) ||
110
+ (markdown && /^(?: {4}|\t| {0,3}>| {0,3}\[[^\]]+\]:)/.test(content)) ||
111
+ (hasFragment && /^ {0,3}#{1,6}\s/.test(content))
112
+ ) {
113
+ record('code', line);
114
+ prose.push('\n');
115
+ } else {
116
+ prose.push(line);
117
+ }
118
+ }
119
+ if (block) throw new Error('Unclosed fenced code or front matter.');
120
+ return prose.join('');
121
+ }
122
+
123
+ function inspectInline(text, markdown, record) {
124
+ const prose = [];
125
+ const brackets = [];
126
+ let plain = 0;
127
+ let i = 0;
128
+ const consume = (rule, end) => {
129
+ prose.push(text.slice(plain, i), ' ');
130
+ record(rule, text.slice(i, end));
131
+ i = end;
132
+ plain = end;
133
+ };
134
+ while (i < text.length) {
135
+ const char = text[i];
136
+ if (char === '\\' && markdown && /[\\[\]!`{}()<>]/.test(text[i + 1] || ' ')) {
137
+ consume('markup', i + 2);
138
+ } else if (char === '`') {
139
+ let j = i + 1;
140
+ while (text[j] === '`') j++;
141
+ const ticks = j - i;
142
+ let close = text.indexOf('`', j);
143
+ while (close !== -1) {
144
+ let end = close + 1;
145
+ while (text[end] === '`') end++;
146
+ if (end - close === ticks) {
147
+ consume('code', end);
148
+ break;
149
+ }
150
+ close = text.indexOf('`', end);
151
+ }
152
+ if (close === -1) throw new Error('Unclosed inline code.');
153
+ } else if (char === '{') {
154
+ consume('placeholder', takeBalanced(text, i, '{', '}'));
155
+ } else if (char === '}') {
156
+ throw new Error('Unbalanced placeholder.');
157
+ } else if (markdown && char === '[') {
158
+ if (brackets.length >= 64)
159
+ throw new Error('Markdown label nesting exceeds the supported depth.');
160
+ brackets.push({ start: i, image: i > 0 && text[i - 1] === '!' });
161
+ i++;
162
+ } else if (markdown && char === ']') {
163
+ const opener = brackets.pop();
164
+ if (!opener) throw new Error('Unbalanced Markdown label.');
165
+ record('link', opener.image ? 'image' : 'label');
166
+ if (text[i + 1] === '(') {
167
+ consume('link', takeBalanced(text, i + 1, '(', ')'));
168
+ } else if (text[i + 1] === '[') {
169
+ const end = text.indexOf(']', i + 2);
170
+ if (end < 0) throw new Error('Unclosed Markdown reference.');
171
+ if (end === i + 2) record('link', text.slice(opener.start, i));
172
+ consume('link', end + 1);
173
+ } else {
174
+ record('link', text.slice(opener.start, i + 1));
175
+ i++;
176
+ }
177
+ } else if (char === '<' && /^<[!?/A-Za-z]/.test(text.slice(i, i + 2))) {
178
+ const comment = text.startsWith('<!--', i);
179
+ const end = comment ? text.indexOf('-->', i + 4) : text.indexOf('>', i + 1);
180
+ if (end < 0) throw new Error('Unclosed markup.');
181
+ const markup = text.slice(i, end + 1);
182
+ if (
183
+ !comment &&
184
+ /<(?:script|style|pre|code|textarea)\b|["'][^"']*$/i.test(
185
+ markup.replace(/(["'])(.*?)\1/g, '')
186
+ )
187
+ ) {
188
+ throw new Error('Raw HTML block or ambiguous attribute needs a format-specific review.');
189
+ }
190
+ consume('markup', end + (comment ? 3 : 1));
191
+ } else {
192
+ i++;
193
+ }
194
+ }
195
+ if (brackets.length) throw new Error('Unbalanced Markdown label.');
196
+ prose.push(text.slice(plain));
197
+ return prose.join('');
198
+ }
199
+
200
+ function inventory(value, locale, markdown) {
201
+ const tokens = new Map();
202
+ const record = (rule, token) => {
203
+ if (!tokens.has(rule)) tokens.set(rule, []);
204
+ tokens.get(rule).push(token);
205
+ };
206
+ const lines = inspectLines(value, markdown, record);
207
+ // Localisation catalogues often embed Markdown links inside otherwise plain JSON strings.
208
+ const inlineMarkdown = markdown || lines.includes('](') || lines.includes('][');
209
+ const prose = inspectInline(lines, inlineMarkdown, record);
210
+ for (const [rule, pattern] of RULES) {
211
+ for (const item of matches(prose, pattern)) record(rule, item);
212
+ }
213
+ for (const match of prose.matchAll(
214
+ /«[^«»]*»|“[^“”]*”|‘[^‘’]*’|"[^"]*"|(?<![\p{L}\p{N}])'[^'\r\n]+'(?![\p{L}\p{N}])/gu
215
+ )) {
216
+ record('quotation', match[0].slice(1, -1).trim());
217
+ }
218
+ // Preserve attribution subjects independently of the language used for the reporting phrase.
219
+ for (const match of prose.matchAll(AUTHOR)) record('attribution', match[1]);
220
+ const qualifiers = [];
221
+ // In dated English prose "May" names a month. Portuguese "no" means "in the".
222
+ const qualifierText = prose.replace(/\bMay\b(?=\s+\d)|\b\d{1,2}(?:st|nd|rd|th)?\s+May\b/gi, ' ');
223
+ for (const [kind, pattern] of QUALIFIERS) {
224
+ for (const match of qualifierText.matchAll(pattern)) {
225
+ if (/^pt(?:-|$)/i.test(locale || '') && /^no$/i.test(match[0])) continue;
226
+ qualifiers.push([match.index, kind]);
227
+ }
228
+ }
229
+ for (const [, kind] of qualifiers.sort((a, b) => a[0] - b[0])) record('qualifier', kind);
230
+ const amount = quantities(prose, locale);
231
+ tokens.set('number', amount.numbers);
232
+ tokens.set('date', amount.dates);
233
+ tokens.set('unit', amount.units);
234
+ return tokens;
235
+ }
236
+
237
+ function isStringList(value) {
238
+ return Array.isArray(value) && value.every((item) => typeof item === 'string' && item.length > 0);
239
+ }
240
+
241
+ function same(left, right) {
242
+ return left.length === right.length && left.every((item, index) => item === right[index]);
243
+ }
244
+
245
+ function count(text, literal) {
246
+ return text.split(literal).length - 1;
247
+ }
248
+
249
+ function checkFidelity(source, output, options = {}) {
250
+ const findings = [];
251
+ const add = (rule, path, message) => findings.push({ rule, path, message });
252
+ const result = (status, coverage) => ({
253
+ status,
254
+ coverage,
255
+ findings,
256
+ semantic: 'unreviewed',
257
+ factual: 'unverified',
258
+ });
259
+ if (
260
+ typeof source !== 'string' ||
261
+ typeof output !== 'string' ||
262
+ !options ||
263
+ typeof options !== 'object'
264
+ ) {
265
+ add('invalid', '', 'Two strings and a check policy are required.');
266
+ return result('incomplete', 'partial');
267
+ }
268
+ if (
269
+ !source.trim() ||
270
+ !output.trim() ||
271
+ [source, output].some((text) => Buffer.byteLength(text) > MAX_BYTES)
272
+ ) {
273
+ add('scope', '', 'Expected nonempty texts of up to 1 MiB each.');
274
+ return result('incomplete', 'partial');
275
+ }
276
+
277
+ const { format = 'text', allowedFields = [], protectedTerms = [], protectedSpans = [] } = options;
278
+ if (!['text', 'markdown', 'json', 'yaml'].includes(format)) {
279
+ add('unsupported', '', 'Unsupported input format.');
280
+ return result('incomplete', 'partial');
281
+ }
282
+ if (
283
+ !isStringList(protectedTerms) ||
284
+ !isStringList(protectedSpans) ||
285
+ !Array.isArray(allowedFields)
286
+ ) {
287
+ add('invalid', '', 'Invalid protected ranges or field list.');
288
+ return result('incomplete', 'partial');
289
+ }
290
+
291
+ let path = '';
292
+ try {
293
+ const structured = format === 'json' || format === 'yaml';
294
+ if (structured && !allowedFields.length)
295
+ throw new Error('Select at least one editable string field.');
296
+ if (!structured && allowedFields.length)
297
+ throw new Error('Editable fields require a structured document.');
298
+ const before = structured
299
+ ? projectStructured(source, format, allowedFields)
300
+ : { units: new Map([['', source]]) };
301
+ const after = structured
302
+ ? projectStructured(output, format, allowedFields)
303
+ : { units: new Map([['', output]]) };
304
+ if (before.frame !== after.frame)
305
+ add('structure', '', 'Bytes outside editable strings changed.');
306
+ for (const span of protectedSpans) {
307
+ if (
308
+ !source.includes(span) &&
309
+ ![...before.units.values()].some((text) => text.includes(span))
310
+ ) {
311
+ throw new Error('A declared protected span is absent from the input.');
312
+ }
313
+ }
314
+ for (const [key, original] of before.units) {
315
+ path = key;
316
+ const revised = after.units.get(path);
317
+ if (typeof revised !== 'string' || (original.trim() && !revised.trim()))
318
+ throw new Error('Missing output unit.');
319
+ for (const [rule, literals] of [
320
+ ['protected-term', protectedTerms],
321
+ ['protected-span', protectedSpans],
322
+ ]) {
323
+ for (const literal of literals) {
324
+ if (count(original, literal) !== count(revised, literal))
325
+ add(rule, path, 'The number of exact occurrences changed.');
326
+ }
327
+ }
328
+ const a = inventory(
329
+ original,
330
+ options.sourceLocale || options.language,
331
+ format === 'markdown'
332
+ );
333
+ const b = inventory(revised, options.targetLocale || options.language, format === 'markdown');
334
+ for (const rule of new Set([...a.keys(), ...b.keys()])) {
335
+ if (!same(a.get(rule) || [], b.get(rule) || []))
336
+ add(rule, path, 'Protected content changed in this unit.');
337
+ }
338
+ }
339
+ } catch (error) {
340
+ add(
341
+ 'unsupported',
342
+ path,
343
+ error.name === 'SyntaxError' || error.name === 'YAMLException'
344
+ ? 'Invalid structured document.'
345
+ : error.message
346
+ );
347
+ return result('incomplete', 'partial');
348
+ }
349
+ return result(findings.length ? 'findings' : 'pass', 'complete');
350
+ }
351
+
352
+ module.exports = { checkFidelity };
@@ -0,0 +1,238 @@
1
+ 'use strict';
2
+
3
+ const path = require('node:path');
4
+ const crypto = require('node:crypto');
5
+ const {
6
+ BASE,
7
+ PACK,
8
+ MAX_FILE,
9
+ MAX_CONTEXT,
10
+ projectArtifact,
11
+ digest,
12
+ identifier,
13
+ textFile,
14
+ present,
15
+ writeOnce,
16
+ selection,
17
+ strings,
18
+ locale,
19
+ loadConfig,
20
+ voice,
21
+ } = require('./ghostwriter-project');
22
+
23
+ const WORKFLOWS = [
24
+ 'voice-profile',
25
+ 'draft',
26
+ 'humanize',
27
+ 'improve',
28
+ 'localize',
29
+ 'agent-output-review',
30
+ ];
31
+ const FORMATS = {
32
+ '.md': 'markdown',
33
+ '.markdown': 'markdown',
34
+ '.txt': 'text',
35
+ '.json': 'json',
36
+ '.yaml': 'yaml',
37
+ '.yml': 'yaml',
38
+ };
39
+ const manifestPath = (id) => BASE + '/runs/' + identifier(id) + '/manifest.json';
40
+
41
+ function applies(file, entries) {
42
+ return entries.some((entry) => {
43
+ const prefix = entry.replace(/\/$/, '');
44
+ return file === prefix || file.startsWith(prefix + '/');
45
+ });
46
+ }
47
+
48
+ function build(root, id, request) {
49
+ const config = loadConfig(root);
50
+ const installManifest = '_bmad/.bmad-plus-install.json';
51
+ if (
52
+ present(root, installManifest) &&
53
+ !JSON.parse(textFile(root, installManifest).content).packs?.includes('ghostwriter')
54
+ ) {
55
+ throw new Error('Ghostwriter is not selected in the installed project.');
56
+ }
57
+ const workflow = selection(request.workflow, WORKFLOWS, 'workflow');
58
+ const mode = selection(
59
+ request.mode ?? config.mode,
60
+ ['manual', 'host_policy', 'orchestrated'],
61
+ 'mode'
62
+ );
63
+ if (config.config_path && request.mode && mode !== config.mode) {
64
+ throw new Error('Requested mode differs from configured project policy.');
65
+ }
66
+ if (mode === 'orchestrated' && workflow !== 'agent-output-review') {
67
+ throw new Error(
68
+ 'The orchestrated backend supports agent-output-review on a materialized draft.'
69
+ );
70
+ }
71
+ const selected = projectArtifact(root, request.input);
72
+ if (!selected.content.trim()) throw new Error('Selected draft is empty.');
73
+ if (
74
+ applies(selected.path, config.scope.exclude_paths) ||
75
+ (config.scope.include_paths.length && !applies(selected.path, config.scope.include_paths))
76
+ ) {
77
+ throw new Error('The selected draft is outside the configured editorial scope.');
78
+ }
79
+ const format = FORMATS[path.extname(selected.path).toLowerCase()];
80
+ if (!format) throw new Error('Unsupported prose format: ' + selected.path);
81
+ const fields = strings(request.fields ?? [], 'fields');
82
+ if (fields.some((f) => config.editable_fields.length && !config.editable_fields.includes(f))) {
83
+ throw new Error('Selected fields exceed project policy.');
84
+ }
85
+ const editable = fields.length ? fields : config.editable_fields;
86
+ if (['json', 'yaml'].includes(format) && !editable.length)
87
+ throw new Error('Select editable RFC 6901 string fields for structured prose.');
88
+ if (editable.some((f) => !f.startsWith('/') || /~(?![01])/.test(f)))
89
+ throw new Error('Invalid RFC 6901 field.');
90
+ const contentType = identifier(request.content_type ?? 'documentation');
91
+ if (config.content_types.length && !config.content_types.includes(contentType))
92
+ throw new Error('Content type excluded by policy.');
93
+ const targetLocale = locale(request.locale ?? config.default_locale);
94
+ const sourceLocale = locale(request.source_locale ?? targetLocale);
95
+ const selectedVoice = voice(root, request.profile ?? config.voice_profile);
96
+ const protectedTerms = [...new Set([...config.protected_terms, ...selectedVoice.terms])];
97
+ const policy = {
98
+ config_path: config.config_path,
99
+ config_sha256: config.config_sha256,
100
+ facts: config.facts,
101
+ editable_fields: editable,
102
+ protected_spans: config.protected_spans,
103
+ protected_terms: protectedTerms,
104
+ scope: config.scope,
105
+ default_locale: config.default_locale,
106
+ source_locale: sourceLocale,
107
+ fidelity: 'required',
108
+ semantic_review: 'required',
109
+ reviewer_context: 'separate',
110
+ };
111
+ const artifacts = strings(request.sources ?? [], 'sources').map((file) =>
112
+ projectArtifact(root, file)
113
+ );
114
+ if (artifacts.length > 32) throw new Error('Select at most 32 additional sources.');
115
+ const brief = request.brief ? projectArtifact(root, request.brief) : null;
116
+ const catalogPath = PACK + '/shared/catalog.json';
117
+ const catalog = JSON.parse(textFile(root, catalogPath).content);
118
+ const route = catalog.workflows?.find((r) => r.id === workflow);
119
+ if (
120
+ catalog.schemaVersion !== 1 ||
121
+ !route ||
122
+ route.path !== 'workflows/' + workflow + '.md' ||
123
+ !/^ghostwriter-(voice|write|edit|humanize|localize|verify)$/.test(route.skill)
124
+ ) {
125
+ throw new Error('Invalid installed Ghostwriter route: ' + workflow);
126
+ }
127
+ const locales = { en: 'en', fr: 'fr-FR', 'pt-BR': 'pt-BR' };
128
+ const layer = locales[targetLocale] ?? locales[targetLocale.split('-')[0]];
129
+ if (!layer && mode === 'orchestrated')
130
+ throw new Error('No shipped editorial layer for ' + targetLocale);
131
+ const instructionPaths = [
132
+ 'SKILL.md',
133
+ 'ghostwriter.md',
134
+ 'shared/editorial-contract.md',
135
+ 'shared/execution.md',
136
+ 'languages/glossary.md',
137
+ ...(layer ? ['languages/' + layer + '.md'] : []),
138
+ route.path,
139
+ ].map((p) => PACK + '/' + p);
140
+ instructionPaths.push(catalogPath);
141
+ const skills = new Set([route.skill, 'ghostwriter-verify']);
142
+ if (workflow === 'agent-output-review') skills.add('ghostwriter-edit');
143
+ for (const skill of skills) instructionPaths.push('.agents/skills/' + skill + '/SKILL.md');
144
+ const resources = [...instructionPaths, ...selectedVoice.samples.map((s) => s.path)].map((p) =>
145
+ textFile(root, p)
146
+ );
147
+ if (
148
+ [selected, ...artifacts, ...resources, brief].reduce((n, a) => n + (a?.bytes ?? 0), 0) >
149
+ MAX_CONTEXT
150
+ ) {
151
+ throw new Error(
152
+ 'Selected context exceeds the supported size. Split the draft into separate runs.'
153
+ );
154
+ }
155
+ const reference = ({ path: file, sha256 }) => ({ path: file, sha256 });
156
+ const sources = artifacts.map(reference);
157
+ const unitCount = selected.content
158
+ .split(/(?:\r?\n)[\t ]*(?:\r?\n)+/)
159
+ .filter((p) => p.trim()).length;
160
+ const units = Array.from({ length: unitCount }, (_, i) => 'p' + (i + 1));
161
+ const outputBase = '_bmad-output/ghostwriter/' + id;
162
+ return {
163
+ schema_version: 1,
164
+ run_id: id,
165
+ workflow,
166
+ content_type: contentType,
167
+ locale: targetLocale,
168
+ input_artifacts: [{ ...reference(selected), format, units }],
169
+ source_artifacts: sources,
170
+ source_set_sha256: digest(sources),
171
+ resource_artifacts: resources.map(reference),
172
+ brief: brief ? reference(brief) : null,
173
+ voice_profile: {
174
+ id: selectedVoice.id,
175
+ version: selectedVoice.version,
176
+ path: selectedVoice.path,
177
+ sha256: selectedVoice.sha256,
178
+ },
179
+ policy: { ...policy, sha256: digest(policy) },
180
+ limits: config.limits,
181
+ execution_requirements: {
182
+ mode,
183
+ backend: mode === 'orchestrated' ? 'codex-exec' : null,
184
+ reviewer_context: 'separate',
185
+ },
186
+ editable_scope: { input: selected.path, fields: editable, output_directory: outputBase },
187
+ expected_outputs: { directory: outputBase, format },
188
+ request,
189
+ };
190
+ }
191
+
192
+ function prepare(root, options) {
193
+ const id = 'gw-' + crypto.randomUUID();
194
+ // Persist the request independently of CLI parsing defaults. Re-resolve it on each check.
195
+ const request = JSON.parse(
196
+ JSON.stringify({
197
+ workflow: options.workflow,
198
+ input: options.input,
199
+ brief: options.brief,
200
+ sources: options.source,
201
+ profile: options.profile,
202
+ locale: options.locale,
203
+ source_locale: options.sourceLocale,
204
+ mode: options.mode,
205
+ content_type: options.contentType,
206
+ fields: options.field,
207
+ })
208
+ );
209
+ const manifest = build(root, id, request);
210
+ if (Buffer.byteLength(JSON.stringify(manifest, null, 2) + '\n') > MAX_FILE) {
211
+ throw new Error(
212
+ 'Manifest exceeds the supported size. Split the selected draft into smaller units.'
213
+ );
214
+ }
215
+ writeOnce(root, manifestPath(id), manifest);
216
+ return {
217
+ status: 'prepared',
218
+ executed: false,
219
+ run_id: id,
220
+ manifest_path: manifestPath(id),
221
+ manifest,
222
+ };
223
+ }
224
+
225
+ function load(root, id) {
226
+ const file = textFile(root, manifestPath(id));
227
+ const stored = JSON.parse(file.content);
228
+ if (stored.schema_version !== 1 || stored.run_id !== id)
229
+ throw new Error('Ghostwriter manifest mismatch.');
230
+ const current = build(root, id, stored.request);
231
+ if (digest(stored) !== digest(current))
232
+ throw new Error(
233
+ 'Prepared inputs, profile, resources or policy have changed. Prepare a new run.'
234
+ );
235
+ return current;
236
+ }
237
+
238
+ module.exports = { WORKFLOWS, manifestPath, prepare, load };