agentic-workflow-manager 9.20.1 → 9.20.3

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.
@@ -475,7 +475,7 @@ function registerChangeCommand(program, deps = {}) {
475
475
  change
476
476
  .command('new <slug>')
477
477
  .description('create docs/changes/YYYY-MM-DD-<slug>.md with derived fields and pending narrative')
478
- .option('--base <ref>', 'base branch (default: origin/HEAD, main, master)')
478
+ .option('--base <ref>', range_1.BASE_OPTION_HELP)
479
479
  .option('--plan <path>', 'repo-relative plan file to link')
480
480
  .option('--issue <url>', 'https issue URL to link')
481
481
  .option('--model <model>', 'provenance: model identifier')
@@ -485,7 +485,7 @@ function registerChangeCommand(program, deps = {}) {
485
485
  change
486
486
  .command('validate [path]')
487
487
  .description('validate the Change Record(s) added by this branch, or one record (--strict also checks the sensor receipt)')
488
- .option('--base <ref>', 'base branch (default: origin/HEAD, main, master)')
488
+ .option('--base <ref>', range_1.BASE_OPTION_HELP)
489
489
  .option('--strict', 'require a matching, passing sensor receipt for verification.commit')
490
490
  .option('--json', 'print a single JSON line')
491
491
  .action((target, opts) => inCwd((cwd) => runChangeValidate(cwd, target, opts), wantsJson(opts)));
@@ -10,6 +10,7 @@ const command_1 = require("../../core/changes/command");
10
10
  const git_1 = require("../../core/changes/git");
11
11
  const list_1 = require("../../core/changes/list");
12
12
  const list_parse_1 = require("../../core/changes/list-parse");
13
+ const range_1 = require("../../core/changes/range");
13
14
  const render_list_1 = require("../../core/changes/render-list");
14
15
  const text_safety_1 = require("../../core/changes/text-safety");
15
16
  const FORMATS = ['text', 'json', 'voice'];
@@ -78,7 +79,7 @@ function registerChangesCommand(program, deps = {}) {
78
79
  .command('list')
79
80
  .description('list the changes of the base branch with their Change Record and derived merge/release state')
80
81
  .option('--since <window>', '<n>h, <n>d or YYYY-MM-DD (default 24h)')
81
- .option('--base <ref>', 'base branch (default: origin/HEAD, main, master)')
82
+ .option('--base <ref>', range_1.BASE_OPTION_HELP)
82
83
  .option('--format <format>', 'text | json | voice (default text)')
83
84
  .action((opts) => (0, command_1.inCwd)((cwd) => runChangesList(cwd, opts, deps), () => (0, command_1.fail)('not-a-git-repo', 'the working directory is not accessible')));
84
85
  }
@@ -15,6 +15,7 @@ const types_1 = require("./types");
15
15
  // Pathspecs relative to the repository top, so the result does not depend on the directory git runs in.
16
16
  const ALL_FILES = ':/';
17
17
  const EXCLUDE_RECORDS = `:(top,exclude,literal)${types_1.RECORD_DIR}`;
18
+ const EXCLUDE_PLANS = ':(top,exclude,literal)docs/plans';
18
19
  const PARSER_TYPE = /^\w+$/;
19
20
  const RECORD_TYPE = /^[a-z]+$/;
20
21
  const MODULE_DEPTH = 3;
@@ -39,18 +40,22 @@ function usable(commits) {
39
40
  }
40
41
  const byCodeUnit = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
41
42
  /**
42
- * R3.3. `breaking` and `semver` cover every usable commit, with the release parser's exact-type semantics; the recorded type is
43
- * the highest-impact commit's type lowercased, or `other` when that is still not purely letters. Null when no commit is usable.
43
+ * R3.3 as amended 2026-10-19. `breaking` and `semver` cover every usable commit, with the release parser's exact-type semantics.
44
+ * `type` and `scope` come from the usable `focus` commits (those touching a path outside docs/changes/ and docs/plans/), or from
45
+ * every usable commit when `focus` is omitted or has none. The recorded type is the highest-impact chosen commit's type
46
+ * lowercased, or `other` when that is still not purely letters. Null when no commit is usable.
44
47
  */
45
- function deriveFromCommits(input) {
48
+ function deriveFromCommits(input, focusInput) {
46
49
  const commits = usable(input);
47
50
  if (commits.length === 0)
48
51
  return null;
52
+ const focused = usable(focusInput);
53
+ const chooser = focused.length > 0 ? focused : commits;
49
54
  const breaking = commits.some((c) => c.breaking);
50
- const pick = commits.find((c) => c.breaking) ?? commits.find((c) => c.type === 'feat') ?? commits.find((c) => c.type === 'fix')
51
- ?? commits.find((c) => c.type === 'perf') ?? commits[0];
55
+ const pick = chooser.find((c) => c.breaking) ?? chooser.find((c) => c.type === 'feat') ?? chooser.find((c) => c.type === 'fix')
56
+ ?? chooser.find((c) => c.type === 'perf') ?? chooser[0];
52
57
  const counts = new Map();
53
- for (const c of commits)
58
+ for (const c of chooser)
54
59
  if (c.scope)
55
60
  counts.set(c.scope, (counts.get(c.scope) ?? 0) + 1);
56
61
  const scope = [...counts.entries()].sort((a, b) => b[1] - a[1] || byCodeUnit(a[0], b[0]))[0]?.[0] ?? null;
@@ -87,6 +92,8 @@ function commitsFromRecords(records) {
87
92
  const fail = (code, message) => ({ ok: false, diagnostic: { code, message: (0, text_safety_1.clipMessage)(message) } });
88
93
  /**
89
94
  * Derives from the non-merge commits in mergeBaseSha..HEAD, ignoring commits and files that only touch docs/changes/.
95
+ * R3.3 amended: `type` and `scope` come from the commits that also touch a path outside docs/plans/ (all of them when no
96
+ * conventional commit does), while `semver` and `breaking` cover every commit.
90
97
  * `mergeBaseSha` must be a full commit id (the output of `mergeBase`); anything else is `invalid-input`.
91
98
  */
92
99
  function deriveFields(root, mergeBaseSha) {
@@ -103,14 +110,20 @@ function deriveFields(root, mergeBaseSha) {
103
110
  // (`merge -s ours`), silently dropping real commits from the range.
104
111
  // -z ends every commit with NUL, which a message cannot contain: each record is exactly one commit, so a message that
105
112
  // embeds the parser's own separator cannot be read as a second commit.
106
- const raw = (0, git_1.runGit)(root, ['log', ...git_1.LOG_SAFETY_ARGS, '--no-merges', '--full-history', '--reverse', '-z', `--format=${core_1.GIT_LOG_FORMAT}`, '--end-of-options', range, '--', ALL_FILES, EXCLUDE_RECORDS]);
113
+ const logArgs = ['log', ...git_1.LOG_SAFETY_ARGS, '--no-merges', '--full-history', '--reverse', '-z', `--format=${core_1.GIT_LOG_FORMAT}`, '--end-of-options', range, '--', ALL_FILES, EXCLUDE_RECORDS];
114
+ const raw = (0, git_1.runGit)(root, logArgs);
107
115
  if (raw === null)
108
116
  return fail('git-failed', `git could not read the commits in ${range}`);
109
117
  const records = raw.split('\0').filter((record) => record !== '');
110
118
  if (records.length === 0)
111
119
  return fail('no-commits', `no non-merge commits outside ${types_1.RECORD_DIR}/ in ${range}`);
112
120
  const commits = commitsFromRecords(records);
113
- const derived = deriveFromCommits(commits);
121
+ // R3.3 amended: plan-only commits do not choose type or scope, so a second log over the same range drops docs/plans/.
122
+ const focusRaw = (0, git_1.runGit)(root, [...logArgs, EXCLUDE_PLANS]);
123
+ if (focusRaw === null)
124
+ return fail('git-failed', `git could not read the commits in ${range}`);
125
+ const focus = commitsFromRecords(focusRaw.split('\0').filter((record) => record !== ''));
126
+ const derived = deriveFromCommits(commits, focus);
114
127
  if (derived === null)
115
128
  return fail('no-conventional-commits', 'no commit in the range uses a conventional-commit subject (type(scope): subject)');
116
129
  const files = (0, git_1.changedFiles)(root, mergeBaseSha, head);
@@ -3,11 +3,12 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.LOG_SAFETY_ARGS = void 0;
6
+ exports.DEFAULT_BASES = exports.LOG_SAFETY_ARGS = void 0;
7
7
  exports.runGit = runGit;
8
8
  exports.runGitBytes = runGitBytes;
9
9
  exports.isSafeRef = isSafeRef;
10
10
  exports.isSafeRevision = isSafeRevision;
11
+ exports.baseCandidates = baseCandidates;
11
12
  exports.resolveBaseCommit = resolveBaseCommit;
12
13
  exports.mergeBase = mergeBase;
13
14
  exports.isAncestor = isAncestor;
@@ -81,14 +82,44 @@ function isSafeRevision(rev) {
81
82
  return parts.length <= 2 && parts.every(isSafeRef);
82
83
  }
83
84
  /**
84
- * R3.1: --base, then origin/HEAD, then main, then master: the first that names a commit, with that commit's id. Null when none
85
- * does (or the explicit base is unsafe). One `rev-parse` per candidate.
85
+ * R3.1 (amended 2026-10-19): the default base candidates, remote first so a stale local branch is the last resort. The local
86
+ * branches resolve as full refs (git would otherwise prefer a tag `main` over the branch) but are reported by their short name.
87
+ */
88
+ exports.DEFAULT_BASES = [
89
+ { ref: 'refs/remotes/origin/HEAD', name: 'refs/remotes/origin/HEAD' },
90
+ { ref: 'refs/remotes/origin/main', name: 'refs/remotes/origin/main' },
91
+ { ref: 'refs/remotes/origin/master', name: 'refs/remotes/origin/master' },
92
+ { ref: 'refs/heads/main', name: 'main' },
93
+ { ref: 'refs/heads/master', name: 'master' },
94
+ ];
95
+ /**
96
+ * The DEFAULT_BASES whose exact ref exists, in order (one `for-each-ref` for all of them; a broken symref is not listed). Without
97
+ * this check git's rev-parse would fall through to `refs/tags/<ref>`, so a tag literally named `refs/heads/main` could stand in for
98
+ * an absent branch. The patterns are constants; only an exact refname match counts (a pattern also lists the refs below it).
99
+ * Empty when git fails: the defaults then fail closed as unresolved.
100
+ */
101
+ function existingDefaultBases(root) {
102
+ const out = runGit(root, ['for-each-ref', '--format=%(refname)', '--end-of-options', ...exports.DEFAULT_BASES.map((c) => c.ref)]);
103
+ const present = new Set((out ?? '').split('\n'));
104
+ return exports.DEFAULT_BASES.filter((c) => present.has(c.ref));
105
+ }
106
+ /**
107
+ * R3.1: the candidates for a base, in order. An explicit base is the only one (no fallback) and keeps git's own resolution;
108
+ * otherwise the DEFAULT_BASES whose exact ref exists. Every caller (`resolveBaseCommit`, `resolveRange`) takes its order from here.
109
+ */
110
+ function baseCandidates(root, explicit) {
111
+ return explicit !== undefined ? [{ ref: explicit, name: explicit }] : existingDefaultBases(root);
112
+ }
113
+ /**
114
+ * R3.1: --base, then origin/HEAD, origin/main, origin/master, main, master: the first that names a commit, with that commit's id.
115
+ * An explicit base is the only candidate (no fallback). Null when none does (or the explicit base is unsafe). One `rev-parse` per
116
+ * candidate tried (and, for the defaults, one `for-each-ref`).
86
117
  */
87
118
  function resolveBaseCommit(root, explicit) {
88
- for (const candidate of explicit !== undefined ? [explicit] : ['refs/remotes/origin/HEAD', 'main', 'master']) {
89
- const sha = commitSha(root, candidate);
119
+ for (const { ref, name } of baseCandidates(root, explicit)) {
120
+ const sha = commitSha(root, ref);
90
121
  if (sha !== null)
91
- return { base: candidate, sha };
122
+ return { base: name, sha };
92
123
  }
93
124
  return null;
94
125
  }
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.HEAD_MOVED = void 0;
3
+ exports.HEAD_MOVED = exports.BASE_OPTION_HELP = void 0;
4
4
  exports.resolveBaseRef = resolveBaseRef;
5
5
  exports.resolveRange = resolveRange;
6
6
  exports.headMovedFailure = headMovedFailure;
@@ -9,34 +9,49 @@ const git_1 = require("./git");
9
9
  const text_safety_1 = require("./text-safety");
10
10
  const types_1 = require("./types");
11
11
  const REMEDY_BASE = 'pass --base <ref>';
12
+ /** R3.1: the `--base` help text of `change new`, `change validate` and `changes list`: `DEFAULT_BASES` (git.ts) in order, remotes without `refs/remotes/`. */
13
+ exports.BASE_OPTION_HELP = `base branch (default: ${git_1.DEFAULT_BASES.map((c) => c.name.replace(/^refs\/remotes\//, '')).join(', ')})`;
12
14
  exports.HEAD_MOVED = { code: 'head-moved', message: 'HEAD moved during derivation' };
13
15
  const KINDS = ['ok', 'absent', 'unsafe', 'error'];
14
16
  const failure = (code, message, remedy) => ({ ok: false, failure: remedy === undefined ? { code, message } : { code, message, remedy } });
17
+ const unsafeBase = (explicitBase) => failure('invalid-input', `--base "${(0, text_safety_1.esc)(explicitBase)}" is not a safe git ref`);
15
18
  /**
16
- * R3.1/R3.2/R3.5: the base ref: `explicitBase` (checked with `isSafeRef` before git sees it: `invalid-input`), else origin/HEAD,
17
- * main, master; `base-unresolved` when none resolves. The one place that decides it, for `change new`, `change validate` and `changes list`.
19
+ * R3.1/R3.2/R3.5, for `changes list`: the base ref: `explicitBase` (checked with `isSafeRef` before git sees it: `invalid-input`),
20
+ * else the first default candidate that names a commit (no merge base is needed); `base-unresolved` when none does. The order of the
21
+ * candidates has one source, `baseCandidates` (git.ts), shared with `resolveRange`.
18
22
  */
19
23
  function resolveBaseRef(root, explicitBase) {
20
24
  if (explicitBase !== undefined && !(0, git_1.isSafeRef)(explicitBase))
21
- return failure('invalid-input', `--base "${(0, text_safety_1.esc)(explicitBase)}" is not a safe git ref`);
25
+ return unsafeBase(explicitBase);
22
26
  const resolved = (0, git_1.resolveBaseCommit)(root, explicitBase);
23
27
  return resolved === null ? failure('base-unresolved', 'could not resolve a base branch', REMEDY_BASE) : { ok: true, ...resolved };
24
28
  }
25
29
  /**
26
- * R3.1/R3.2/R3.5: pins HEAD, then resolves the base (explicit `--base`, else origin/HEAD, main, master) and its merge base with HEAD.
27
- * An explicit base is checked with `isSafeRef` before git sees it.
30
+ * R3.1/R3.2/R3.5, for `change new` and `change validate`: pins HEAD, then resolves the base and its merge base with HEAD, over the
31
+ * same `baseCandidates` (git.ts) as `resolveBaseRef` but also requiring a merge base. An explicit `--base` (checked with `isSafeRef`
32
+ * before git sees it) is the only candidate. Without it (R3.1 amended, Q7), the first default candidate that names a commit AND has
33
+ * a merge base with HEAD: a shallow remote ref that does not reach HEAD gives way to the next.
34
+ * The merge base is computed from the commit id the candidate resolved to, never from its name read a second time (Q9).
28
35
  */
29
36
  function resolveRange(root, explicitBase) {
30
37
  const head = (0, git_1.headSha)(root);
31
38
  if (head === null)
32
39
  return failure('git-failed', 'git could not read HEAD');
33
- const resolved = resolveBaseRef(root, explicitBase);
34
- if (!resolved.ok)
35
- return resolved;
36
- const mergeBaseSha = (0, git_1.mergeBase)(root, resolved.base);
37
- if (mergeBaseSha === null)
38
- return failure('base-unresolved', `no merge base between "${(0, text_safety_1.esc)(resolved.base)}" and HEAD`, REMEDY_BASE);
39
- return { ok: true, head, mergeBase: mergeBaseSha };
40
+ if (explicitBase !== undefined && !(0, git_1.isSafeRef)(explicitBase))
41
+ return unsafeBase(explicitBase);
42
+ let named = null;
43
+ for (const { ref, name } of (0, git_1.baseCandidates)(root, explicitBase)) {
44
+ const sha = (0, git_1.commitSha)(root, ref);
45
+ if (sha === null)
46
+ continue;
47
+ named ??= name;
48
+ const mergeBaseSha = (0, git_1.mergeBase)(root, sha);
49
+ if (mergeBaseSha !== null)
50
+ return { ok: true, head, mergeBase: mergeBaseSha };
51
+ }
52
+ if (named === null)
53
+ return failure('base-unresolved', 'could not resolve a base branch', REMEDY_BASE);
54
+ return failure('base-unresolved', `no merge base between "${(0, text_safety_1.esc)(named)}" and HEAD`, REMEDY_BASE);
40
55
  }
41
56
  /** `HEAD_MOVED` when HEAD is no longer `head` (or cannot be read), else null: a verdict about a moving target is never given. */
42
57
  function headMovedFailure(root, head) {
@@ -24,11 +24,71 @@ exports.matchFrontmatterBlock = matchFrontmatterBlock;
24
24
  exports.isBlockScalarHeader = isBlockScalarHeader;
25
25
  exports.findFrontmatterDescription = findFrontmatterDescription;
26
26
  exports.readFrontmatterDescription = readFrontmatterDescription;
27
+ /** Tope del contenido interno (entre `---` y el cerrador) antes de abandonar el
28
+ * escaneo (FH-3). Misma cifra que `FRONTMATTER_MAX` en process/model.ts. */
29
+ const FRONTMATTER_INNER_MAX = 65536;
30
+ /** ¿La linea es exactamente el cerrador `---` con espacios/tabs finales opcionales?
31
+ * `---x`, `---#comment` y similares NO cierran. */
32
+ function isFrontmatterCloserLine(line) {
33
+ if (!line.startsWith('---'))
34
+ return false;
35
+ for (let i = 3; i < line.length; i++) {
36
+ const c = line[i];
37
+ if (c !== ' ' && c !== '\t')
38
+ return false;
39
+ }
40
+ return true;
41
+ }
27
42
  /** Texto crudo del frontmatter (entre los delimitadores `---`), o null si el
28
- * bloque falta o esta mal formado. Tolera CRLF. */
43
+ * bloque falta o esta mal formado. Tolera CRLF. Cierra solo en una linea que
44
+ * sea exactamente `---` (con espacios/tabs finales opcionales). Si el contenido
45
+ * interno excederia `FRONTMATTER_INNER_MAX` antes de un cerrador valido, retorna
46
+ * null sin seguir acumulando lineas (FH-3). */
29
47
  function matchFrontmatterBlock(raw) {
30
- const fmMatch = raw.match(/^---\r?\n([\s\S]*?)\r?\n---/);
31
- return fmMatch ? fmMatch[1] : null;
48
+ if (!raw.startsWith('---'))
49
+ return null;
50
+ const afterOpen = raw[3] === '\r' && raw[4] === '\n' ? 5
51
+ : raw[3] === '\n' ? 4
52
+ : -1;
53
+ if (afterOpen < 0)
54
+ return null;
55
+ const body = raw.slice(afterOpen);
56
+ const lines = [];
57
+ let innerLen = 0;
58
+ let i = 0;
59
+ while (i <= body.length) {
60
+ let end = i;
61
+ while (end < body.length && body[end] !== '\n' && body[end] !== '\r')
62
+ end++;
63
+ const line = body.slice(i, end);
64
+ if (isFrontmatterCloserLine(line)) {
65
+ return lines.join('\n');
66
+ }
67
+ // join('\n') inserta un salto entre lineas ya acumuladas.
68
+ const nextLen = lines.length === 0 ? line.length : innerLen + 1 + line.length;
69
+ if (nextLen > FRONTMATTER_INNER_MAX)
70
+ return null;
71
+ lines.push(line);
72
+ innerLen = nextLen;
73
+ if (end >= body.length)
74
+ break;
75
+ if (body[end] === '\r' && body[end + 1] === '\n')
76
+ i = end + 2;
77
+ else
78
+ i = end + 1;
79
+ }
80
+ return null;
81
+ }
82
+ /** Quita un comentario YAML de escalar plano: solo `#` precedido de espacio o
83
+ * tab (no NBSP ni otros whitespace Unicode). Lineal en la longitud del valor. */
84
+ function stripPlainScalarComment(value) {
85
+ for (let i = 0; i < value.length - 1; i++) {
86
+ const c = value[i];
87
+ if ((c === ' ' || c === '\t') && value[i + 1] === '#') {
88
+ return value.slice(0, i).trim();
89
+ }
90
+ }
91
+ return value.trim();
32
92
  }
33
93
  /** Indicador de block scalar en la linea de la clave: estilo (`>` folded /
34
94
  * `|` literal) + chomping opcional (`-`/`+`) + indentacion explicita opcional
@@ -212,10 +272,11 @@ function findFrontmatterDescription(frontmatter) {
212
272
  }
213
273
  }
214
274
  }
215
- // Escalar plano: un `#` PRECEDIDO DE ESPACIO abre un comentario y no forma
216
- // parte del valor (un `#` pegado a texto, como en `C#`, si). Dentro de
275
+ // Escalar plano: un `#` PRECEDIDO DE ESPACIO O TAB abre un comentario y no
276
+ // forma parte del valor (un `#` pegado a texto, como en `C#`, si; NBSP
277
+ // antes de `#` tampoco abre comentario — alineado con js-yaml). Dentro de
217
278
  // comillas el `#` es literal, y esas ramas ya retornaron.
218
- return { value: value.replace(/\s+#.*$/, '').trim(), startLine, endLine };
279
+ return { value: stripPlainScalarComment(value), startLine, endLine };
219
280
  }
220
281
  /** Azucar para el caso comun: solo el valor resuelto de `description`. */
221
282
  function readFrontmatterDescription(frontmatter) {
@@ -24,8 +24,16 @@ const ALLOWED_FIELDS = ['awm', 'schema', 'name', 'status', 'entry_point', 'termi
24
24
  const DESCRIPTION_MAX = 1024;
25
25
  /** Tope del bloque de frontmatter antes de entregarlo al parser YAML: acota el
26
26
  * costo de parsear contenido no confiable de un registry. Por encima no se
27
- * parsea (para `description`, se rechaza con el mensaje del límite de 1024). */
27
+ * parsea (para `description`, se rechaza con el mensaje del límite de 1024).
28
+ * Para un bloque con discriminador `awm: process-model`, también corta
29
+ * `readPairs` (FH-5). */
28
30
  const FRONTMATTER_MAX = 65536;
31
+ /** Tope de problemas acumulados en un solo diagnóstico de proceso (FH-6). */
32
+ const MAX_PROCESS_PROBLEMS = 20;
33
+ /** Tope de caracteres de una clave desconocida/duplicada embebida en el diagnóstico (FH-6). */
34
+ const UNKNOWN_FIELD_KEY_MAX = 64;
35
+ /** Tope del valor crudo de `name`/`terminates_to` antes de `yaml.load` (FH-4). */
36
+ const YAML_SCALAR_RAW_MAX = 128;
29
37
  /** Lo que un runtime mostraría mal o usaría para engañar: controles C0 (salvo
30
38
  * tab), DEL, C1, separadores U+2028/U+2029, marcas LRM/RLM/ALM, overrides e
31
39
  * isolates bidi, y surrogates sueltos (regex en vez de `isWellFormed`: el lib
@@ -34,7 +42,50 @@ const FORBIDDEN_CHAR = /[\u0000-\u0008\u000A-\u001F\u007F-\u009F\u061C\u200E\u20
34
42
  /** Discriminador indentado: un modelo cuyas claves quedaron con sangría se
35
43
  * perdería en silencio como "no es un modelo". */
36
44
  const INDENTED_DISCRIMINATOR = /^awm[ \t]*:[ \t]*process-model$/;
45
+ /** Discriminador a nivel de línea (sin sangría) para el gate de tamaño FH-5. */
46
+ const PROCESS_MODEL_DISCRIMINATOR_LINE = /^awm[ \t]*:[ \t]*process-model[ \t]*$/m;
47
+ /** Discriminador en prefijo (columna 0 o indentado) cuando matchFrontmatterBlock
48
+ * devolvió null por exceso de tamaño (FH-5 QA amend). */
49
+ const PROCESS_MODEL_DISCRIMINATOR_PREFIX = /^[ \t]*awm[ \t]*:[ \t]*process-model[ \t]*$/m;
50
+ /** Token de ancla/alias YAML con forma `&name` / `*name` (FH-4). */
51
+ const YAML_ALIAS_TOKEN = /[&*][A-Za-z0-9_-]+/;
37
52
  const STATUSES = ['draft', 'active'];
53
+ /** Sentinel cuando `loadYamlScalar` no obtiene un mapeo plano con clave `v`. */
54
+ const YAML_SCALAR_MISS = Symbol('yaml-scalar-miss');
55
+ /** Quita un comentario de escalar plano (` #…` / `\t#…`) solo para el guard FH-4. */
56
+ function stripTrailingPlainCommentForGuard(raw) {
57
+ for (let i = 0; i < raw.length - 1; i++) {
58
+ const c = raw[i];
59
+ if ((c === ' ' || c === '\t') && raw[i + 1] === '#')
60
+ return raw.slice(0, i);
61
+ }
62
+ return raw;
63
+ }
64
+ /** Carga un valor suelto de `readPairs` como escalar YAML (`v: <raw>`). NUNCA lanza.
65
+ * Rechaza sin parsear si el raw (sin comentario final) es demasiado largo o trae
66
+ * un token de ancla/alias con forma `&name` / `*name`. */
67
+ function loadYamlScalar(raw) {
68
+ const forGuard = stripTrailingPlainCommentForGuard(raw);
69
+ if (forGuard.length > YAML_SCALAR_RAW_MAX || YAML_ALIAS_TOKEN.test(forGuard))
70
+ return YAML_SCALAR_MISS;
71
+ try {
72
+ const doc = js_yaml_1.default.load(`v: ${raw}`);
73
+ if (isPlainObject(doc) && Object.prototype.hasOwnProperty.call(doc, 'v'))
74
+ return doc.v;
75
+ }
76
+ catch { /* invalid YAML → miss */ }
77
+ return YAML_SCALAR_MISS;
78
+ }
79
+ /** Si `raw` es un escalar string YAML, lo devuelve; si no (null/bool/number/…), `null`. */
80
+ function yamlStringSlug(raw) {
81
+ const value = loadYamlScalar(raw);
82
+ return typeof value === 'string' ? value : null;
83
+ }
84
+ /** Clave truncada para diagnósticos `unknown field` / `duplicate field` (FH-6). */
85
+ function formatFieldKey(key) {
86
+ const shown = key.length > UNKNOWN_FIELD_KEY_MAX ? `${key.slice(0, UNKNOWN_FIELD_KEY_MAX)}…` : key;
87
+ return JSON.stringify(shown);
88
+ }
38
89
  /** El slug es lo único del modelo que puede viajar dentro de un id del Dashboard
39
90
  * (ver sanitize.ts). Por eso se valida acá y no en la frontera de render: si
40
91
  * admitiera rutas, markup o `=`, el id dejaría de ser seguro por construcción. */
@@ -42,13 +93,21 @@ exports.PROCESS_NAME = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/;
42
93
  const DATE = /^\d{4}-\d{2}-\d{2}$/;
43
94
  /** Caracteres de ancho cero: un valor hecho solo de ellos se ve vacío. */
44
95
  const ZERO_WIDTH = /[\u200B-\u200D\u2060\uFEFF]/g;
96
+ /** Empuja a `problems` mientras haya cupo (FH-6); cuenta el resto en `omitted`. */
97
+ function noteProblem(problems, omitted, msg) {
98
+ if (problems.length < MAX_PROCESS_PROBLEMS)
99
+ problems.push(msg);
100
+ else
101
+ omitted.n++;
102
+ }
45
103
  /** Lector de pares `clave: valor` de un frontmatter plano. El contrato no admite
46
104
  * anidamiento ni block scalars: cualquier línea que no sea `clave: valor` es un
47
105
  * rechazo, no una interpretación. (El VALOR de `description` sí pasa por el
48
- * parser YAML, más abajo.) */
106
+ * parser YAML, más abajo.) Deja de registrar problemas tras 20 (FH-6). */
49
107
  function readPairs(block) {
50
108
  const pairs = new Map();
51
109
  const problems = [];
110
+ const omitted = { n: 0 };
52
111
  const continuations = [];
53
112
  // Mismo criterio que YAML, no que JS: se parte en TODO salto de línea YAML
54
113
  // (un CR suelto también; si no, `a\rclave: x` sería un par para acá y dos
@@ -60,8 +119,9 @@ function readPairs(block) {
60
119
  // NEL/LS/PS son saltos de línea para YAML 1.1 (PyYAML) y no para js-yaml:
61
120
  // un comentario podría esconder una clave que solo un runtime ve. Se
62
121
  // reporta en CUALQUIER línea, comentarios incluidos, y solo por posición.
63
- if (/[\u0085\u2028\u2029]/.test(raw))
64
- problems.push(`frontmatter line ${index + 1} contains a YAML 1.1 line break (NEL, LS or PS)`);
122
+ if (/[\u0085\u2028\u2029]/.test(raw)) {
123
+ noteProblem(problems, omitted, `frontmatter line ${index + 1} contains a YAML 1.1 line break (NEL, LS or PS)`);
124
+ }
65
125
  if (line === '' || line.startsWith('#'))
66
126
  continue;
67
127
  // El contrato es un mapa PLANO: una línea que empieza con espacio o tab
@@ -78,23 +138,26 @@ function readPairs(block) {
78
138
  // contenido: una línea suelta suele ser la continuación de un valor
79
139
  // multilínea, y los diagnósticos no transportan valores de campos.
80
140
  if (!m) {
81
- problems.push(`frontmatter line ${index + 1} is not a "key: value" pair (multi-line values are not supported)`);
141
+ noteProblem(problems, omitted, `frontmatter line ${index + 1} is not a "key: value" pair (multi-line values are not supported)`);
82
142
  continue;
83
143
  }
84
144
  if (pairs.has(m[1])) {
85
- problems.push(`duplicate field ${JSON.stringify(m[1])}`);
145
+ noteProblem(problems, omitted, `duplicate field ${formatFieldKey(m[1])}`);
86
146
  continue;
87
147
  }
88
148
  pairs.set(m[1], m[2]);
89
149
  }
90
- return { pairs, problems, continuations };
150
+ return { pairs, problems, continuations, omittedProblems: omitted.n };
91
151
  }
92
152
  /** Carga el bloque de frontmatter COMPLETO con js-yaml (schema por defecto),
93
153
  * exactamente como lo lee un runtime. Por encima del tope no se parsea. NUNCA
94
- * lanza: un error de js-yaml es `invalid`. */
154
+ * lanza: un error de js-yaml es `invalid`. Rechaza sin `yaml.load` si el bloque
155
+ * contiene un token de ancla/alias con forma `&name` / `*name` (FH-4). */
95
156
  function loadBlock(block) {
96
157
  if (block.length > FRONTMATTER_MAX)
97
158
  return { kind: 'too-long' };
159
+ if (YAML_ALIAS_TOKEN.test(block))
160
+ return { kind: 'invalid' };
98
161
  try {
99
162
  return { kind: 'loaded', doc: js_yaml_1.default.load(block) };
100
163
  }
@@ -168,9 +231,28 @@ function parseProcessFrontmatter(source, file) {
168
231
  catch {
169
232
  return { diagnostics: [] };
170
233
  }
171
- if (block === null)
234
+ const sizeDiag = { diagnostics: [`${file}: invalid process model — frontmatter exceeds ${FRONTMATTER_MAX} characters`] };
235
+ if (block === null) {
236
+ // FH-5: match devolvió null (sin cerrador a tiempo / tope interno). Si el
237
+ // prefijo declara process-model (columna 0 o indentado) → tamaño; si no → silencio.
238
+ if (source.startsWith('---')) {
239
+ const prefix = source.slice(0, FRONTMATTER_MAX + 128);
240
+ if (PROCESS_MODEL_DISCRIMINATOR_PREFIX.test(prefix))
241
+ return sizeDiag;
242
+ }
172
243
  return { diagnostics: [] };
173
- const { pairs, problems, continuations } = readPairs(block);
244
+ }
245
+ // FH-5 defensa: bloque devuelto que aun así exceda el tope (no debería pasar
246
+ // tras FH-3). Con discriminador → tamaño; sin él → silencio.
247
+ if (block.length > FRONTMATTER_MAX) {
248
+ if (PROCESS_MODEL_DISCRIMINATOR_LINE.test(block) || PROCESS_MODEL_DISCRIMINATOR_PREFIX.test(block)) {
249
+ return sizeDiag;
250
+ }
251
+ return { diagnostics: [] };
252
+ }
253
+ const { pairs, problems, continuations, omittedProblems } = readPairs(block);
254
+ const omitted = { n: omittedProblems };
255
+ const note = (msg) => noteProblem(problems, omitted, msg);
174
256
  // Un modelo con las claves indentadas no tiene `awm` de nivel superior y se
175
257
  // perdería en silencio como "otro documento". Se nombra solo la línea.
176
258
  // Dispara con el prefiltro barato y, además, si el bloque NO carga como YAML
@@ -193,13 +275,13 @@ function parseProcessFrontmatter(source, file) {
193
275
  return { diagnostics: [] };
194
276
  for (const key of pairs.keys()) {
195
277
  if (!ALLOWED_FIELDS.includes(key)) {
196
- problems.push(`unknown field ${JSON.stringify(key)} — the contract admits only ${ALLOWED_FIELDS.join(', ')}`);
278
+ note(`unknown field ${formatFieldKey(key)} — the contract admits only ${ALLOWED_FIELDS.join(', ')}`);
197
279
  }
198
280
  }
199
281
  const rawSchema = pairs.get('schema');
200
282
  const schema = rawSchema !== undefined && /^\d+$/.test(rawSchema) ? Number(rawSchema) : Number.NaN;
201
283
  if (!Number.isInteger(schema) || schema < 1) {
202
- problems.push('"schema" must be a positive integer');
284
+ note('"schema" must be a positive integer');
203
285
  }
204
286
  else if (schema > types_1.KNOWN_PROCESS_SCHEMA) {
205
287
  // R1.4: detenerse e informar. Interpretarlo como el contrato anterior es
@@ -209,37 +291,58 @@ function parseProcessFrontmatter(source, file) {
209
291
  for (const field of ['name', 'status', 'entry_point', 'terminates_to', 'created', 'updated']) {
210
292
  const value = pairs.get(field);
211
293
  if (value === undefined || value === '')
212
- problems.push(`"${field}" is required`);
294
+ note(`"${field}" is required`);
295
+ }
296
+ const YAML_STRING_DIAG = 'must be a YAML string scalar (quote values YAML reads as null, boolean, or number)';
297
+ let name = '';
298
+ const rawName = pairs.get('name') ?? '';
299
+ if (rawName !== '') {
300
+ const resolvedName = yamlStringSlug(rawName);
301
+ if (resolvedName === null)
302
+ note(`"name" ${YAML_STRING_DIAG}`);
303
+ else if (!exports.PROCESS_NAME.test(resolvedName))
304
+ note('"name" must be a lowercase slug (a-z, 0-9, hyphen)');
305
+ else
306
+ name = resolvedName;
213
307
  }
214
- const name = pairs.get('name') ?? '';
215
- if (name !== '' && !exports.PROCESS_NAME.test(name))
216
- problems.push('"name" must be a lowercase slug (a-z, 0-9, hyphen)');
217
308
  const status = pairs.get('status') ?? '';
218
309
  if (status !== '' && !STATUSES.includes(status))
219
- problems.push(`"status" must be one of ${STATUSES.join(', ')}`);
310
+ note(`"status" must be one of ${STATUSES.join(', ')}`);
220
311
  const entryPointRaw = pairs.get('entry_point') ?? '';
221
312
  if (entryPointRaw !== '' && entryPointRaw !== 'true' && entryPointRaw !== 'false')
222
- problems.push('"entry_point" must be true or false');
223
- const terminatesTo = pairs.get('terminates_to') ?? '';
224
- if (terminatesTo !== '' && terminatesTo !== 'none' && !exports.PROCESS_NAME.test(terminatesTo)) {
225
- problems.push('"terminates_to" must be a lowercase slug or "none"');
313
+ note('"entry_point" must be true or false');
314
+ let terminatesTo = '';
315
+ const rawTerminatesTo = pairs.get('terminates_to') ?? '';
316
+ if (rawTerminatesTo !== '') {
317
+ const resolvedTerminatesTo = yamlStringSlug(rawTerminatesTo);
318
+ if (resolvedTerminatesTo === null)
319
+ note(`"terminates_to" ${YAML_STRING_DIAG}`);
320
+ else if (resolvedTerminatesTo !== 'none' && !exports.PROCESS_NAME.test(resolvedTerminatesTo)) {
321
+ note('"terminates_to" must be a lowercase slug or "none"');
322
+ }
323
+ else {
324
+ terminatesTo = resolvedTerminatesTo;
325
+ }
226
326
  }
227
327
  for (const field of ['created', 'updated']) {
228
328
  const value = pairs.get(field) ?? '';
229
329
  if (value !== '' && !DATE.test(value))
230
- problems.push(`"${field}" must be YYYY-MM-DD`);
330
+ note(`"${field}" must be YYYY-MM-DD`);
231
331
  }
232
332
  let description;
233
333
  const rawDescription = pairs.get('description');
234
334
  if (rawDescription !== undefined) {
235
335
  const checked = checkDescription(rawDescription, block, new Set(pairs.keys()));
236
336
  if ('problem' in checked)
237
- problems.push(checked.problem);
337
+ note(checked.problem);
238
338
  else
239
339
  description = checked.value;
240
340
  }
241
- if (problems.length > 0) {
242
- return { diagnostics: [`${file}: invalid process model — ${problems.join('; ')}`] };
341
+ if (problems.length > 0 || omitted.n > 0) {
342
+ const capped = omitted.n > 0
343
+ ? problems.concat([`${omitted.n} more problems`])
344
+ : problems;
345
+ return { diagnostics: [`${file}: invalid process model — ${capped.join('; ')}`] };
243
346
  }
244
347
  return {
245
348
  model: {
@@ -781,7 +781,7 @@ describe('awm change new: base and derivation diagnostics (R3.1, R3.2, R3.5)', (
781
781
  receiptForHead();
782
782
  expectFailure(run('ok', { base: 'nope' }), 'base-unresolved', 'pass --base <ref>');
783
783
  });
784
- test('no main, master or origin/HEAD is base-unresolved', () => {
784
+ test('no default base resolves: base-unresolved', () => {
785
785
  repo.git('branch', '-m', 'main', 'trunk');
786
786
  receiptForHead();
787
787
  expectFailure(run('ok'), 'base-unresolved', 'pass --base <ref>');
@@ -794,6 +794,29 @@ describe('awm change new: base and derivation diagnostics (R3.1, R3.2, R3.5)', (
794
794
  run('change-record', { base: 'mid' });
795
795
  expect(frontmatter(read())).toMatchObject({ type: 'fix', scope: 'core', semver: 'patch', modules: ['cli/src'] });
796
796
  });
797
+ test('a #228-shaped branch (plan commits first, then ci(release) commits) records type ci and scope release', () => {
798
+ repo.git('checkout', '-q', '-b', 'ci/shard', 'main');
799
+ repo.commit({ 'docs/plans/p.md': '1' }, 'docs(plans): plan it');
800
+ repo.commit({ '.github/workflows/ci.yml': '1' }, 'ci(release): shard');
801
+ repo.commit({ 'docs/plans/p.md': '2' }, 'docs(plans): amend A1');
802
+ repo.commit({ 'docs/plans/p.md': '3' }, 'docs(plans): amend A2');
803
+ repo.commit({ '.github/workflows/release.yml': '1' }, 'ci(release): gate it');
804
+ receiptForHead();
805
+ expect(run('change-record').code).toBe(0);
806
+ expect(frontmatter(read())).toMatchObject({ type: 'ci', scope: 'release', semver: 'none', breaking: false, modules: ['.github/workflows', 'docs/plans'] });
807
+ });
808
+ test('without origin/HEAD, a current origin/main is the base, not a stale local main', () => {
809
+ repo.git('checkout', '-q', '-b', 'upstream', 'main');
810
+ repo.commit({ 'other/u.ts': '1' }, 'feat(other)!: merged upstream');
811
+ repo.git('update-ref', 'refs/remotes/origin/main', 'upstream');
812
+ repo.git('checkout', '-q', '-b', 'feat/y', 'upstream');
813
+ repo.git('branch', '-D', 'upstream');
814
+ repo.commit({ 'cli/src/m.ts': '1' }, 'fix(core): mine');
815
+ receiptForHead();
816
+ expect(run('change-record').code).toBe(0);
817
+ // Against the stale local main, the upstream breaking feat would be in the range.
818
+ expect(frontmatter(read())).toMatchObject({ type: 'fix', scope: 'core', semver: 'patch', breaking: false, modules: ['cli/src'] });
819
+ });
797
820
  test('a branch with no commits beyond the base is no-commits', () => {
798
821
  repo.git('checkout', '-q', 'main');
799
822
  expectFailure(run('ok'), 'no-commits');
@@ -1096,6 +1119,10 @@ describe('registerChangeCommand', () => {
1096
1119
  const change = program().commands.find((c) => c.name() === 'change');
1097
1120
  const sub = change?.commands.find((c) => c.name() === 'new');
1098
1121
  expect(sub?.options.map((o) => o.long).sort()).toEqual(['--base', '--issue', '--model', '--plan', '--refresh', '--session']);
1122
+ for (const name of ['new', 'validate']) {
1123
+ const base = change?.commands.find((c) => c.name() === name)?.options.find((o) => o.long === '--base');
1124
+ expect(base?.description).toBe('base branch (default: origin/HEAD, origin/main, origin/master, main, master)');
1125
+ }
1099
1126
  });
1100
1127
  test('the change command describes both of its subcommands', () => {
1101
1128
  expect(program().commands.find((c) => c.name() === 'change')?.description()).toBe('create and validate the Change Record of the current branch');