owenloop 0.5.9 → 0.5.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/CHANGELOG.md +51 -0
  2. package/README.md +77 -37
  3. package/bin/owenloop.mjs +16 -1
  4. package/dist/packages/work/src/agent/loop.js +7 -0
  5. package/dist/packages/work/src/bundle/pull.d.ts +21 -0
  6. package/dist/packages/work/src/bundle/pull.js +118 -0
  7. package/dist/packages/work/src/exec/instructions.d.ts +4 -1
  8. package/dist/packages/work/src/exec/instructions.js +3 -0
  9. package/dist/packages/work/src/exec/loop.d.ts +1 -1
  10. package/dist/packages/work/src/exec/loop.js +92 -14
  11. package/dist/packages/work/src/harness/claude.js +16 -0
  12. package/dist/packages/work/src/harness/codex.d.ts +8 -0
  13. package/dist/packages/work/src/harness/codex.js +27 -1
  14. package/dist/packages/work/src/harness/contract.d.ts +9 -0
  15. package/dist/packages/work/src/roles/agent-run.js +38 -10
  16. package/dist/packages/work/src/roles/exec.js +25 -8
  17. package/dist/packages/work/src/shift/loop.js +118 -4
  18. package/dist/packages/work/src/shift/runtime.d.ts +3 -0
  19. package/dist/packages/work/src/shift/runtime.js +10 -1
  20. package/dist/packages/work/src/submit-proof.d.ts +11 -8
  21. package/dist/packages/work/src/submit-proof.js +11 -8
  22. package/dist/src/capabilities.d.ts +70 -6
  23. package/dist/src/capabilities.js +49 -6
  24. package/dist/src/capability-mapping-client.d.ts +29 -0
  25. package/dist/src/capability-mapping-client.js +160 -0
  26. package/dist/src/cli.d.ts +2 -2
  27. package/dist/src/cli.js +1200 -166
  28. package/dist/src/defs.d.ts +41 -1
  29. package/dist/src/defs.js +461 -92
  30. package/dist/src/engine.d.ts +108 -22
  31. package/dist/src/engine.js +573 -85
  32. package/dist/src/factory.js +5 -3
  33. package/dist/src/hub.d.ts +77 -0
  34. package/dist/src/hub.js +162 -0
  35. package/dist/src/implements.d.ts +37 -0
  36. package/dist/src/implements.js +790 -0
  37. package/dist/src/index.d.ts +12 -10
  38. package/dist/src/index.js +7 -6
  39. package/dist/src/mcp/serve.js +254 -45
  40. package/dist/src/mcp/server.d.ts +10 -7
  41. package/dist/src/mcp/server.js +53 -8
  42. package/dist/src/model.d.ts +46 -10
  43. package/dist/src/model.js +224 -78
  44. package/dist/src/order-resolver.js +1 -0
  45. package/dist/src/store/def-source.d.ts +19 -0
  46. package/dist/src/store/def-source.js +87 -17
  47. package/dist/src/store/gc-recovery.d.ts +46 -0
  48. package/dist/src/store/gc-recovery.js +258 -0
  49. package/dist/src/store/gc.d.ts +94 -0
  50. package/dist/src/store/gc.js +563 -0
  51. package/dist/src/store/index.d.ts +3 -1
  52. package/dist/src/store/index.js +2 -0
  53. package/dist/src/store/install.d.ts +34 -5
  54. package/dist/src/store/install.js +73 -11
  55. package/dist/src/store/pre-commit-verifier.js +42 -2
  56. package/dist/src/store/snapshot-guard.d.ts +18 -0
  57. package/dist/src/store/snapshot-guard.js +94 -0
  58. package/dist/src/store.d.ts +66 -4
  59. package/dist/src/store.js +333 -12
  60. package/dist/src/types.d.ts +97 -17
  61. package/dist/src/types.js +4 -0
  62. package/dist/src/util.js +4 -1
  63. package/docs/authoring.md +214 -9
  64. package/docs/bundles.md +19 -0
  65. package/docs/cli.md +270 -30
  66. package/docs/crypto.md +13 -7
  67. package/docs/design.md +107 -46
  68. package/docs/evals/mcp-charter-baseline.json +428 -0
  69. package/docs/mcp-charter-eval.md +124 -0
  70. package/docs/shift-logs.md +18 -0
  71. package/docs/wire-contracts.md +28 -7
  72. package/examples/workflows/compile-dev-playbook.yaml +1 -1
  73. package/examples/workflows/ship.yaml +28 -2
  74. package/package.json +2 -1
  75. package/plugins/claude-code/plugin/.claude-plugin/plugin.json +1 -1
  76. package/plugins/claude-code/plugin/.mcp.json +1 -1
  77. package/plugins/claude-code/plugin/skills/author/SKILL.md +22 -0
  78. package/plugins/claude-code/plugin/skills/ephemeral/SKILL.md +95 -0
  79. package/plugins/claude-code/plugin/skills/graduate/SKILL.md +156 -0
  80. package/plugins/claude-code/plugin/skills/plan/SKILL.md +236 -0
  81. package/plugins/codex/plugins/owenloop/.codex-plugin/plugin.json +1 -1
  82. package/plugins/codex/plugins/owenloop/.mcp.json +1 -1
  83. package/plugins/codex/plugins/owenloop/skills/author/SKILL.md +22 -0
  84. package/plugins/codex/plugins/owenloop/skills/ephemeral/SKILL.md +95 -0
  85. package/plugins/codex/plugins/owenloop/skills/graduate/SKILL.md +156 -0
  86. package/plugins/codex/plugins/owenloop/skills/plan/SKILL.md +236 -0
