JavaScript Python PHP
import { isAlias, isMap, isScalar, isSeq, LineCounter, parseDocument } from "yaml";
function executar(values) {
function productivityText(value, label = 'Campo') {
if (value === undefined)
return '';
if (typeof value !== 'string' || value.length > 100000)
throw new Error(label + ': informe texto de até 100 mil unidades UTF-16.');
if (/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f\uD800-\uDFFF]/u.test(value))
throw new Error(label + ': caracteres de controle ou Unicode inválido.');
return value.replace(/\r\n?/g, '\n');
}
function productivityOutput(output) {
if (output.text.length > 1000000)
throw new Error('Saída excede 1 milhão de unidades UTF-16.');
return output;
}
function generateRoadmapBacklog(v) {
const mode = productivityChoice(v.mode, ['Roadmap', 'Backlog']), name = productivityLabel(v.name, 'Projeto'), roadmap = mode === 'Roadmap';
const list = productivityArray(v.input, mode), ids = new Map();
const keys = roadmap ? ['id', 'title', 'objective', 'period', 'owner', 'status'] : ['id', 'kind', 'title', 'description', 'parent', 'priority', 'acceptance'];
const records = list.map((item, index) => {
const row = productivityObject(item, 'Item ' + (index + 1), keys), id = productivityLabel(row.id, 'ID');
if (!/^[A-Za-z0-9_.-]{1,40}$/.test(id) || ids.has(id))
throw new Error('IDs devem ser únicos, com 1–40 letras ASCII, dígitos, _, . ou -.');
productivityLabel(row.title, 'Título');
if (roadmap) {
productivityLabel(row.objective, 'Objetivo');
productivityLabel(row.period, 'Período');
productivityLabel(row.owner, 'Responsável', true);
productivityChoice(row.status, ['Planejado', 'Em andamento', 'Concluído']);
}
else {
productivityChoice(row.kind, ['Épico', 'História', 'Tarefa']);
productivityChoice(row.priority, ['Alta', 'Média', 'Baixa']);
productivityText(row.description, 'Descrição');
productivityLabel(row.parent, 'Pai', true);
if (row.acceptance !== undefined && (!Array.isArray(row.acceptance) || row.acceptance.length > 100 || row.acceptance.some(x => !productivityLabel(x, 'Critério de aceite'))))
throw new Error('Critérios de aceite: lista de até 100 strings não vazias.');
}
ids.set(id, row);
return { row, id };
});
let text = '# ' + mode + ' — ' + productivityMd(name) + '\n';
const detail = (title, value) => productivitySection(title, value).replace(/^\n## /, '\n### ');
for (const { row, id } of records) {
if (roadmap) {
text += '\n## ' + productivityMd(productivityLabel(row.period, 'Período')) + ' — ' + productivityMd(id) + ': ' + productivityMd(productivityLabel(row.title, 'Título')) + '\n';
text += detail('Objetivo', row.objective) + detail('Responsável', row.owner) + detail('Status', row.status);
}
else {
const parent = productivityLabel(row.parent, 'Pai', true);
if (parent && (!ids.has(parent) || (row.kind === 'Épico' || row.kind === 'História' && ids.get(parent).kind !== 'Épico' || row.kind === 'Tarefa' && ids.get(parent).kind !== 'História')))
throw new Error('Pai inválido em ' + id + ': História pode apontar para Épico; Tarefa para História; Épico não tem pai.');
text += '\n## ' + productivityMd(id) + ' — ' + productivityMd(productivityLabel(row.title, 'Título')) + '\n';
text += detail('Tipo', row.kind) + detail('Prioridade', row.priority) + detail('Pai', parent) + detail('Descrição', row.description);
if (Array.isArray(row.acceptance) && row.acceptance.length)
text += '\n### Critérios de aceite\n\n' + row.acceptance.map(item => '- [ ] ' + productivityMd(item)).join('\n') + '\n';
}
}
return { text, filename: roadmap ? 'roadmap.md' : 'backlog.md' };
}
function text(value, label) {
if (typeof value !== 'string')
throw new Error(label + ': informe texto.');
if (value.length > 100_000)
throw new Error(label + ': limite de 100 mil caracteres.');
return value;
}
function productivityLabel(value, label, optional = false) {
const content = productivityText(value, label).trim();
if ((!content && !optional) || content.length > 200 || /[\n\t\u2028\u2029]/.test(content))
throw new Error(label + ': use uma linha de 1–200 caracteres' + (optional ? ' ou deixe vazio.' : '.'));
return content;
}
function productivityChoice(value, options) {
if (typeof value !== 'string' || !options.includes(value))
throw new Error('Escolha uma opção válida: ' + options.join(', ') + '.');
return value;
}
function productivityMd(value) {
return value.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/[\\`*_{}[\]()#+.!|~-]/g, '\\$&');
}
function productivitySection(title, value, list = false, required = false) {
if (list) {
const lines = productivityLines(value, title, required);
return lines.length ? '\n## ' + title + '\n\n' + lines.map(line => '- ' + productivityMd(line)).join('\n') + '\n' : '';
}
const content = productivityText(value, title).trim();
if (required && !content)
throw new Error('Preencha ' + title + '.');
return content ? '\n## ' + title + '\n\n' + productivityMd(content) + '\n' : '';
}
function productivityObject(value, label, keys) {
if (!value || typeof value !== 'object' || Array.isArray(value))
throw new Error(label + ': use um objeto JSON.');
if (keys)
for (const key of Object.keys(value))
if (!keys.includes(key))
throw new Error(label + ': campo não suportado: ' + key + '.');
return value;
}
function productivityArray(input, label, limit = 500) {
const value = json(input, label);
if (!Array.isArray(value) || !value.length || value.length > limit)
throw new Error(label + ': use uma lista JSON não vazia com até ' + limit + ' itens.');
return value;
}
function json(input, label, objectOnly = false) {
try {
const value = parseJsonCompatible(text(input, label), 'JSON');
if (objectOnly && (!value || typeof value !== 'object' || Array.isArray(value)))
throw new Error('Informe um objeto JSON.');
return value;
}
catch (cause) {
const message = cause && typeof cause === 'object' && 'message' in cause && typeof cause.message === 'string' ? cause.message : 'JSON inválido.';
throw new Error(label + ': ' + message);
}
}
function parseJsonCompatible(input, format, onObjectKeys) {
if (!input.trim())
throw new Error(`Informe um documento ${format}.`);
if (input.length > 1_000_000)
throw new Error('A entrada excede o limite de 1 milhão de caracteres.');
if (format === 'JSON') {
// Syntax check only: do not use the rounded numeric values from JSON.parse.
try {
JSON.parse(input);
}
catch (cause) {
throw new Error(`JSON inválido: ${cause instanceof Error ? cause.message : 'erro de sintaxe'}`);
}
}
const lines = new LineCounter();
const doc = parseDocument(input, { version: '1.2', schema: format === 'JSON' ? 'json' : 'core', intAsBigInt: true, uniqueKeys: true, lineCounter: lines, prettyErrors: true, resolveKnownTags: false });
const issue = doc.errors[0] ?? doc.warnings[0];
if (issue)
throw new Error(`${format} inválido (${issue.code}): ${issue.message}`);
if (doc.directives?.yaml.version !== '1.2')
throw new Error('Somente YAML 1.2 é aceito para preservar os tipos de JSON.');
let count = 0;
function fail(message, node) {
const offset = node?.range?.[0];
const position = offset === undefined ? '' : (() => { const { line, col } = lines.linePos(offset); return ` (linha ${line}, coluna ${col})`; })();
throw new Error(message + position);
}
function convert(node, depth = 0) {
if (++count > 100_000 || depth > 100)
fail('Documento muito complexo: limite de 100 níveis ou 100 mil nós.', node);
if (!node)
return null;
if (isAlias(node))
fail('Aliases YAML não são aceitos: JSON não preserva referências ou ciclos.', node);
if (node.tag && !SAFE_TAGS.has(node.tag))
fail(`Tag não permitida: ${node.tag}.`, node);
if (isScalar(node)) {
const value = node.value;
if (typeof value === 'bigint') {
if (value === BigInt(0) && node.source?.startsWith('-'))
fail('JSON de saída não preserva o sinal de zero negativo. Use 0 ou uma string.', node);
if (value > BigInt(Number.MAX_SAFE_INTEGER) || value < BigInt(Number.MIN_SAFE_INTEGER))
fail('Inteiro fora do intervalo seguro de JSON/JavaScript. Use uma string entre aspas para preservar todos os dígitos.', node);
return Number(value);
}
if (typeof value === 'number') {
if (!Number.isFinite(value))
fail('JSON não representa NaN ou infinito.', node);
if (Number.isInteger(value) && !Number.isSafeInteger(value))
fail('Número inteiro fora do intervalo seguro. Use uma string entre aspas para preservar a precisão.', node);
if (value === 0 && /[1-9]/.test((node.source ?? '').split(/[eE]/)[0]))
fail('Número pequeno demais para a precisão de JavaScript. Use uma string entre aspas.', node);
if (Object.is(value, -0))
fail('JSON de saída não preserva o sinal de zero negativo. Use 0 ou uma string.', node);
return value;
}
if (value === null || typeof value === 'string' || typeof value === 'boolean')
return value;
fail('Valor não representável em JSON.', node);
}
if (isSeq(node))
return node.items.map(item => convert(item, depth + 1));
if (isMap(node)) {
const result = Object.create(null);
const keys = [];
for (const pair of node.items) {
if (!isScalar(pair.key) || typeof pair.key.value !== 'string')
fail('Chaves de objetos devem ser strings; chaves numéricas, booleanas ou complexas não são preservadas em JSON.', pair.key);
const key = pair.key.value;
if (format === 'YAML' && key === '<<' && pair.key.type === 'PLAIN')
fail('Chaves de merge YAML (<<) não são aceitas.', pair.key);
if (Object.hasOwn(result, key))
fail(`Chave duplicada: ${key}.`, pair.key);
keys.push(key);
result[key] = convert(pair.value, depth + 1);
}
onObjectKeys?.(result, keys);
return result;
}
fail('Estrutura não representável em JSON.', node);
}
if (!doc.contents)
throw new Error('Informe um documento com um valor; use null para um valor nulo.');
return convert(doc.contents);
}
function productivityLines(value, label, required = false) {
const lines = productivityText(value, label).split('\n').map(line => line.trim()).filter(Boolean);
if (lines.length > 500 || required && !lines.length)
throw new Error(label + ': informe de ' + (required ? '1' : '0') + ' a 500 linhas não vazias.');
return lines;
}
function result(value) {
const output = JSON.stringify(value, null, 2);
if (output.length > 1_000_000)
throw new Error('Resultado excede 1 milhão de caracteres.');
return output;
}
const SAFE_TAGS = new Set(['str', 'bool', 'null', 'int', 'float', 'map', 'seq'].map(tag => `tag:yaml.org,2002:${tag}`));
for (const value of Object.values(values)) productivityText(value);
return productivityOutput(generateRoadmapBacklog(values));
}
import re
import json
import math
def executar(values):
def text(value='', label='Campo'):
if not isinstance(value,str) or len(value.encode('utf-16-le',errors='surrogatepass'))//2 > 100000: raise ValueError(label+': informe texto de até 100 mil unidades UTF-16.')
if re.search(r'[\x00-\x08\x0b\x0c\x0e-\x1f\x7f\ud800-\udfff]',value): raise ValueError(label+': controles ou Unicode inválido.')
return value.replace('\r\n','\n').replace('\r','\n')
def trim(value):
return value.strip('\t\n\r \v\f\u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000\ufeff')
def label(value, title, optional=False):
content=trim(text(value,title))
if (not content and not optional) or len(content.encode('utf-16-le'))//2>200 or re.search(r'[\n\t\u2028\u2029]',content): raise ValueError(title+': use uma linha de 1–200 caracteres.')
return content
def choice(value, options):
if value not in options: raise ValueError('Escolha uma opção válida.')
return value
def md(value):
value=value.replace('&','&').replace('<','<').replace('>','>')
return re.sub(r'[\\`*_{}[\]()#+.!|~-]',lambda m:'\\'+m[0],value)
def lines(value, title, required=False):
result=[trim(line) for line in text(value,title).split('\n') if trim(line)]
if len(result)>500 or required and not result: raise ValueError(title+': informe até 500 linhas não vazias.')
return result
def section(title, value='', listing=False, required=False):
if listing:
items=lines(value,title,required)
return '\n## '+title+'\n\n'+'\n'.join('- '+md(item) for item in items)+'\n' if items else ''
content=trim(text(value,title))
if required and not content: raise ValueError('Preencha '+title+'.')
return '\n## '+title+'\n\n'+md(content)+'\n' if content else ''
def obj(value, title, keys=None):
if not isinstance(value,dict): raise ValueError(title+': use um objeto JSON.')
if keys is not None and any(key not in keys for key in value): raise ValueError(title+': campo não suportado.')
return value
def array_input(source,title,limit=500):
value=read(source,title)
if not isinstance(value,list) or not value or len(value)>limit: raise ValueError(title+': lista JSON não vazia fora do limite.')
return value
def finish(content, filename):
if len(content.encode('utf-16-le'))//2>1000000: raise ValueError('Saída excede 1 milhão de unidades UTF-16.')
return {'text':content,'filename':filename}
def read(source, label, object_only=False):
text(source, label)
if not source.strip(): raise ValueError(label + ': informe JSON')
def pairs(items):
result = {}
for key, value in items:
if key in result: raise ValueError('Chave duplicada: ' + key)
result[key] = value
return result
def number(token):
if '.' not in token and 'e' not in token.lower() and len(token.lstrip('-')) > 16: raise ValueError('Inteiro fora do intervalo seguro; use string')
value = float(token) if '.' in token or 'e' in token.lower() else int(token)
if not math.isfinite(value): raise ValueError('Número não finito')
if value == 0 and (token.startswith('-') or re.search('[1-9]', token.lower().split('e')[0])): raise ValueError('Zero negativo ou underflow')
if value % 1 == 0 and abs(value) > 9007199254740991: raise ValueError('Inteiro fora do intervalo seguro; use string')
return value
def reject(value): raise ValueError('Constante JSON inválida: ' + value)
value = json.loads(source, object_pairs_hook=pairs, parse_int=number, parse_float=number, parse_constant=reject)
count = 0
def walk(value, depth=0):
nonlocal count
count += 1
if count > 100000 or depth > 100: raise ValueError('Limite de 100 níveis ou 100 mil nós JSON')
if isinstance(value, dict):
for child in value.values(): walk(child, depth + 1)
elif isinstance(value, list):
for child in value: walk(child, depth + 1)
walk(value)
if object_only and not isinstance(value, dict): raise ValueError(label + ': informe objeto JSON')
return value
for value in values.values(): text(value)
mode=choice(values.get('mode'),['Roadmap','Backlog']); name=label(values.get('name',''),'Projeto'); roadmap=mode=='Roadmap'; ids={}; records=[]
keys=['id','title','objective','period','owner','status'] if roadmap else ['id','kind','title','description','parent','priority','acceptance']
for item in array_input(values.get('input',''),mode):
row=obj(item,'Item',keys); identifier=label(row.get('id',''),'ID')
if not re.fullmatch(r'[A-Za-z0-9_.-]{1,40}',identifier) or identifier in ids: raise ValueError('ID inválido ou repetido.')
label(row.get('title',''),'Título')
if roadmap:
label(row.get('objective',''),'Objetivo'); label(row.get('period',''),'Período'); label(row.get('owner',''),'Responsável',True); choice(row.get('status'),['Planejado','Em andamento','Concluído'])
else:
choice(row.get('kind'),['Épico','História','Tarefa']); choice(row.get('priority'),['Alta','Média','Baixa']); text(row.get('description',''),'Descrição'); label(row.get('parent',''),'Pai',True)
if 'acceptance' in row:
if not isinstance(row['acceptance'],list) or len(row['acceptance'])>100: raise ValueError('Critérios de aceite inválidos.')
for item in row['acceptance']: label(item,'Critério de aceite')
ids[identifier]=row; records.append((row,identifier))
out='# '+mode+' — '+md(name)+'\n'
detail=lambda title,value: section(title,value).replace('\n## ','\n### ',1)
for row,identifier in records:
if roadmap:
out+='\n## '+md(label(row['period'],'Período'))+' — '+md(identifier)+': '+md(label(row['title'],'Título'))+'\n'
out+=detail('Objetivo',row['objective'])+detail('Responsável',row.get('owner',''))+detail('Status',row['status'])
else:
parent=label(row.get('parent',''),'Pai',True)
if parent and (parent not in ids or row['kind']=='Épico' or row['kind']=='História' and ids[parent]['kind']!='Épico' or row['kind']=='Tarefa' and ids[parent]['kind']!='História'): raise ValueError('Pai inválido: História → Épico; Tarefa → História.')
out+='\n## '+md(identifier)+' — '+md(label(row['title'],'Título'))+'\n'
out+=detail('Tipo',row['kind'])+detail('Prioridade',row['priority'])+detail('Pai',parent)+detail('Descrição',row.get('description',''))
if row.get('acceptance'): out+='\n### Critérios de aceite\n\n'+'\n'.join('- [ ] '+md(item) for item in row['acceptance'])+'\n'
return finish(out,'roadmap.md' if roadmap else 'backlog.md')
<?php
function executar(array $values): array {
$text = function ($value = '', $label = 'Campo') {
if (!is_string($value) || !preg_match('//u', $value) || strlen(iconv('UTF-8','UTF-16LE',$value))/2 > 100000) throw new InvalidArgumentException($label.': texto de até 100 mil unidades UTF-16.');
if (preg_match('/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/', $value)) throw new InvalidArgumentException($label.': caracteres de controle.');
return str_replace(["\r\n","\r"],"\n",$value);
};
$read = function ($source, $label, $objectOnly = false) use ($text) {
$source = $text($source, $label);
if (trim($source) === '') throw new InvalidArgumentException($label.': informe JSON');
json_decode($source, false, 512, JSON_THROW_ON_ERROR | JSON_BIGINT_AS_STRING);
$stack = [];
for ($i = 0; $i < strlen($source); $i++) {
$ch = $source[$i];
if ($ch === '{' || $ch === '[') { $stack[] = ['object'=>$ch === '{', 'keys'=>[]]; continue; }
if ($ch === '}' || $ch === ']') { array_pop($stack); continue; }
if ($ch === '"') {
$start = $i; $escaped = false;
while (++$i < strlen($source)) { $c = $source[$i]; if ($escaped) $escaped = false; elseif ($c === '\\') $escaped = true; elseif ($c === '"') break; }
$look = $i + 1; while ($look < strlen($source) && str_contains(" \t\r\n", $source[$look])) $look++;
$index = count($stack) - 1;
if ($index >= 0 && $stack[$index]['object'] && ($source[$look] ?? '') === ':') {
$key = json_decode(substr($source, $start, $i-$start+1), false, 512, JSON_THROW_ON_ERROR);
if (array_key_exists($key, $stack[$index]['keys'])) throw new InvalidArgumentException('Chave duplicada: '.$key);
$stack[$index]['keys'][$key] = true;
}
} elseif ($ch === '-' || ctype_digit($ch)) {
preg_match('/\G-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?/', $source, $match, 0, $i);
$token = $match[0]; $value = (float)$token; $mantissa = explode('e', strtolower($token))[0];
if (!is_finite($value) || ($value == 0 && (str_starts_with($token, '-') || preg_match('/[1-9]/', $mantissa))) || (floor($value) === $value && abs($value) > 9007199254740991)) throw new InvalidArgumentException('Número não preservável; use string');
$i += strlen($token)-1;
}
}
$value = json_decode($source, false, 512, JSON_THROW_ON_ERROR);
$count = 0;
$walk = function ($value, $depth = 0) use (&$walk, &$count) {
if (++$count > 100000 || $depth > 100) throw new InvalidArgumentException('Limite de 100 níveis ou 100 mil nós JSON');
if (is_object($value) || is_array($value)) foreach ($value as $child) $walk($child, $depth+1);
};
$walk($value);
if ($objectOnly && !is_object($value)) throw new InvalidArgumentException($label.': informe objeto JSON');
return $value;
};
$trimText = fn($value)=>preg_replace('/^[\s\x{FEFF}]+|[\s\x{FEFF}]+$/u','',$value);
$label = function ($value,$title,$optional=false) use ($text,$trimText) {
$content=$trimText($text($value,$title));
if (($content==='' && !$optional) || strlen(iconv('UTF-8','UTF-16LE',$content))/2>200 || preg_match('/[\n\t\x{2028}\x{2029}]/u',$content)) throw new InvalidArgumentException($title.': use uma linha de 1–200 caracteres.');
return $content;
};
$choice = function ($value,$options) {
if (!in_array($value,$options,true)) throw new InvalidArgumentException('Escolha uma opção válida.');
return $value;
};
$md = function ($value) {
$value=str_replace(['&','<','>'],['&','<','>'],$value);
return preg_replace_callback('/[\\\\`*_{}\[\]()#+.!|~\-]/',fn($m)=>'\\'.$m[0],$value);
};
$lines = function ($value,$title,$required=false) use ($text,$trimText) {
$result=array_values(array_filter(array_map($trimText,explode("\n",$text($value,$title))),fn($x)=>$x!==''));
if (count($result)>500 || ($required && !$result)) throw new InvalidArgumentException($title.': informe até 500 linhas não vazias.');
return $result;
};
$section = function ($title,$value='',$listing=false,$required=false) use ($lines,$md,$text,$trimText) {
if ($listing) { $items=$lines($value,$title,$required); return $items ? "\n## ".$title."\n\n".implode("\n",array_map(fn($x)=>'- '.$md($x),$items))."\n" : ''; }
$content=$trimText($text($value,$title));
if ($required && $content==='') throw new InvalidArgumentException('Preencha '.$title.'.');
return $content!=='' ? "\n## ".$title."\n\n".$md($content)."\n" : '';
};
$obj = function ($value,$title,$keys=null) {
if (!is_object($value)) throw new InvalidArgumentException($title.': use objeto JSON.');
if ($keys!==null) foreach (get_object_vars($value) as $key=>$unused) if (!in_array((string)$key,$keys,true)) throw new InvalidArgumentException($title.': campo não suportado: '.$key);
return $value;
};
$arrayInput = function ($source,$title,$limit=500) use ($read) {
$value=$read($source,$title);
if (!is_array($value) || !$value || count($value)>$limit) throw new InvalidArgumentException($title.': lista JSON não vazia fora do limite.');
return $value;
};
$finish = function ($content,$filename) {
if (strlen(iconv('UTF-8','UTF-16LE',$content))/2>1000000) throw new InvalidArgumentException('Saída excede 1 milhão de unidades UTF-16.');
return ['text'=>$content,'filename'=>$filename];
};
$get = fn($object,$key)=>property_exists($object,$key) ? $object->{$key} : '';
foreach ($values as $value) $text($value);
$mode=$choice($values['mode'],['Roadmap','Backlog']); $name=$label($values['name'] ?? '','Projeto'); $roadmap=$mode==='Roadmap'; $ids=[]; $records=[];
$keys=$roadmap ? ['id','title','objective','period','owner','status'] : ['id','kind','title','description','parent','priority','acceptance'];
foreach ($arrayInput($values['input'] ?? '',$mode) as $item) {
$row=$obj($item,'Item',$keys); $id=$label($get($row,'id'),'ID');
if (!preg_match('/^[A-Za-z0-9_.-]{1,40}$/D',$id) || array_key_exists($id,$ids)) throw new InvalidArgumentException('ID inválido ou repetido.');
$label($get($row,'title'),'Título');
if ($roadmap) { $label($get($row,'objective'),'Objetivo'); $label($get($row,'period'),'Período'); $label($get($row,'owner'),'Responsável',true); $choice($get($row,'status'),['Planejado','Em andamento','Concluído']); }
else {
$choice($get($row,'kind'),['Épico','História','Tarefa']); $choice($get($row,'priority'),['Alta','Média','Baixa']); $text($get($row,'description'),'Descrição'); $label($get($row,'parent'),'Pai',true);
if (property_exists($row,'acceptance')) { if (!is_array($row->acceptance) || count($row->acceptance)>100) throw new InvalidArgumentException('Critérios de aceite inválidos.'); foreach ($row->acceptance as $item) $label($item,'Critério de aceite'); }
}
$ids[$id]=$row; $records[]=[$row,$id];
}
$out='# '.$mode.' — '.$md($name)."\n";
$detail=fn($title,$value)=>preg_replace('/^\n## /',"\n### ",$section($title,$value));
foreach ($records as [$row,$id]) {
if ($roadmap) {
$out.="\n## ".$md($label($row->period,'Período')).' — '.$md($id).': '.$md($label($row->title,'Título'))."\n";
$out.=$detail('Objetivo',$row->objective).$detail('Responsável',$get($row,'owner')).$detail('Status',$row->status);
} else {
$parent=$label($get($row,'parent'),'Pai',true);
if ($parent!=='' && (!array_key_exists($parent,$ids) || $row->kind==='Épico' || $row->kind==='História' && $ids[$parent]->kind!=='Épico' || $row->kind==='Tarefa' && $ids[$parent]->kind!=='História')) throw new InvalidArgumentException('Pai inválido: História → Épico; Tarefa → História.');
$out.="\n## ".$md($id).' — '.$md($label($row->title,'Título'))."\n";
$out.=$detail('Tipo',$row->kind).$detail('Prioridade',$row->priority).$detail('Pai',$parent).$detail('Descrição',$get($row,'description'));
if (property_exists($row,'acceptance') && count($row->acceptance)) $out.="\n### Critérios de aceite\n\n".implode("\n",array_map(fn($item)=>'- [ ] '.$md($item),$row->acceptance))."\n";
}
}
return $finish($out,$roadmap ? 'roadmap.md' : 'backlog.md');
}