@polymorphism-tech/morph-spec 11.5.1 → 12.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -4
- package/bin/morph-spec.js +2 -1
- package/docs/CHEATSHEET.md +3 -3
- package/docs/QUICKSTART.md +1 -1
- package/framework/CLAUDE.md +1 -1
- package/framework/MORPH.md +5 -6
- package/framework/agents.json +4 -4
- package/framework/docs/CLI.md +7 -11
- package/framework/evals/review-checklist.md +28 -42
- package/framework/hooks/README.md +1 -1
- package/framework/hooks/claude-code/core/masked-exit.js +16 -5
- package/framework/hooks/claude-code/core/protect-spec-files.js +4 -27
- package/framework/hooks/shared/command-tokens.js +12 -0
- package/framework/rules/implement-report.md +2 -2
- package/framework/rules/plan-grammar.md +9 -25
- package/framework/schemas/config.schema.json +0 -4
- package/framework/skills/core/create-umbraco-lp/SKILL.md +1 -1
- package/framework/skills/core/migrate-lp-to-umbraco/SKILL.md +1 -1
- package/framework/skills/core/morph-apply/SKILL.md +19 -11
- package/framework/skills/core/morph-plan/SKILL.md +13 -13
- package/framework/skills/core/morph-uiux/SKILL.md +1 -1
- package/framework/standards/STANDARDS.json +1 -1
- package/framework/standards/architecture/engineering-lens.md +1 -1
- package/framework/standards/architecture/stack-baseline.md +2 -2
- package/framework/standards/integration/mcp/mcp-tools.md +1 -1
- package/framework/templates/REGISTRY.json +1 -1
- package/framework/templates/docs/plan.md +7 -75
- package/package.json +1 -1
- package/src/commands/project/init-contract.js +1 -1
- package/src/commands/validation/check.js +10 -8
- package/src/commands/validation/plan-check.js +6 -13
- package/src/lib/check/signals.js +16 -27
- package/src/lib/contract/defaults.js +1 -1
- package/src/lib/installers/memory-installer.js +0 -1
- package/src/lib/plan/checks.js +11 -93
- package/src/lib/plan/plan-parser.js +28 -137
- package/src/lib/review-reports.js +4 -1
- package/src/lib/specs/gfm-table.js +0 -6
- package/src/utils/agents-installer.js +2 -2
- package/framework/hooks/shared/errata.js +0 -59
- package/src/lib/specs/adr-index.js +0 -122
- package/src/lib/specs/frontmatter.js +0 -31
- package/src/lib/specs/revocations.js +0 -85
package/src/lib/check/signals.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { readFileSync } from 'fs';
|
|
2
2
|
import { join } from 'path';
|
|
3
3
|
import { minimatch } from 'minimatch';
|
|
4
|
-
import { diffLines, git } from '../diff/diff-lines.js';
|
|
4
|
+
import { diffLines, fileClass, git } from '../diff/diff-lines.js';
|
|
5
5
|
import { detectDefaultBranch } from '../git/default-branch.js';
|
|
6
6
|
import { parseReport } from '../../../framework/hooks/shared/report-progress.js';
|
|
7
7
|
import { checksCoverage } from '../review-reports.js';
|
|
@@ -62,36 +62,28 @@ function withContent(cwd, file) {
|
|
|
62
62
|
}
|
|
63
63
|
}
|
|
64
64
|
|
|
65
|
-
|
|
65
|
+
/** What the diff touches by category: it decides whether the security review is required, never the verdict alone. */
|
|
66
|
+
export function riskSignals(changed, risk = {}) {
|
|
67
|
+
const files = changed.filter((f) => !['doc', 'test'].includes(fileClass(f.path)));
|
|
66
68
|
const out = [];
|
|
67
69
|
for (const cat of RISK_CATEGORIES) {
|
|
68
70
|
const globs = Array.isArray(risk[cat]) ? risk[cat] : [];
|
|
69
71
|
const byPath = files.find((f) => globs.some((g) => minimatch(f.path, g, { dot: true })));
|
|
70
72
|
if (byPath) { out.push({ kind: 'risco', categoria: cat, onde: byPath.path, por: 'caminho' }); continue; }
|
|
71
73
|
const re = LINE_CATEGORY.find(([c]) => c === cat)?.[1];
|
|
72
|
-
const byLine = re && files.find((f) => f.added.some((l) => re.test(l)));
|
|
74
|
+
const byLine = re && files.find((f) => fileClass(f.path) === 'code' && f.added.some((l) => re.test(l)));
|
|
73
75
|
if (byLine) out.push({ kind: 'risco', categoria: cat, onde: byLine.path, por: 'linha' });
|
|
74
76
|
}
|
|
75
77
|
return out;
|
|
76
78
|
}
|
|
77
79
|
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
: [];
|
|
80
|
+
/** A scenario a revert cannot undo needs the security review even when no path or line flags it. */
|
|
81
|
+
export function planRisks(checks) {
|
|
82
|
+
return (checks?.checks ?? []).filter((c) => STOP_RUNGS.has(c.rung)).map((c) => ({ kind: 'risco', categoria: 'degrau', onde: c.id, por: 'plano' }));
|
|
82
83
|
}
|
|
83
84
|
|
|
84
|
-
export function planSignals(checks
|
|
85
|
-
|
|
86
|
-
const out = [];
|
|
87
|
-
if (checks.summary?.source === 'proposta') out.push({ kind: 'cenarios-propostos', onde: 'plan.md' });
|
|
88
|
-
for (const c of checks.checks ?? []) {
|
|
89
|
-
if (STOP_RUNGS.has(c.rung)) out.push({ kind: 'degrau', onde: c.id, degrau: c.rung });
|
|
90
|
-
}
|
|
91
|
-
if (limits.maxScenarios && (checks.checks?.length ?? 0) > limits.maxScenarios) {
|
|
92
|
-
out.push({ kind: 'plano-grande', onde: `${checks.checks.length} cenários`, limite: limits.maxScenarios });
|
|
93
|
-
}
|
|
94
|
-
return out;
|
|
85
|
+
export function planSignals(checks) {
|
|
86
|
+
return (checks?.checks ?? []).filter((c) => STOP_RUNGS.has(c.rung)).map((c) => ({ kind: 'degrau', onde: c.id, degrau: c.rung }));
|
|
95
87
|
}
|
|
96
88
|
|
|
97
89
|
export function reportSignals(reportText) {
|
|
@@ -120,14 +112,15 @@ function staleReason(cwd, sha) {
|
|
|
120
112
|
}
|
|
121
113
|
|
|
122
114
|
/**
|
|
123
|
-
* Personas of the single review round: verifier and reviewer always, security when it wrote a report.
|
|
115
|
+
* Personas of the single review round: verifier and reviewer always, security when the diff has a risk or it wrote a report.
|
|
124
116
|
* With `cwd`, a report whose `Reviewed-SHA` is missing or older than the code counts as no review.
|
|
125
117
|
*/
|
|
126
|
-
export function reviewSignals(reports, checkIds = [], cwd = null) {
|
|
127
|
-
const required = ['verifier', 'reviewer', ...(reports.security.status
|
|
118
|
+
export function reviewSignals(reports, checkIds = [], cwd = null, risks = []) {
|
|
119
|
+
const required = ['verifier', 'reviewer', ...(risks.length || reports.security.status !== 'missing' ? ['security'] : [])];
|
|
128
120
|
const out = [];
|
|
129
121
|
const absent = required.filter((role) => reports[role].status !== 'ok');
|
|
130
|
-
|
|
122
|
+
const why = (role) => (role === 'security' && risks.length ? `; mexe em ${risks.map((r) => `${r.categoria} (${r.onde})`).join(', ')}` : '');
|
|
123
|
+
if (absent.length) out.push({ kind: 'sem-revisao', onde: absent.map((r) => `${r} (${reports[r].status}${why(r)})`).join(', ') });
|
|
131
124
|
const open = (role) => [...reports[role].blockers, ...reports[role].untyped];
|
|
132
125
|
const fix = required.filter((role) => reports[role].status === 'ok' && (reports[role].verdict === 'FIX' || open(role).length));
|
|
133
126
|
if (fix.length) {
|
|
@@ -144,18 +137,14 @@ export function reviewSignals(reports, checkIds = [], cwd = null) {
|
|
|
144
137
|
}
|
|
145
138
|
|
|
146
139
|
const SAY = {
|
|
147
|
-
risco: (s) => `mexe em ${s.categoria} (${s.onde}, pelo ${s.por})`,
|
|
148
|
-
'pr-grande': (s) => `PR grande: ${s.onde}, limite ${s.limite}`,
|
|
149
|
-
'cenarios-propostos': () => 'os cenários foram propostos pelo agente (a issue veio incompleta): aprovar antes de implementar',
|
|
150
140
|
degrau: (s) => `${s.onde} tem degrau "${s.degrau}"`,
|
|
151
|
-
'plano-grande': (s) => `plano grande: ${s.onde}, limite ${s.limite}`,
|
|
152
141
|
preso: (s) => s.motivo,
|
|
153
142
|
vermelho: (s) => `testes vermelhos: ${s.onde}`,
|
|
154
143
|
bloqueado: (s) => `${s.onde} bloqueado: espera uma decisão (ver ## Notas)`,
|
|
155
144
|
pendente: (s) => `cenário não fechado no report.md: ${s.onde}`,
|
|
156
145
|
'sem-prova': (s) => s.onde,
|
|
157
146
|
'sem-revisao': (s) => `revisão em contexto novo sem relatório completo: ${s.onde}`,
|
|
158
|
-
'revisao-fix': (s) => `a revisão
|
|
147
|
+
'revisao-fix': (s) => `a revisão deixou bloqueador aberto: ${s.onde}`,
|
|
159
148
|
'nao-provado': (s) => `o verificador não provou: ${s.onde}`,
|
|
160
149
|
'nao-commitado': (s) => `fora do commit, o PR não leva: ${s.onde}`,
|
|
161
150
|
};
|
|
@@ -3,7 +3,7 @@ import { join } from 'path';
|
|
|
3
3
|
|
|
4
4
|
const CONTRACT_VERSION = 1;
|
|
5
5
|
|
|
6
|
-
export const DEFAULT_LIMITS = Object.freeze({ maxScenarios: 6,
|
|
6
|
+
export const DEFAULT_LIMITS = Object.freeze({ maxScenarios: 6, maxIterations: 8, sameErrorStop: 3 });
|
|
7
7
|
|
|
8
8
|
// Globs over repo-relative paths; `LINE_CATEGORY` in check/signals.js catches what a path cannot name.
|
|
9
9
|
export const DEFAULT_RISK = Object.freeze({
|
|
@@ -53,7 +53,6 @@ metadata:
|
|
|
53
53
|
# morph-spec context locations
|
|
54
54
|
|
|
55
55
|
- \`.morph/context/design-system.md\` — design tokens and components, when the project has a UI
|
|
56
|
-
- \`.morph/specs/adrs/\` — project-scope decisions, written by plan-check
|
|
57
56
|
- \`.morph/framework/CLI.md\` — the CLI reference, one section per command
|
|
58
57
|
- \`.morph/framework/evals/review-checklist.md\` — what the review personas check (SHIP/FIX + evidence-typed blockers)
|
|
59
58
|
`;
|
package/src/lib/plan/checks.js
CHANGED
|
@@ -1,60 +1,18 @@
|
|
|
1
|
-
import { createHash } from 'crypto';
|
|
2
|
-
import { frozenBody } from '../../../framework/hooks/shared/errata.js';
|
|
3
1
|
import { findArtifactTerms } from './artifact-vocabulary.js';
|
|
4
2
|
import { mediaCitationError } from './media.js';
|
|
5
3
|
import { scenarioLabel, WORK_NAME } from '../../../framework/hooks/shared/owner-words.js';
|
|
6
4
|
import { foldAccents } from '../text.js';
|
|
7
|
-
import { PROOF_KINDS, RISK_KINDS, REWORK_RUNGS,
|
|
5
|
+
import { PROOF_KINDS, RISK_KINDS, REWORK_RUNGS, SECTIONS } from './plan-parser.js';
|
|
8
6
|
|
|
9
7
|
import { issueNumberOf } from '../github/issue-sync.js';
|
|
10
8
|
|
|
11
|
-
const CHECKS_VERSION =
|
|
12
|
-
|
|
13
|
-
/** sha256 of the plan without its errata: appending a correction never invalidates the extracted checks. */
|
|
14
|
-
export function planHash(text) {
|
|
15
|
-
return createHash('sha256').update(frozenBody(text), 'utf8').digest('hex');
|
|
16
|
-
}
|
|
9
|
+
const CHECKS_VERSION = 2;
|
|
17
10
|
|
|
18
11
|
const foldRisk = (s) => foldAccents(s.replace(/`/g, '')).trim();
|
|
19
12
|
const RISK_BY_FOLD = new Map(RISK_KINDS.map((r) => [foldRisk(r), r]));
|
|
20
13
|
const RUNG_BY_FOLD = new Map(REWORK_RUNGS.map((r) => [foldRisk(r), r]));
|
|
21
14
|
const canonicalRung = (rung) => (rung === null ? null : RUNG_BY_FOLD.get(foldRisk(rung)) ?? false);
|
|
22
15
|
const REGRESSION_WORK_TYPES = ['bug', 'hotfix'];
|
|
23
|
-
const POLICY_PLAN_WORK_TYPES = ['chore', 'hotfix'];
|
|
24
|
-
// Vetar por número só vale para o que custa pouco errar: o resto é pergunta. Aviso, não erro: o vocabulário
|
|
25
|
-
// é comum em plano por outros motivos, e um erro só ensinaria a reescrever a linha.
|
|
26
|
-
const NEVER_DEFAULT_RE = /\b(autentica\w*|senha|password|credencia\w*|segredo|secret|api key|chave de api|permiss\w*|pagamento|cobranc\w*|billing|drop (table|column)|(apaga\w*|delet\w*|exclu\w*) (o |os |a |as )?(dado|registro|lead|conta|cliente)s?)\b/;
|
|
27
|
-
|
|
28
|
-
function defaultsWarnings(plan, at) {
|
|
29
|
-
return plan.defaults.items.flatMap((d) => {
|
|
30
|
-
const hit = NEVER_DEFAULT_RE.exec(foldRisk(d.text));
|
|
31
|
-
return hit ? [`padrão ${d.n} toca "${hit[1]}"${at(d.line)} — credencial, permissão, pagamento e apagar dado viram pergunta, nunca padrão`] : [];
|
|
32
|
-
});
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
// Optional: absent is fine; present, every line is a transition the plan view can draw.
|
|
36
|
-
function transitionErrors(plan, key, at) {
|
|
37
|
-
if (!plan.present[key]) return [];
|
|
38
|
-
const { transitions, invalid } = plan[key === 'flow' ? 'flow' : 'states'];
|
|
39
|
-
const errors = invalid.map((l) => `## ${SECTIONS[key]}: "${l.raw}" não é transição — use "- origem → destino: gatilho"${at(l.line)}`);
|
|
40
|
-
if (transitions.length === 0 && invalid.length === 0) errors.push(`## ${SECTIONS[key]} vazia — liste as transições ou apague a seção`);
|
|
41
|
-
return errors;
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
function defaultsErrors(plan, workType, at) {
|
|
45
|
-
const { items, none } = plan.defaults;
|
|
46
|
-
if (!plan.present.defaults) {
|
|
47
|
-
return !POLICY_PLAN_WORK_TYPES.includes(workType)
|
|
48
|
-
? [`seção obrigatória ausente: ## ${SECTIONS.defaults} — numere o que você decidiu sem perguntar, ou escreva "nenhum"`]
|
|
49
|
-
: [];
|
|
50
|
-
}
|
|
51
|
-
if (items.length === 0) {
|
|
52
|
-
return none ? [] : [`## ${SECTIONS.defaults} sem item numerado ("1. …") nem "nenhum"`];
|
|
53
|
-
}
|
|
54
|
-
return items.some((d, i) => d.n !== i + 1)
|
|
55
|
-
? [`## ${SECTIONS.defaults} numerada fora de 1..${items.length} — o usuário veta pelo número`]
|
|
56
|
-
: [];
|
|
57
|
-
}
|
|
58
16
|
|
|
59
17
|
export function validatePlan(plan, { text = null } = {}) {
|
|
60
18
|
const errors = [];
|
|
@@ -67,21 +25,12 @@ export function validatePlan(plan, { text = null } = {}) {
|
|
|
67
25
|
if (media) errors.push(media);
|
|
68
26
|
const at = (line) => (line ? ` (linha ${line})` : '');
|
|
69
27
|
|
|
70
|
-
|
|
71
|
-
if (!plan.present[key]) errors.push(`seção obrigatória ausente: ## ${SECTIONS[key]}`);
|
|
72
|
-
}
|
|
73
|
-
if (plan.present.decisions && !plan.conflicts) {
|
|
74
|
-
errors.push(`### ${CONFLICTS_HEADING} ausente em ## ${SECTIONS.decisions} — escreva "nenhum" quando não houver`);
|
|
75
|
-
} else if (plan.conflicts && !plan.conflicts.text) {
|
|
76
|
-
errors.push(`### ${CONFLICTS_HEADING} está vazio${at(plan.conflicts.line)} — escreva "nenhum" quando não houver`);
|
|
77
|
-
}
|
|
78
|
-
if (plan.sectionsAfterErrata.length > 0) {
|
|
79
|
-
errors.push(`## ${SECTIONS.errata} precisa ser a última seção — depois dela: ${plan.sectionsAfterErrata.join(', ')}`);
|
|
80
|
-
}
|
|
28
|
+
if (!plan.present.scenarios) errors.push(`seção obrigatória ausente: ## ${SECTIONS.scenarios}`);
|
|
81
29
|
|
|
82
|
-
const
|
|
83
|
-
for (const id of new Set(
|
|
84
|
-
|
|
30
|
+
const ids = plan.scenarios.map((c) => c.id);
|
|
31
|
+
for (const id of new Set(ids.filter((id, i) => ids.indexOf(id) !== i))) {
|
|
32
|
+
errors.push(`Cenário ${id.replace(/^C/i, '')} aparece mais de uma vez no plano (${id}): cada cenário precisa de um número só dele`);
|
|
33
|
+
}
|
|
85
34
|
|
|
86
35
|
if (plan.present.scenarios && plan.scenarios.length === 0) {
|
|
87
36
|
errors.push(`## ${SECTIONS.scenarios} sem nenhum cenário no formato "- **C1** — Dado …, quando …, então …"`);
|
|
@@ -116,53 +65,22 @@ export function validatePlan(plan, { text = null } = {}) {
|
|
|
116
65
|
errors.push(`${WORK_NAME[workType]} sem cenário que prove que o bug não volta (${workType}): escreva um cenário com o sintoma real, "prova: teste" e "risco: regressão"`);
|
|
117
66
|
}
|
|
118
67
|
|
|
119
|
-
errors.push(...defaultsErrors(plan, workType, at));
|
|
120
|
-
errors.push(...transitionErrors(plan, 'states', at), ...transitionErrors(plan, 'flow', at));
|
|
121
|
-
warnings.push(...defaultsWarnings(plan, at));
|
|
122
|
-
if (!(plan.summary.today && plan.summary.after)) {
|
|
123
|
-
warnings.push(`## ${SECTIONS.summary} sem "- Hoje:" e "- Depois:" — o PR e a revisão abrem com o texto técnico do plano; escreva as duas linhas para quem não lê código`);
|
|
124
|
-
}
|
|
125
|
-
const bare = plan.adrs.filter((a) => !(a.plain.decided && a.plain.why && a.plain.cost)).map((a) => a.id);
|
|
126
|
-
if (bare.length) {
|
|
127
|
-
warnings.push(`${bare.join(', ')} sem "**Decidimos:**", "**Por quê:**" e "**O que custa:**" — uma frase cada, sem código: é o que o revisor e o PR mostram da decisão`);
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
const known = new Set(Object.values(SECTIONS).map(foldRisk));
|
|
131
68
|
for (const s of plan.sections.filter((section) => !section.key)) {
|
|
132
|
-
warnings.push(
|
|
133
|
-
? `## ${s.name} repetida${at(s.line)} — só a primeira é lida, o conteúdo desta se perde`
|
|
134
|
-
: `## ${s.name} não é seção do plano${at(s.line)}: a conferência do plano não a lê`);
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
for (const r of plan.reuse) {
|
|
138
|
-
if (!REUSE_VERDICTS.includes(r.verdict)) {
|
|
139
|
-
errors.push(`## ${SECTIONS.reuse}: veredito "${r.verdict}" de "${r.concept}" fora de ${REUSE_VERDICTS.join(' | ')}${at(r.line)}`);
|
|
140
|
-
} else if (r.verdict === 'CRIAR' && !r.why) {
|
|
141
|
-
warnings.push(`## ${SECTIONS.reuse}: CRIAR "${r.concept}" sem dizer por que não dá para reusar (why)${at(r.line)}`);
|
|
142
|
-
}
|
|
143
|
-
}
|
|
144
|
-
for (const a of plan.adrs) {
|
|
145
|
-
if (!ADR_SCOPES.includes(a.scope)) warnings.push(`${a.id} sem **Alcance:** ${ADR_SCOPES.join(' | ')}${at(a.line)}`);
|
|
69
|
+
warnings.push(`## ${s.name} não é seção do plano${at(s.line)}: ninguém a lê — apague`);
|
|
146
70
|
}
|
|
147
71
|
|
|
148
72
|
return { errors, warnings };
|
|
149
73
|
}
|
|
150
74
|
|
|
151
|
-
export function buildChecks(feature,
|
|
75
|
+
export function buildChecks(feature, plan) {
|
|
152
76
|
return {
|
|
153
77
|
version: CHECKS_VERSION,
|
|
154
78
|
feature,
|
|
155
|
-
|
|
156
|
-
|
|
79
|
+
summary: { name: plan.summary?.name ?? null, issue: issueNumberOf(plan.summary?.source) },
|
|
80
|
+
decisions: plan.decisions ?? [],
|
|
157
81
|
checks: plan.scenarios.map((c) => ({
|
|
158
82
|
id: c.id, title: c.title || null, text: c.text, proof: c.proof ? c.proof.toLowerCase() : null, artifactWhy: c.artifactWhy || null,
|
|
159
83
|
rung: canonicalRung(c.rung) || null,
|
|
160
84
|
})),
|
|
161
|
-
reuse: plan.reuse.map(({ concept, verdict, target, why }) => ({ concept, verdict, target, why })),
|
|
162
|
-
adrs: plan.adrs.map((a) => ({ id: a.id, title: a.title, scope: ADR_SCOPES.includes(a.scope) ? a.scope : null })),
|
|
163
85
|
};
|
|
164
86
|
}
|
|
165
|
-
|
|
166
|
-
// The scenarios came from the issue, or the agent proposed them because the issue had none: then someone approves first.
|
|
167
|
-
const sourceOf = (text) => (/^propost/i.test(String(text ?? '').trim()) ? 'proposta' : text ? 'issue' : null);
|
|
168
|
-
const summaryOf = (plan) => ({ name: plan.summary?.name ?? null, after: plan.summary?.after ?? null, watch: plan.summary?.watch ?? [], source: sourceOf(plan.summary?.source), issue: issueNumberOf(plan.summary?.source) });
|
|
@@ -1,52 +1,47 @@
|
|
|
1
|
-
import { tableCells, isTableLine, SEPARATOR_ROW_RE } from '../specs/gfm-table.js';
|
|
2
1
|
import { foldAccents } from '../text.js';
|
|
3
2
|
import { ARTIFACT_MARKER_RE } from './artifact-vocabulary.js';
|
|
4
|
-
import { markdownLines } from '../../../framework/hooks/shared/errata.js';
|
|
5
3
|
|
|
6
4
|
export const PROOF_KINDS = ['teste', 'e2e', 'eval', 'manual', 'leitura'];
|
|
7
5
|
export const RISK_KINDS = ['regra', 'dinheiro', 'contrato', 'concorrência', 'dado', 'regressão'];
|
|
8
6
|
export const REWORK_RUNGS = ['refazer', 'desfazer', 'migrar', 'irreversível'];
|
|
9
|
-
export const REUSE_VERDICTS = ['REUSAR', 'ESTENDER', 'CRIAR'];
|
|
10
|
-
export const ADR_SCOPES = ['feature', 'projeto'];
|
|
11
7
|
|
|
12
8
|
export const SECTIONS = {
|
|
13
9
|
summary: 'Resumo',
|
|
14
|
-
problem: 'Problema',
|
|
15
|
-
outOfScope: 'Fora de escopo',
|
|
16
|
-
assumptions: 'Suposições não confirmadas',
|
|
17
|
-
defaults: 'Padrões assumidos',
|
|
18
|
-
states: 'Estados',
|
|
19
|
-
flow: 'Fluxo',
|
|
20
10
|
scenarios: 'Cenários',
|
|
11
|
+
outOfScope: 'Fora de escopo',
|
|
21
12
|
decisions: 'Decisões',
|
|
22
|
-
architecture: 'Arquitetura',
|
|
23
|
-
reuse: 'Reuso',
|
|
24
|
-
contract: 'Contrato de implementação',
|
|
25
|
-
errata: 'Errata',
|
|
26
13
|
};
|
|
27
14
|
|
|
28
|
-
export const CONFLICTS_HEADING = 'Conflitos com o acervo';
|
|
29
|
-
|
|
30
15
|
const DASH = String.raw`\s+[—–-]\s+`;
|
|
31
16
|
const SCENARIO_RE = new RegExp(String.raw`^[-*]\s+\*\*(C\d+)\*\*${DASH}(.+)$`);
|
|
32
|
-
const ADR_RE = new RegExp(String.raw`^###\s+(ADR-\d+)${DASH}(.+?)\s*$`);
|
|
33
17
|
const PROOF_RE = /^\s*prova\s*:\s*(.*?)\s*$/i;
|
|
34
18
|
const RISK_RE = /^\s*risco\s*:\s*(.*?)\s*$/i;
|
|
35
19
|
const RUNG_RE = /^\s*degrau\s*:\s*(.*?)\s*$/i;
|
|
36
20
|
const TITLE_RE = /^\s*t[ií]tulo\s*:\s*(.*?)\s*$/i;
|
|
37
|
-
const SUMMARY_RE = /^\s*[-*]\s+\**\s*(nome|tipo|
|
|
38
|
-
const SUMMARY_KEYS = { nome: 'name', tipo: 'kind',
|
|
39
|
-
|
|
40
|
-
const ADR_PLAIN = {
|
|
41
|
-
decided: /^\s*\*\*Decidimos:\*\*\s*(.+?)\s*$/im,
|
|
42
|
-
why: /^\s*\*\*Por qu[eê]:\*\*\s*(.+?)\s*$/im,
|
|
43
|
-
cost: /^\s*\*\*O que custa:\*\*\s*(.+?)\s*$/im,
|
|
44
|
-
};
|
|
45
|
-
const WHY_RE =new RegExp(String.raw`^\s*>\s*` + ARTIFACT_MARKER_RE.source + String.raw`\s*(.*?)\s*$`, 'i');
|
|
46
|
-
const SCOPE_RE = /^\s*\*\*Alcance:\*\*\s*(.*?)\s*$/i;
|
|
21
|
+
const SUMMARY_RE = /^\s*[-*]\s+\**\s*(nome|tipo|origem)\s*\**\s*:\s*\**\s*(.+?)\s*$/i;
|
|
22
|
+
const SUMMARY_KEYS = { nome: 'name', tipo: 'kind', origem: 'source' };
|
|
23
|
+
const WHY_RE = new RegExp(String.raw`^\s*>\s*` + ARTIFACT_MARKER_RE.source + String.raw`\s*(.*?)\s*$`, 'i');
|
|
47
24
|
|
|
48
25
|
const fold = (s) => foldAccents(s).trim();
|
|
49
26
|
|
|
27
|
+
/** BOM and CRLF read as LF; each line knows whether it sits inside a code fence. */
|
|
28
|
+
export function markdownLines(text) {
|
|
29
|
+
const out = [];
|
|
30
|
+
let fence = null;
|
|
31
|
+
String(text ?? '').replace(/^/, '').replace(/\r\n?/g, '\n').split('\n').forEach((raw, i) => {
|
|
32
|
+
const opener = /^\s*(`{3,}|~{3,})/.exec(raw);
|
|
33
|
+
let fenced = Boolean(fence);
|
|
34
|
+
if (fence) {
|
|
35
|
+
if (opener && opener[1][0] === fence[0] && opener[1].length >= fence.length) fence = null;
|
|
36
|
+
} else if (opener) {
|
|
37
|
+
fence = opener[1];
|
|
38
|
+
fenced = true;
|
|
39
|
+
}
|
|
40
|
+
out.push({ raw, n: i + 1, fenced });
|
|
41
|
+
});
|
|
42
|
+
return out;
|
|
43
|
+
}
|
|
44
|
+
|
|
50
45
|
function splitSections(lines) {
|
|
51
46
|
const sections = [];
|
|
52
47
|
let current = null;
|
|
@@ -91,142 +86,38 @@ function parseScenarios(lines) {
|
|
|
91
86
|
return scenarios;
|
|
92
87
|
}
|
|
93
88
|
|
|
94
|
-
function parseDecisions(lines) {
|
|
95
|
-
const adrs = [];
|
|
96
|
-
let conflicts = null;
|
|
97
|
-
let current = null;
|
|
98
|
-
for (const line of lines) {
|
|
99
|
-
if (line.fenced) {
|
|
100
|
-
if (current?.kind === 'conflicts') conflicts.body.push(line.raw);
|
|
101
|
-
else if (current?.kind === 'adr') current.entry.body.push(line.raw);
|
|
102
|
-
continue;
|
|
103
|
-
}
|
|
104
|
-
const adr = ADR_RE.exec(line.raw);
|
|
105
|
-
if (adr) {
|
|
106
|
-
current = { kind: 'adr', entry: { id: adr[1], title: adr[2], scope: null, body: [], line: line.n } };
|
|
107
|
-
adrs.push(current.entry);
|
|
108
|
-
continue;
|
|
109
|
-
}
|
|
110
|
-
const h3 = /^###\s+(.+?)\s*$/.exec(line.raw);
|
|
111
|
-
if (h3) {
|
|
112
|
-
if (fold(h3[1]) === fold(CONFLICTS_HEADING)) {
|
|
113
|
-
conflicts = { line: line.n, body: [] };
|
|
114
|
-
current = { kind: 'conflicts' };
|
|
115
|
-
} else {
|
|
116
|
-
current = null;
|
|
117
|
-
}
|
|
118
|
-
continue;
|
|
119
|
-
}
|
|
120
|
-
if (current?.kind === 'adr') {
|
|
121
|
-
current.entry.body.push(line.raw);
|
|
122
|
-
const scope = current.entry.scope === null && SCOPE_RE.exec(line.raw);
|
|
123
|
-
if (scope) current.entry.scope = scope[1].replace(/`/g, '').trim().toLowerCase();
|
|
124
|
-
} else if (current?.kind === 'conflicts') {
|
|
125
|
-
conflicts.body.push(line.raw);
|
|
126
|
-
}
|
|
127
|
-
}
|
|
128
|
-
for (const a of adrs) {
|
|
129
|
-
a.body = a.body.join('\n').trim();
|
|
130
|
-
a.plain = Object.fromEntries(Object.entries(ADR_PLAIN).map(([key, re]) => [key, re.exec(a.body)?.[1] ?? null]));
|
|
131
|
-
}
|
|
132
|
-
return {
|
|
133
|
-
adrs,
|
|
134
|
-
conflicts: conflicts && { line: conflicts.line, text: conflicts.body.join('\n').trim() },
|
|
135
|
-
};
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
function parseReuse(lines) {
|
|
139
|
-
const rows = [];
|
|
140
|
-
let header = null;
|
|
141
|
-
for (const line of lines) {
|
|
142
|
-
if (line.fenced || !isTableLine(line.raw) || SEPARATOR_ROW_RE.test(line.raw)) continue;
|
|
143
|
-
const cells = tableCells(line.raw);
|
|
144
|
-
if (!header) { header = cells.map(fold); continue; }
|
|
145
|
-
const at = (name) => cells[header.indexOf(name)] ?? '';
|
|
146
|
-
rows.push({
|
|
147
|
-
concept: at('conceito'),
|
|
148
|
-
verdict: at('veredito').replace(/`|\*/g, '').trim().toUpperCase(),
|
|
149
|
-
target: at('alvo'),
|
|
150
|
-
why: at('why'),
|
|
151
|
-
line: line.n,
|
|
152
|
-
});
|
|
153
|
-
}
|
|
154
|
-
return rows;
|
|
155
|
-
}
|
|
156
|
-
|
|
157
89
|
function parseSummary(lines) {
|
|
158
|
-
const found = { name: null, kind: null,
|
|
90
|
+
const found = { name: null, kind: null, source: null };
|
|
159
91
|
let open = null;
|
|
160
92
|
for (const line of lines) {
|
|
161
93
|
const m = !line.fenced && SUMMARY_RE.exec(line.raw);
|
|
162
94
|
if (m) {
|
|
163
|
-
open = { text: m[2] };
|
|
164
95
|
const key = SUMMARY_KEYS[m[1].toLowerCase()];
|
|
165
|
-
|
|
166
|
-
|
|
96
|
+
open = found[key] === null ? { text: m[2] } : null;
|
|
97
|
+
if (open) found[key] = open;
|
|
167
98
|
continue;
|
|
168
99
|
}
|
|
169
100
|
if (open && /^\s+\S/.test(line.raw)) { open.text += ` ${line.raw.trim()}`; continue; }
|
|
170
101
|
open = null;
|
|
171
102
|
}
|
|
172
|
-
return { name: found.name?.text ?? null, kind: found.kind?.text.trim().toLowerCase() ?? null,
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
function parseDefaults(lines) {
|
|
176
|
-
const items = [];
|
|
177
|
-
let none = false;
|
|
178
|
-
let comment = false;
|
|
179
|
-
for (const line of lines) {
|
|
180
|
-
if (line.fenced) continue;
|
|
181
|
-
if (comment || line.raw.includes('<!--')) { comment = !line.raw.includes('-->'); continue; }
|
|
182
|
-
const m = /^\s*(\d+)[.)]\s+(.+?)\s*$/.exec(line.raw);
|
|
183
|
-
if (m) items.push({ n: Number(m[1]), text: m[2], line: line.n });
|
|
184
|
-
else if (items.length && /^\s+\S/.test(line.raw)) items[items.length - 1].text += ` ${line.raw.trim()}`;
|
|
185
|
-
else if (/^\s*nenhum\.?\s*$/i.test(line.raw)) none = true;
|
|
186
|
-
}
|
|
187
|
-
return { items, none };
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
const TRANSITION_RE = /^\s*[-*]\s+(.+?)\s*(?:→|->)\s*(.+?)\s*:\s*(.+?)\s*$/;
|
|
191
|
-
|
|
192
|
-
function parseStates(lines) {
|
|
193
|
-
const transitions = [];
|
|
194
|
-
const invalid = [];
|
|
195
|
-
let comment = false;
|
|
196
|
-
for (const line of lines) {
|
|
197
|
-
if (line.fenced || !line.raw.trim()) continue;
|
|
198
|
-
if (comment || line.raw.includes('<!--')) { comment = !line.raw.includes('-->'); continue; }
|
|
199
|
-
const m = TRANSITION_RE.exec(line.raw);
|
|
200
|
-
if (m) transitions.push({ from: m[1], to: m[2], trigger: m[3], line: line.n });
|
|
201
|
-
else invalid.push({ line: line.n, raw: line.raw.trim() });
|
|
202
|
-
}
|
|
203
|
-
return { transitions, invalid };
|
|
103
|
+
return { name: found.name?.text ?? null, kind: found.kind?.text.trim().toLowerCase() ?? null, source: found.source?.text ?? null };
|
|
204
104
|
}
|
|
205
105
|
|
|
206
106
|
/** Pure: no validation, no I/O; `checks.js` judges what this returns. */
|
|
207
107
|
export function parsePlan(text) {
|
|
208
|
-
const
|
|
209
|
-
const sections = splitSections(lines);
|
|
108
|
+
const sections = splitSections(markdownLines(text));
|
|
210
109
|
const byName = new Map();
|
|
211
110
|
for (const s of sections) {
|
|
212
111
|
const key = Object.keys(SECTIONS).find((k) => fold(SECTIONS[k]) === fold(s.name));
|
|
213
112
|
if (key && !byName.has(key)) byName.set(key, s);
|
|
214
113
|
}
|
|
215
114
|
const body = (key) => byName.get(key)?.lines ?? [];
|
|
216
|
-
const decisions = parseDecisions(body('decisions'));
|
|
217
|
-
const errata = byName.get('errata');
|
|
218
115
|
|
|
219
116
|
return {
|
|
220
117
|
sections: sections.map((s) => ({ name: s.name, line: s.line, key: [...byName].find(([, v]) => v === s)?.[0] ?? null })),
|
|
221
118
|
present: Object.fromEntries(Object.keys(SECTIONS).map((k) => [k, byName.has(k)])),
|
|
222
119
|
scenarios: parseScenarios(body('scenarios')),
|
|
223
|
-
adrs: decisions.adrs,
|
|
224
|
-
conflicts: decisions.conflicts,
|
|
225
|
-
reuse: parseReuse(body('reuse')),
|
|
226
120
|
summary: parseSummary(body('summary')),
|
|
227
|
-
|
|
228
|
-
states: parseStates(body('states')),
|
|
229
|
-
flow: parseStates(body('flow')),
|
|
230
|
-
sectionsAfterErrata: errata ? sections.filter((s) => s.line > errata.line).map((s) => s.name) : [],
|
|
121
|
+
decisions: body('decisions').filter((l) => !l.fenced && /^[-*]\s+\S/.test(l.raw)).map((l) => l.raw.replace(/^[-*]\s+/, '').trim()),
|
|
231
122
|
};
|
|
232
123
|
}
|
|
@@ -76,6 +76,7 @@ function parseBlockers(body) {
|
|
|
76
76
|
const untyped = [];
|
|
77
77
|
for (const cells of tableRows(body, (header) => !isStatusHeader(header))) {
|
|
78
78
|
const row = { id: cleanId(cells[0]), type: normalize(cells[1]), where: cells[2] ?? '', evidence: cells[3] ?? '' };
|
|
79
|
+
if (/^nenhum\b/.test(foldAccents(row.id))) continue;
|
|
79
80
|
if (CLOSED_ROW_RE.test(normalize(row.evidence.replace(/[*_`]/g, '')))) continue;
|
|
80
81
|
(BLOCKER_TYPES.includes(row.type) ? blockers : untyped).push(row);
|
|
81
82
|
}
|
|
@@ -83,6 +84,8 @@ function parseBlockers(body) {
|
|
|
83
84
|
}
|
|
84
85
|
|
|
85
86
|
const STATUS_BY_KEY = Object.fromEntries(CHECK_STATUSES.map((s) => [normalize(s), s]));
|
|
87
|
+
// "PROVADO (nota)" and "PROVADO, com B3" are PROVADO: the note is cut, then the match stays exact (NÃO PROVADO contains PROVADO).
|
|
88
|
+
const statusOf = (raw) => STATUS_BY_KEY[normalize(raw)] ?? STATUS_BY_KEY[normalize(raw.replace(/\s*[(,;—–].*$/, ''))] ?? raw;
|
|
86
89
|
|
|
87
90
|
// Vale a última linha de cada Cn em todas as seções: uma confirmação traz só os Cn que mudou.
|
|
88
91
|
function parseChecks(bodies) {
|
|
@@ -92,7 +95,7 @@ function parseChecks(bodies) {
|
|
|
92
95
|
if (!/^C\d+$/.test(id)) continue;
|
|
93
96
|
const raw = String(cells[1] ?? '').replace(/[*`]/g, '').trim();
|
|
94
97
|
byId.delete(id);
|
|
95
|
-
byId.set(id, { id, status:
|
|
98
|
+
byId.set(id, { id, status: statusOf(raw), evidence: cells[2] ?? '' });
|
|
96
99
|
}
|
|
97
100
|
return [...byId.values()];
|
|
98
101
|
}
|
|
@@ -1,9 +1,3 @@
|
|
|
1
|
-
/** A markdown table separator row: `|---|:--:|`, with or without the outer pipes. */
|
|
2
|
-
export const SEPARATOR_ROW_RE = /^\s*\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)*\|?\s*$/;
|
|
3
|
-
|
|
4
|
-
/** A line that belongs to a table: it carries an unescaped pipe (GFM does not require the leading one). */
|
|
5
|
-
export const isTableLine = (line) => /(?<!\\)\|/.test(line);
|
|
6
|
-
|
|
7
1
|
/** Splits on unescaped pipes, outer pipes optional; `\|` inside a cell is a literal pipe. */
|
|
8
2
|
export function tableCells(row) {
|
|
9
3
|
const inner = row.trim().replace(/^\|/, '').replace(/(?<!\\)\|$/, '');
|
|
@@ -197,8 +197,8 @@ export const REVIEW_REPORT_CONTRACT = [
|
|
|
197
197
|
'Nunca leia os relatórios dos outros papéis.',
|
|
198
198
|
'',
|
|
199
199
|
`Primeira linha \`${VERDICT_TOKEN} ${VERDICTS.join('|')}\`, depois \`${REVIEWED_SHA_TOKEN} {sha}\`, ` +
|
|
200
|
-
'tabela `## Bloqueadores` (`| id | tipo | onde | evidência |`; vazia = `Nenhum.`) e
|
|
201
|
-
'Bloqueador só com evidência e tipo; o resto
|
|
200
|
+
'tabela `## Bloqueadores` (`| id | tipo | onde | evidência |`; vazia = `Nenhum.`) e mais nada: sem notas nem narrativa. ' +
|
|
201
|
+
'Bloqueador só com evidência e tipo; o resto fica fora.',
|
|
202
202
|
];
|
|
203
203
|
|
|
204
204
|
function buildBody(agent, maxTurns) {
|
|
@@ -1,59 +0,0 @@
|
|
|
1
|
-
export const ERRATA_HEADING = '## Errata';
|
|
2
|
-
|
|
3
|
-
/** The one normalization every reader of a frozen markdown applies. */
|
|
4
|
-
export function normalizeMarkdown(text) {
|
|
5
|
-
return String(text ?? '').replace(/^/, '').replace(/\r\n?/g, '\n');
|
|
6
|
-
}
|
|
7
|
-
|
|
8
|
-
export function markdownLines(text) {
|
|
9
|
-
const out = [];
|
|
10
|
-
let fence = null;
|
|
11
|
-
normalizeMarkdown(text).split('\n').forEach((raw, i) => {
|
|
12
|
-
const opener = /^\s*(`{3,}|~{3,})/.exec(raw);
|
|
13
|
-
let fenced = Boolean(fence);
|
|
14
|
-
if (fence) {
|
|
15
|
-
if (opener && opener[1][0] === fence[0] && opener[1].length >= fence.length) fence = null;
|
|
16
|
-
} else if (opener) {
|
|
17
|
-
fence = opener[1];
|
|
18
|
-
fenced = true;
|
|
19
|
-
}
|
|
20
|
-
out.push({ raw, n: i + 1, fenced });
|
|
21
|
-
});
|
|
22
|
-
return out;
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
const isErrataHeading = (line) => !line.fenced
|
|
26
|
-
&& /^##\s+errata\s*$/i.test(line.raw);
|
|
27
|
-
|
|
28
|
-
/** Offset in the NORMALIZED text, or -1. */
|
|
29
|
-
export function errataOffset(text) {
|
|
30
|
-
let offset = 0;
|
|
31
|
-
for (const line of markdownLines(text)) {
|
|
32
|
-
if (isErrataHeading(line)) return offset;
|
|
33
|
-
offset += line.raw.length + 1;
|
|
34
|
-
}
|
|
35
|
-
return -1;
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
export function frozenBody(text) {
|
|
39
|
-
const norm = normalizeMarkdown(text);
|
|
40
|
-
const at = errataOffset(norm);
|
|
41
|
-
return (at === -1 ? norm : norm.slice(0, at)).trimEnd();
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
export function errataViolation(original, proposed) {
|
|
45
|
-
if (frozenBody(proposed) !== frozenBody(original)) {
|
|
46
|
-
return { ok: false, why: 'o corpo aprovado mudou — errata só ACRESCENTA ao fim, nunca altera o texto aprovado' };
|
|
47
|
-
}
|
|
48
|
-
const next = normalizeMarkdown(proposed);
|
|
49
|
-
const nextAt = errataOffset(next);
|
|
50
|
-
if (nextAt === -1) {
|
|
51
|
-
return { ok: false, why: `o conteúdo novo precisa estar sob um bloco \`${ERRATA_HEADING}\` no fim do arquivo` };
|
|
52
|
-
}
|
|
53
|
-
const prev = normalizeMarkdown(original);
|
|
54
|
-
const prevAt = errataOffset(prev);
|
|
55
|
-
if (prevAt !== -1 && !next.slice(nextAt).startsWith(prev.slice(prevAt).trimEnd())) {
|
|
56
|
-
return { ok: false, why: 'a errata existente foi reescrita — ela é append-only, entradas anteriores não se apagam' };
|
|
57
|
-
}
|
|
58
|
-
return { ok: true };
|
|
59
|
-
}
|