package/dist/src/defs.js CHANGED
@@ -29,6 +29,7 @@ import { assertValidSchema } from "./schema.js";
29
29
  // The separator lives with composition/matching (capabilities.ts); the parser
30
30
  // only enforces that an AUTHORED name never contains it.
31
31
  import { MODIFIER_SEPARATOR } from "./capabilities.js";
32
+ import { isCallStep } from "./types.js";
32
33
  /** Hand-maintained key allowlist for RawInput — kept next to the interface so
33
34
  * the two can't silently drift (§27 unknown-key rejection). */
34
35
  const RAW_INPUT_KEYS = ['name', 'producer', 'seedOwed', 'schema'];
@@ -44,12 +45,12 @@ const RAW_STEP_KEYS = [
44
45
  'name', 'consumes', 'produces', 'generates', 'invalidates', 'cadence',
45
46
  'maxRunsPerDay', 'parallel', 'maxAttempts', 'maxSchemaFailures', 'model',
46
47
  'workdir', 'workdirFrom', 'terminal', 'effect', 'on', 'idleAfter', 'body', 'bodyFile',
47
- 'calls', 'reapTtl', 'capabilities', 'maxLease', 'x', 'executor', 'command', 'spec',
48
+ 'calls', 'callsInterface', 'reapTtl', 'capabilities', 'maxLease', 'x', 'executor', 'command', 'spec',
48
49
  'escalation', 'onCancel',
49
50
  ];
50
51
  /** Keys valid on a calls: step entry — a DIFFERENT (smaller) shape than RawStep;
51
52
  * the `calls:` key is what routes an entry here instead of RAW_STEP_KEYS. */
52
- const RAW_CALLS_KEYS = ['name', 'calls', 'inputs', 'produces'];
53
+ const RAW_CALLS_KEYS = ['name', 'calls', 'callsInterface', 'inputs', 'produces'];
53
54
  /** Keys valid on an include: directive entry — the `include:` key is the
54
55
  * discriminator that routes an entry here instead of RAW_STEP_KEYS/RAW_CALLS_KEYS. */
55
56
  const RAW_INCLUDE_KEYS = ['include', 'as', 'inputs'];
@@ -478,6 +479,45 @@ function parseProduces(v, ctx, baseDir) {
478
479
  }
479
480
  export class DefError extends Error {
480
481
  }
482
+ /** Named, actionable refusal for a malformed authored interface call. */
483
+ export class InterfaceCallDefinitionError extends DefError {
484
+ name = 'InterfaceCallDefinitionError';
485
+ step;
486
+ interfaceName;
487
+ interfaceVersion;
488
+ detail;
489
+ constructor(step, claim, detail) {
490
+ const interfaceName = typeof claim?.name === 'string' && claim.name.trim() !== '' ? claim.name : undefined;
491
+ const interfaceVersion = typeof claim?.version === 'string' && claim.version.trim() !== '' ? claim.version : undefined;
492
+ const coordinate = interfaceName === undefined
493
+ ? ''
494
+ : ` for interface '${interfaceName}${interfaceVersion === undefined ? '' : `@${interfaceVersion}`}'`;
495
+ super(`definition loading refused for interface-call step '${step}'${coordinate}: ${detail}`);
496
+ this.step = step;
497
+ this.interfaceName = interfaceName;
498
+ this.interfaceVersion = interfaceVersion;
499
+ this.detail = detail;
500
+ }
501
+ }
502
+ function parseCallsInterface(value, step) {
503
+ const claim = typeof value === 'object' && value !== null && !Array.isArray(value)
504
+ ? value
505
+ : undefined;
506
+ if (claim === undefined) {
507
+ throw new InterfaceCallDefinitionError(step, undefined, "callsInterface must be a map with exactly 'name' and 'version'");
508
+ }
509
+ const unknown = Object.keys(claim).filter((key) => key !== 'name' && key !== 'version');
510
+ if (unknown.length > 0) {
511
+ throw new InterfaceCallDefinitionError(step, claim, `callsInterface has unknown field${unknown.length === 1 ? '' : 's'} ${unknown.map((key) => `'${key}'`).join(', ')}`);
512
+ }
513
+ if (typeof claim.name !== 'string' || claim.name.trim() === '') {
514
+ throw new InterfaceCallDefinitionError(step, claim, 'callsInterface.name must be a non-empty string');
515
+ }
516
+ if (typeof claim.version !== 'string' || claim.version.trim() === '') {
517
+ throw new InterfaceCallDefinitionError(step, claim, 'callsInterface.version must be a non-empty string');
518
+ }
519
+ return { name: claim.name, version: claim.version };
520
+ }
481
521
  // ---- Mode 1 include-directive helpers (M1-GRAMMAR) ---------------------------
482
522
  /** Duck-check: does this raw step-list entry look like an include directive? */
483
523
  function isIncludeDirective(v) {
@@ -485,7 +525,7 @@ function isIncludeDirective(v) {
485
525
  }
486
526
  /** Duck-check: does this raw step-list entry look like a calls: directive (M2-GRAMMAR)? */
487
527
  function isCallsDirective(v) {
488
- return typeof v === 'object' && v !== null && 'calls' in v && !('include' in v);
528
+ return typeof v === 'object' && v !== null && ('calls' in v || 'callsInterface' in v) && !('include' in v);
489
529
  }
490
530
  /** Parse and validate a raw include directive (M1-GRAMMAR pre-checks). */
491
531
  function parseIncludeDirective(raw, i, parentName) {
@@ -915,13 +955,23 @@ export function expandIncludes(def, resolve, stack) {
915
955
  stepIdx++;
916
956
  }
917
957
  }
918
- return {
958
+ const expanded = {
919
959
  ...def,
920
960
  steps: resultSteps,
921
961
  inputs: resultInputs,
922
962
  outputs: resultOutputs.length > 0 ? resultOutputs : def.outputs,
923
963
  _includes: undefined,
924
964
  };
965
+ // CAS store roots are live loader provenance, deliberately non-enumerable so
966
+ // they never enter hashes or persisted snapshots. The spread above therefore
967
+ // cannot carry them. Preserve the original descriptor explicitly so an
968
+ // include-expanded CAS definition still coordinates its snapshot writes with
969
+ // bundle GC.
970
+ const storeRoots = Object.getOwnPropertyDescriptor(def, 'bundleStoreRoots');
971
+ if (storeRoots !== undefined) {
972
+ Object.defineProperty(expanded, 'bundleStoreRoots', storeRoots);
973
+ }
974
+ return expanded;
925
975
  }
926
976
  /** Build a validated `WorkflowDef` from a parsed YAML object (or throw DefError). */
927
977
  export function parseDef(raw, source, baseDir) {
@@ -994,12 +1044,24 @@ function synthesizeJudgeSteps(producerStepName, pat, producerConsumeStems, produ
994
1044
  });
995
1045
  }
996
1046
  function buildStep(rl, i, baseDir) {
997
- // M2-GRAMMAR: if this entry carries a 'calls' key, parse it as a calls: step (Mode 2).
998
- if (typeof rl.calls !== 'undefined') {
1047
+ // M2-GRAMMAR: either discriminator routes through the same restricted
1048
+ // machine-call shape. A definition may never author both.
1049
+ if (typeof rl.calls !== 'undefined' || typeof rl.callsInterface !== 'undefined') {
999
1050
  const rawCalls = rl;
1000
1051
  assertNoUnknownKeys(rawCalls, RAW_CALLS_KEYS, `steps[${i}] (calls: step)`);
1001
1052
  const name = asString(rawCalls.name, `steps[${i}].name`);
1002
- const callsTarget = asString(rawCalls.calls, `step '${name}'.calls`);
1053
+ const hasCalls = rawCalls.calls !== undefined;
1054
+ const hasInterface = rawCalls.callsInterface !== undefined;
1055
+ const claimRecord = typeof rawCalls.callsInterface === 'object' && rawCalls.callsInterface !== null
1056
+ && !Array.isArray(rawCalls.callsInterface)
1057
+ ? rawCalls.callsInterface
1058
+ : undefined;
1059
+ if (hasCalls && hasInterface) {
1060
+ throw new InterfaceCallDefinitionError(name, claimRecord, 'calls and callsInterface are mutually exclusive; author exactly one call discriminator');
1061
+ }
1062
+ const callsTarget = hasCalls ? asString(rawCalls.calls, `step '${name}'.calls`) : undefined;
1063
+ const callsInterface = hasInterface ? parseCallsInterface(rawCalls.callsInterface, name) : undefined;
1064
+ const callLabel = callsInterface === undefined ? 'calls:' : 'callsInterface';
1003
1065
  // parse inputs: optional mapping of child input name -> parent artifact name
1004
1066
  const callsInputs = {};
1005
1067
  if (rawCalls.inputs !== undefined) {
@@ -1016,15 +1078,16 @@ function buildStep(rl, i, baseDir) {
1016
1078
  const { patterns: producesPatterns, groups: callsGroups } = parseProduces(rawCalls.produces, `step '${name}'.produces`, baseDir);
1017
1079
  for (const p of producesPatterns) {
1018
1080
  if (p.judges && p.judges.length > 0) {
1019
- throw new DefError(`step '${name}': judges: is not supported on a calls: step's produces (produce '${p.stem}')`);
1081
+ throw new DefError(`step '${name}': judges: is not supported on a ${callLabel} step's produces (produce '${p.stem}')`);
1020
1082
  }
1021
1083
  }
1022
1084
  if (callsGroups.length > 0) {
1023
- throw new DefError(`step '${name}': group: is not supported on a calls: step's produces (group '${callsGroups[0].group}')`);
1085
+ throw new DefError(`step '${name}': group: is not supported on a ${callLabel} step's produces (group '${callsGroups[0].group}')`);
1024
1086
  }
1025
1087
  const step = {
1026
1088
  name,
1027
- calls: callsTarget,
1089
+ ...(callsTarget === undefined ? {} : { calls: callsTarget }),
1090
+ ...(callsInterface === undefined ? {} : { callsInterface }),
1028
1091
  callsInputs,
1029
1092
  consumes: [], // calls: steps have no consumes in StepDef (eligibility is engine-managed)
1030
1093
  produces: producesPatterns,
@@ -1468,24 +1531,28 @@ export function validateDef(def) {
1468
1531
  // because validateDef is a pure per-def function with no resolver. Those checks live in loadDefs
1469
1532
  // Phase 2, analogous to how expandIncludes validates include input-key mappings.
1470
1533
  for (const l of def.steps) {
1471
- if (!l.calls)
1534
+ if (!isCallStep(l))
1472
1535
  continue;
1536
+ if (l.calls !== undefined && l.callsInterface !== undefined) {
1537
+ errors.push(`call step '${l.name}' declares both calls and callsInterface; the discriminators are mutually exclusive`);
1538
+ }
1539
+ const callLabel = l.callsInterface === undefined ? 'calls:' : 'callsInterface';
1473
1540
  // (a) calls: step must produce exactly one output (one child, one outcome path — v1)
1474
1541
  if (l.produces.length !== 1) {
1475
- errors.push(`calls: step '${l.name}' must produce exactly one output (got ${l.produces.length})`);
1542
+ errors.push(`${callLabel} step '${l.name}' must produce exactly one output (got ${l.produces.length})`);
1476
1543
  }
1477
1544
  // A calls: outcome is published by the composition machinery rather than
1478
1545
  // accepted through green(), so it has no transactional bind write path.
1479
1546
  // Refuse it at definition load instead of allowing a silently stale route.
1480
1547
  for (const produce of l.produces) {
1481
1548
  if (produce.bind !== undefined) {
1482
- errors.push(`calls: step '${l.name}' produce '${produce.raw}' declares bind, which is not supported on calls: outcomes`);
1549
+ errors.push(`${callLabel} step '${l.name}' produce '${produce.raw}' declares bind, which is not supported on ${callLabel} outcomes`);
1483
1550
  }
1484
1551
  }
1485
1552
  // (b) callsInputs VALUES must be real parent artifacts (inputs or step-produced stems)
1486
1553
  for (const [, parentArtifact] of Object.entries(l.callsInputs ?? {})) {
1487
1554
  if (!producerOf.has(parentArtifact)) {
1488
- errors.push(`calls: step '${l.name}' maps to parent artifact '${parentArtifact}' which is not produced by any step or input`);
1555
+ errors.push(`${callLabel} step '${l.name}' maps to parent artifact '${parentArtifact}' which is not produced by any step or input`);
1489
1556
  }
1490
1557
  }
1491
1558
  }
@@ -1893,6 +1960,150 @@ function unroutedCapabilityWarnings(def) {
1893
1960
  }
1894
1961
  return warnings;
1895
1962
  }
1963
+ /** Whether a discovery-convention value is a YAML mapping. */
1964
+ function isDiscoveryMap(value) {
1965
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
1966
+ }
1967
+ /**
1968
+ * Return advisory issues for Owenloop's optional x.discovery convention.
1969
+ *
1970
+ * This deliberately does not assign a severity. W2.1 can promote these same
1971
+ * deterministic issues for library definitions without duplicating validation.
1972
+ * The parser and engine continue to treat all extension contents as opaque.
1973
+ */
1974
+ function discoveryIssues(def) {
1975
+ const issues = [];
1976
+ const discovery = def.x?.discovery;
1977
+ if (discovery === undefined)
1978
+ return ['x.discovery: missing required discovery metadata'];
1979
+ if (!isDiscoveryMap(discovery))
1980
+ return ['x.discovery: expected a map'];
1981
+ const requiredString = (value, path) => {
1982
+ if (typeof value !== 'string' || value.trim() === '') {
1983
+ issues.push(path + ': expected a non-empty string');
1984
+ return undefined;
1985
+ }
1986
+ return value;
1987
+ };
1988
+ const requiredPhraseList = (value, path) => {
1989
+ if (!Array.isArray(value) || value.length === 0) {
1990
+ issues.push(path + ': expected a non-empty array of non-empty strings');
1991
+ return;
1992
+ }
1993
+ for (const [index, item] of value.entries())
1994
+ requiredString(item, path + '[' + index + ']');
1995
+ };
1996
+ /**
1997
+ * Validate a mapping in the order its fields were authored. Required
1998
+ * fields absent from the mapping follow in the convention's fixed order,
1999
+ * making both kinds of diagnostic deterministic.
2000
+ */
2001
+ const visitMapFields = (value, allowed, path, visitKnownField) => {
2002
+ const allowedSet = new Set(allowed);
2003
+ const present = new Set();
2004
+ for (const key of Object.keys(value)) {
2005
+ if (!allowedSet.has(key)) {
2006
+ issues.push(path + '.' + key + ': unknown field');
2007
+ continue;
2008
+ }
2009
+ present.add(key);
2010
+ visitKnownField(key, value[key]);
2011
+ }
2012
+ for (const key of allowed)
2013
+ if (!present.has(key))
2014
+ visitKnownField(key, undefined);
2015
+ };
2016
+ const inputs = new Map(def.inputs.map((input) => [input.name, { schema: input.schema }]));
2017
+ const outputs = new Map((def.outputs ?? []).map((name) => {
2018
+ const artifact = def.steps.flatMap((step) => [...step.produces, ...(step.generates ?? [])])
2019
+ .find((produce) => produce.stem === name);
2020
+ return [name, { schema: artifact?.schema }];
2021
+ }));
2022
+ const validateInterfaceEntries = (value, path, declared) => {
2023
+ const fieldPath = 'x.discovery.interface.' + path;
2024
+ const singular = path === 'inputs' ? 'input' : 'output';
2025
+ if (!Array.isArray(value)) {
2026
+ issues.push(fieldPath + ': expected an array');
2027
+ return;
2028
+ }
2029
+ const seen = new Set();
2030
+ for (const [index, entry] of value.entries()) {
2031
+ const entryPath = fieldPath + '[' + index + ']';
2032
+ if (!isDiscoveryMap(entry)) {
2033
+ issues.push(entryPath + ': expected a map');
2034
+ continue;
2035
+ }
2036
+ visitMapFields(entry, ['name', 'summary', 'schemaRef'], entryPath, (key, fieldValue) => {
2037
+ switch (key) {
2038
+ case 'name': {
2039
+ const name = requiredString(fieldValue, entryPath + '.name');
2040
+ if (name === undefined)
2041
+ break;
2042
+ // Record every non-blank name before declaration lookup. This
2043
+ // preserves both useful findings for repeated unknown names.
2044
+ if (seen.has(name)) {
2045
+ issues.push(entryPath + '.name: duplicate workflow ' + singular + " '" + name + "'");
2046
+ }
2047
+ else {
2048
+ seen.add(name);
2049
+ }
2050
+ const artifact = declared.get(name);
2051
+ if (artifact === undefined) {
2052
+ issues.push(entryPath + '.name: unknown workflow ' + singular + " '" + name + "'");
2053
+ }
2054
+ else if (artifact.schema === undefined) {
2055
+ issues.push(entryPath + '.schemaRef: workflow ' + singular + " '" + name + "' has no schema");
2056
+ }
2057
+ break;
2058
+ }
2059
+ case 'summary':
2060
+ requiredString(fieldValue, entryPath + '.summary');
2061
+ break;
2062
+ case 'schemaRef': {
2063
+ const schemaRef = requiredString(fieldValue, entryPath + '.schemaRef');
2064
+ if (schemaRef !== undefined && !schemaRef.startsWith('#/')) {
2065
+ issues.push(entryPath + '.schemaRef: expected a local JSON pointer starting with \'#/\'');
2066
+ }
2067
+ break;
2068
+ }
2069
+ }
2070
+ });
2071
+ }
2072
+ for (const name of declared.keys()) {
2073
+ if (!seen.has(name))
2074
+ issues.push(fieldPath + ': missing workflow ' + singular + " '" + name + "'");
2075
+ }
2076
+ };
2077
+ const validateInterface = (value) => {
2078
+ if (!isDiscoveryMap(value)) {
2079
+ issues.push('x.discovery.interface: expected a map');
2080
+ return;
2081
+ }
2082
+ visitMapFields(value, ['inputs', 'outputs'], 'x.discovery.interface', (key, fieldValue) => {
2083
+ if (key === 'inputs')
2084
+ validateInterfaceEntries(fieldValue, 'inputs', inputs);
2085
+ else
2086
+ validateInterfaceEntries(fieldValue, 'outputs', outputs);
2087
+ });
2088
+ };
2089
+ visitMapFields(discovery, ['description', 'whenToUse', 'notFor', 'interface'], 'x.discovery', (key, value) => {
2090
+ switch (key) {
2091
+ case 'description':
2092
+ requiredString(value, 'x.discovery.description');
2093
+ break;
2094
+ case 'whenToUse':
2095
+ requiredPhraseList(value, 'x.discovery.whenToUse');
2096
+ break;
2097
+ case 'notFor':
2098
+ requiredPhraseList(value, 'x.discovery.notFor');
2099
+ break;
2100
+ case 'interface':
2101
+ validateInterface(value);
2102
+ break;
2103
+ }
2104
+ });
2105
+ return issues;
2106
+ }
1896
2107
  /**
1897
2108
  * Static lint over a workflow definition. Returns both the hard errors from
1898
2109
  * `validateDef` (which `parseDef` / `loadDefFile` would throw on) and
@@ -1906,7 +2117,7 @@ function unroutedCapabilityWarnings(def) {
1906
2117
  export function lintDef(def) {
1907
2118
  const errors = validateDef(def);
1908
2119
  const warnings = errors.length === 0
1909
- ? [...deadEndWarnings(def), ...danglingReduceSuffixWarnings(def), ...unroutedCapabilityWarnings(def)]
2120
+ ? [...deadEndWarnings(def), ...danglingReduceSuffixWarnings(def), ...unroutedCapabilityWarnings(def), ...discoveryIssues(def)]
1910
2121
  : [];
1911
2122
  return { errors, warnings };
1912
2123
  }
@@ -1982,49 +2193,195 @@ export function resolveCallsTarget(defs, target, from) {
1982
2193
  const key = resolveCallsTargetKey(defs, target, from);
1983
2194
  return key === undefined ? undefined : defs.get(key);
1984
2195
  }
1985
- // ---- M2-CYCLE: cross-def calls-cycle detection --------------------------------
2196
+ function buildCallsGraph(defs) {
2197
+ const keys = [...defs.keys()];
2198
+ const edges = new Map();
2199
+ for (const [key, def] of defs) {
2200
+ // WS-6: graph nodes are RESOLVED map keys, not bare calls text. Two bundles
2201
+ // may both export `build` without being fused into one graph node.
2202
+ const children = new Set();
2203
+ for (const step of def.steps) {
2204
+ if (step.calls === undefined)
2205
+ continue;
2206
+ const child = resolveCallsTargetKey(defs, step.calls, def);
2207
+ if (child !== undefined)
2208
+ children.add(child);
2209
+ }
2210
+ edges.set(key, [...children]);
2211
+ }
2212
+ return {
2213
+ keys,
2214
+ order: new Map(keys.map((key, index) => [key, index])),
2215
+ edges,
2216
+ };
2217
+ }
1986
2218
  /**
1987
- * Walk the calls: edges in a flat def map and throw a DefError if any cycle exists.
1988
- * This is the Mode 2 analogue of the Mode 1 include-cycle guard in expandIncludes.
1989
- * Note: include: and calls: are DIFFERENT edge kinds — they are checked separately.
1990
- *
1991
- * Called from loadDefs Phase 2 after all defs are expanded and per-def validated.
2219
+ * Preserve the original tri-color DFS exactly for strict loading. It stops at
2220
+ * the first back edge, so finalizeDefs remains O(V+E) and retains its stable
2221
+ * first-cycle message and traversal precedence.
1992
2222
  */
1993
- function detectCallsCycles(defs) {
2223
+ function findFirstCallsCycle(graph) {
1994
2224
  const WHITE = 0, GREY = 1, BLACK = 2;
1995
- const color = new Map([...defs.keys()].map((k) => [k, WHITE]));
2225
+ const color = new Map(graph.keys.map((key) => [key, WHITE]));
1996
2226
  const stack = [];
1997
- // WS-6: the walk must key on RESOLVED identity, not on the bare `calls:` text.
1998
- // Two installed bundles may each export a workflow named `build`; keying the
1999
- // walk by that bare text would fuse them into one node and report a cycle that
2000
- // does not exist. `resolveCallsTarget` maps (edge text, calling def) to the
2001
- // exact map key the engine will spawn, so each bundle's `build` stays its own
2002
- // node under its own qualified key.
2003
- const visit = (name) => {
2004
- color.set(name, GREY);
2005
- stack.push(name);
2006
- const def = defs.get(name);
2007
- // Unique calls: edges from this def (multiple steps might call the same child)
2008
- const callsEdges = new Set((def?.steps ?? []).filter((l) => l.calls).map((l) => l.calls));
2009
- for (const edge of callsEdges) {
2010
- const child = def === undefined ? undefined : resolveCallsTargetKey(defs, edge, def);
2011
- if (child === undefined)
2012
- continue; // missing-def error is reported separately in loadDefs
2013
- const c = color.get(child) ?? WHITE;
2014
- if (c === GREY) {
2015
- const from = stack.indexOf(child);
2016
- throw new DefError(`calls cycle: ${[...stack.slice(from), child].join(' -> ')}`);
2227
+ const visit = (key) => {
2228
+ color.set(key, GREY);
2229
+ stack.push(key);
2230
+ for (const child of graph.edges.get(key) ?? []) {
2231
+ const state = color.get(child) ?? WHITE;
2232
+ if (state === GREY)
2233
+ return [...stack.slice(stack.indexOf(child)), child];
2234
+ if (state === WHITE) {
2235
+ const found = visit(child);
2236
+ if (found !== undefined)
2237
+ return found;
2017
2238
  }
2018
- if (c === WHITE)
2019
- visit(child);
2020
2239
  }
2021
2240
  stack.pop();
2022
- color.set(name, BLACK);
2241
+ color.set(key, BLACK);
2242
+ return undefined;
2243
+ };
2244
+ for (const key of graph.keys) {
2245
+ if ((color.get(key) ?? WHITE) !== WHITE)
2246
+ continue;
2247
+ const found = visit(key);
2248
+ if (found !== undefined)
2249
+ return found;
2250
+ }
2251
+ return undefined;
2252
+ }
2253
+ function cycleFingerprint(cycle) {
2254
+ const members = cycle.slice(0, -1);
2255
+ return members
2256
+ .map((_, index) => [...members.slice(index), ...members.slice(0, index)].join('\u0000'))
2257
+ .sort()[0] ?? '';
2258
+ }
2259
+ function canonicalizeCycle(cycle, order) {
2260
+ const members = cycle.slice(0, -1);
2261
+ let first = 0;
2262
+ for (let index = 1; index < members.length; index++) {
2263
+ if ((order.get(members[index]) ?? Number.MAX_SAFE_INTEGER) < (order.get(members[first]) ?? Number.MAX_SAFE_INTEGER)) {
2264
+ first = index;
2265
+ }
2266
+ }
2267
+ const rotated = [...members.slice(first), ...members.slice(0, first)];
2268
+ return [...rotated, rotated[0]];
2269
+ }
2270
+ /** Return each cyclic SCC, indexed by every member, using deterministic Tarjan traversal. */
2271
+ function cyclicComponentsByMember(graph) {
2272
+ let nextIndex = 0;
2273
+ const index = new Map();
2274
+ const lowlink = new Map();
2275
+ const stack = [];
2276
+ const onStack = new Set();
2277
+ const byMember = new Map();
2278
+ const visit = (key) => {
2279
+ index.set(key, nextIndex);
2280
+ lowlink.set(key, nextIndex);
2281
+ nextIndex++;
2282
+ stack.push(key);
2283
+ onStack.add(key);
2284
+ for (const child of graph.edges.get(key) ?? []) {
2285
+ if (!index.has(child)) {
2286
+ visit(child);
2287
+ lowlink.set(key, Math.min(lowlink.get(key), lowlink.get(child)));
2288
+ }
2289
+ else if (onStack.has(child)) {
2290
+ lowlink.set(key, Math.min(lowlink.get(key), index.get(child)));
2291
+ }
2292
+ }
2293
+ if (lowlink.get(key) !== index.get(key))
2294
+ return;
2295
+ const members = [];
2296
+ while (stack.length > 0) {
2297
+ const member = stack.pop();
2298
+ onStack.delete(member);
2299
+ members.push(member);
2300
+ if (member === key)
2301
+ break;
2302
+ }
2303
+ const cyclic = members.length > 1 || (graph.edges.get(key) ?? []).includes(key);
2304
+ if (!cyclic)
2305
+ return;
2306
+ const component = new Set(members);
2307
+ for (const member of members)
2308
+ byMember.set(member, component);
2023
2309
  };
2024
- for (const name of defs.keys()) {
2025
- if ((color.get(name) ?? WHITE) === WHITE)
2026
- visit(name);
2310
+ for (const key of graph.keys) {
2311
+ if (!index.has(key))
2312
+ visit(key);
2313
+ }
2314
+ return byMember;
2315
+ }
2316
+ /** Find one deterministic simple cycle through member inside its cyclic SCC. */
2317
+ function cycleThroughMember(member, component, graph) {
2318
+ const pathBack = (key, target, path, seen) => {
2319
+ for (const child of graph.edges.get(key) ?? []) {
2320
+ if (!component.has(child))
2321
+ continue;
2322
+ if (child === target)
2323
+ return [...path, child];
2324
+ if (seen.has(child))
2325
+ continue;
2326
+ seen.add(child);
2327
+ const found = pathBack(child, target, [...path, child], seen);
2328
+ if (found !== undefined)
2329
+ return found;
2330
+ }
2331
+ return undefined;
2332
+ };
2333
+ for (const child of graph.edges.get(member) ?? []) {
2334
+ if (!component.has(child))
2335
+ continue;
2336
+ if (child === member)
2337
+ return [member, member];
2338
+ const found = pathBack(child, member, [child], new Set([member, child]));
2339
+ if (found !== undefined)
2340
+ return [member, ...found];
2027
2341
  }
2342
+ return undefined;
2343
+ }
2344
+ /**
2345
+ * Report calls cycles in a flat def map. This is the Mode 2 analogue of the
2346
+ * Mode 1 include-cycle guard in expandIncludes; the two edge kinds stay
2347
+ * deliberately separate. Findings use resolved map identity, not bare call
2348
+ * text, so CAS bundle siblings cannot be accidentally fused. The first finding
2349
+ * is strict loading's legacy DFS witness. Further findings add at most one
2350
+ * deterministic witness for each still-unattributed cyclic member, keeping
2351
+ * authoring attribution polynomial and every finding's members consistent with
2352
+ * its displayed path without enumerating exponentially many simple cycles.
2353
+ */
2354
+ export function reportCallsCycles(defs) {
2355
+ const graph = buildCallsGraph(defs);
2356
+ const first = findFirstCallsCycle(graph);
2357
+ if (first === undefined)
2358
+ return [];
2359
+ const cycles = [first];
2360
+ const seen = new Set([cycleFingerprint(first)]);
2361
+ const attributed = new Set(first.slice(0, -1));
2362
+ const components = cyclicComponentsByMember(graph);
2363
+ for (const member of graph.keys) {
2364
+ if (attributed.has(member))
2365
+ continue;
2366
+ const component = components.get(member);
2367
+ if (component === undefined)
2368
+ continue;
2369
+ const witness = cycleThroughMember(member, component, graph);
2370
+ if (witness === undefined)
2371
+ continue; // unreachable for a member of a cyclic SCC
2372
+ const cycle = canonicalizeCycle(witness, graph.order);
2373
+ for (const cycleMember of cycle.slice(0, -1))
2374
+ attributed.add(cycleMember);
2375
+ const fingerprint = cycleFingerprint(cycle);
2376
+ if (seen.has(fingerprint))
2377
+ continue;
2378
+ seen.add(fingerprint);
2379
+ cycles.push(cycle);
2380
+ }
2381
+ return cycles.map((cycle) => ({
2382
+ message: `calls cycle: ${cycle.join(' -> ')}`,
2383
+ members: cycle.slice(0, -1),
2384
+ }));
2028
2385
  }
2029
2386
  // ---- filesystem loading ------------------------------------------------------
2030
2387
  /** Load and validate a single workflow definition from a YAML file. */
@@ -2103,51 +2460,59 @@ export function loadDefsUnfinalized(dir) {
2103
2460
  }
2104
2461
  return raw;
2105
2462
  }
2463
+ /**
2464
+ * Return every direct cross-definition `calls:` error for one expanded
2465
+ * definition. Strict loading uses the first result to retain its historical
2466
+ * throw behavior; tolerant authoring commands can present the complete list.
2467
+ */
2468
+ export function validateCallsEdges(def, defs, options = {}) {
2469
+ const errors = [];
2470
+ for (const step of def.steps) {
2471
+ if (!step.calls)
2472
+ continue;
2473
+ const childDef = resolveCallsTarget(defs, step.calls, def);
2474
+ if (!childDef) {
2475
+ if (options.allowUnresolvedCalls !== true
2476
+ && options.allowUnresolvedVersionedCalls?.has(step.calls) !== true) {
2477
+ errors.push(`calls names workflow '${step.calls}' which does not exist`);
2478
+ }
2479
+ continue;
2480
+ }
2481
+ const childInputNames = new Set(childDef.inputs.map((input) => input.name));
2482
+ for (const key of Object.keys(step.callsInputs ?? {})) {
2483
+ if (!childInputNames.has(key)) {
2484
+ errors.push(`calls '${step.name}' maps input '${key}' which workflow '${step.calls}' does not declare`);
2485
+ }
2486
+ }
2487
+ const childOutputs = childDef.outputs ?? [];
2488
+ if (childOutputs.length === 0) {
2489
+ errors.push(`calls names workflow '${step.calls}' which declares no outputs:`);
2490
+ }
2491
+ if (childOutputs.length > 1) {
2492
+ errors.push(`calls names workflow '${step.calls}' which declares ${childOutputs.length} outputs:, calls: v1 requires exactly one`);
2493
+ }
2494
+ }
2495
+ return errors;
2496
+ }
2106
2497
  export function finalizeDefs(raw, options = {}) {
2107
2498
  const out = new Map();
2108
2499
  const resolver = (name) => raw.get(name);
2109
2500
  for (const [name, def] of raw) {
2110
2501
  const expanded = expandIncludes(def, resolver);
2111
- // M2-VALIDATE cross-def: target-def existence + child input-key validity.
2112
- // These cannot live in validateDef (pure per-def, no resolver) — same split as expandIncludes.
2113
- //
2114
- // WS-6: `calls:` targets resolve through `resolveCallsTarget` (scope-aware),
2115
- // NOT through the plain `resolver` used for `include:` expansion above.
2116
- // `include:` is a DIFFERENT edge kind and is deliberately left on the flat
2117
- // lookup — this workstream is `calls:`-only.
2118
- for (const l of expanded.steps) {
2119
- if (!l.calls)
2120
- continue;
2121
- const childDef = resolveCallsTarget(raw, l.calls, expanded);
2122
- if (!childDef) {
2123
- if (options.allowUnresolvedCalls === true
2124
- || options.allowUnresolvedVersionedCalls?.has(l.calls) === true)
2125
- continue;
2126
- throw new DefError(`calls names workflow '${l.calls}' which does not exist`);
2127
- }
2128
- const childInputNames = new Set(childDef.inputs.map((i) => i.name));
2129
- for (const k of Object.keys(l.callsInputs ?? {})) {
2130
- if (!childInputNames.has(k)) {
2131
- throw new DefError(`calls '${l.name}' maps input '${k}' which workflow '${l.calls}' does not declare`);
2132
- }
2133
- }
2134
- // M2B-OUTCOME v1: the called workflow must declare exactly one output.
2135
- const childOutputs = childDef.outputs ?? [];
2136
- if (childOutputs.length === 0) {
2137
- throw new DefError(`calls names workflow '${l.calls}' which declares no outputs:`);
2138
- }
2139
- if (childOutputs.length > 1) {
2140
- throw new DefError(`calls names workflow '${l.calls}' which declares ${childOutputs.length} outputs:, calls: v1 requires exactly one`);
2141
- }
2142
- }
2502
+ const callsErrors = validateCallsEdges(expanded, raw, options);
2503
+ if (callsErrors.length > 0)
2504
+ throw new DefError(callsErrors[0]);
2143
2505
  const errors = validateDef(expanded);
2144
2506
  if (errors.length) {
2145
2507
  throw new DefError(`invalid workflow '${name}' (${def.dir ?? 'unknown'}):\n - ${errors.join('\n - ')}`);
2146
2508
  }
2147
2509
  out.set(name, expanded);
2148
2510
  }
2149
- // M2-CYCLE: detect calls: cycles over the full expanded def map (after all per-def checks pass).
2150
- detectCallsCycles(out);
2511
+ // Preserve strict loading's first, stable cycle error after all per-def checks
2512
+ // without paying the wider authoring reporter's per-member attribution cost.
2513
+ const cycle = findFirstCallsCycle(buildCallsGraph(out));
2514
+ if (cycle !== undefined)
2515
+ throw new DefError(`calls cycle: ${cycle.join(' -> ')}`);
2151
2516
  return out;
2152
2517
  }
2153
2518
  /**
@@ -2159,7 +2524,7 @@ export function finalizeDefs(raw, options = {}) {
2159
2524
  * Two-phase: Phase 1 collects all defs. Phase 2 expands includes best-effort
2160
2525
  * (silently skips expansion failures so the lint caller sees un-expanded defs).
2161
2526
  */
2162
- export function loadDefsRaw(dir, failures) {
2527
+ export function scanDefsRaw(dir, failures) {
2163
2528
  // Phase 1: build all defs, skipping (and recording) malformed files.
2164
2529
  const raw = new Map();
2165
2530
  const tryAdd = (file) => {
@@ -2189,7 +2554,10 @@ export function loadDefsRaw(dir, failures) {
2189
2554
  tryAdd(full);
2190
2555
  }
2191
2556
  }
2192
- // Phase 2: expand includes best-effort; on failure keep the un-expanded def.
2557
+ return raw;
2558
+ }
2559
+ /** Best-effort include expansion for a complete, already-merged raw map. */
2560
+ export function expandDefsRaw(raw) {
2193
2561
  const out = new Map();
2194
2562
  const resolver = (name) => raw.get(name);
2195
2563
  for (const [name, def] of raw) {
@@ -2202,12 +2570,13 @@ export function loadDefsRaw(dir, failures) {
2202
2570
  out.set(name, def);
2203
2571
  }
2204
2572
  }
2205
- // M2-CYCLE: best-effort calls-cycle check so lint can surface cycle errors.
2206
- try {
2207
- detectCallsCycles(out);
2208
- }
2209
- catch {
2210
- // Cycle errors are surfaced via validateDef in the lint caller; swallow here.
2211
- }
2212
2573
  return out;
2213
2574
  }
2575
+ /**
2576
+ * Compatibility wrapper for tolerant single-directory loading. Raw loading
2577
+ * builds and expands includes best-effort; callers explicitly invoke shared
2578
+ * calls validation and cycle reporting against the complete definition map.
2579
+ */
2580
+ export function loadDefsRaw(dir, failures) {
2581
+ return expandDefsRaw(scanDefsRaw(dir, failures));
2582
+ }