@cleocode/contracts 2026.5.111 → 2026.5.113

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 (118) hide show
  1. package/dist/__tests__/cli-meta-suggested-next.test.d.ts +21 -0
  2. package/dist/__tests__/cli-meta-suggested-next.test.d.ts.map +1 -0
  3. package/dist/__tests__/cli-meta-suggested-next.test.js +70 -0
  4. package/dist/__tests__/cli-meta-suggested-next.test.js.map +1 -0
  5. package/dist/__tests__/evidence-atom-schema.test.d.ts +16 -0
  6. package/dist/__tests__/evidence-atom-schema.test.d.ts.map +1 -0
  7. package/dist/__tests__/evidence-atom-schema.test.js +394 -0
  8. package/dist/__tests__/evidence-atom-schema.test.js.map +1 -0
  9. package/dist/config/__tests__/manifest.test.d.ts +13 -0
  10. package/dist/config/__tests__/manifest.test.d.ts.map +1 -0
  11. package/dist/config/__tests__/manifest.test.js +143 -0
  12. package/dist/config/__tests__/manifest.test.js.map +1 -0
  13. package/dist/config/manifest.d.ts +158 -0
  14. package/dist/config/manifest.d.ts.map +1 -0
  15. package/dist/config/manifest.js +123 -0
  16. package/dist/config/manifest.js.map +1 -0
  17. package/dist/docs/__tests__/provenance.test.d.ts +14 -0
  18. package/dist/docs/__tests__/provenance.test.d.ts.map +1 -0
  19. package/dist/docs/__tests__/provenance.test.js +579 -0
  20. package/dist/docs/__tests__/provenance.test.js.map +1 -0
  21. package/dist/docs/provenance.d.ts +731 -0
  22. package/dist/docs/provenance.d.ts.map +1 -0
  23. package/dist/docs/provenance.js +258 -0
  24. package/dist/docs/provenance.js.map +1 -0
  25. package/dist/docs-taxonomy.d.ts +24 -0
  26. package/dist/docs-taxonomy.d.ts.map +1 -1
  27. package/dist/docs-taxonomy.js +27 -0
  28. package/dist/docs-taxonomy.js.map +1 -1
  29. package/dist/doctor.d.ts +101 -0
  30. package/dist/doctor.d.ts.map +1 -1
  31. package/dist/errors.d.ts +4 -0
  32. package/dist/errors.d.ts.map +1 -1
  33. package/dist/errors.js +4 -0
  34. package/dist/errors.js.map +1 -1
  35. package/dist/evidence-atom-schema.d.ts +407 -0
  36. package/dist/evidence-atom-schema.d.ts.map +1 -0
  37. package/dist/evidence-atom-schema.js +505 -0
  38. package/dist/evidence-atom-schema.js.map +1 -0
  39. package/dist/exit-codes.d.ts +37 -0
  40. package/dist/exit-codes.d.ts.map +1 -1
  41. package/dist/exit-codes.js +37 -0
  42. package/dist/exit-codes.js.map +1 -1
  43. package/dist/index.d.ts +13 -2
  44. package/dist/index.d.ts.map +1 -1
  45. package/dist/index.js +8 -1
  46. package/dist/index.js.map +1 -1
  47. package/dist/invariants/__tests__/adr-056-release.test.d.ts +16 -0
  48. package/dist/invariants/__tests__/adr-056-release.test.d.ts.map +1 -0
  49. package/dist/invariants/__tests__/adr-056-release.test.js +88 -0
  50. package/dist/invariants/__tests__/adr-056-release.test.js.map +1 -0
  51. package/dist/invariants/__tests__/adr-070-orchestration.test.d.ts +22 -0
  52. package/dist/invariants/__tests__/adr-070-orchestration.test.d.ts.map +1 -0
  53. package/dist/invariants/__tests__/adr-070-orchestration.test.js +151 -0
  54. package/dist/invariants/__tests__/adr-070-orchestration.test.js.map +1 -0
  55. package/dist/invariants/__tests__/registry.test.d.ts +14 -0
  56. package/dist/invariants/__tests__/registry.test.d.ts.map +1 -0
  57. package/dist/invariants/__tests__/registry.test.js +113 -0
  58. package/dist/invariants/__tests__/registry.test.js.map +1 -0
  59. package/dist/invariants/adr-056-release.d.ts +42 -0
  60. package/dist/invariants/adr-056-release.d.ts.map +1 -0
  61. package/dist/invariants/adr-056-release.js +143 -0
  62. package/dist/invariants/adr-056-release.js.map +1 -0
  63. package/dist/invariants/adr-070-orchestration.d.ts +73 -0
  64. package/dist/invariants/adr-070-orchestration.d.ts.map +1 -0
  65. package/dist/invariants/adr-070-orchestration.js +290 -0
  66. package/dist/invariants/adr-070-orchestration.js.map +1 -0
  67. package/dist/invariants/adr-073-saga.d.ts +32 -0
  68. package/dist/invariants/adr-073-saga.d.ts.map +1 -0
  69. package/dist/invariants/adr-073-saga.js +155 -0
  70. package/dist/invariants/adr-073-saga.js.map +1 -0
  71. package/dist/invariants/index.d.ts +162 -0
  72. package/dist/invariants/index.d.ts.map +1 -0
  73. package/dist/invariants/index.js +118 -0
  74. package/dist/invariants/index.js.map +1 -0
  75. package/dist/operations/__tests__/input-contract.test.d.ts +20 -0
  76. package/dist/operations/__tests__/input-contract.test.d.ts.map +1 -0
  77. package/dist/operations/__tests__/input-contract.test.js +158 -0
  78. package/dist/operations/__tests__/input-contract.test.js.map +1 -0
  79. package/dist/operations/docs.d.ts +16 -0
  80. package/dist/operations/docs.d.ts.map +1 -1
  81. package/dist/operations/input-contract.d.ts +267 -0
  82. package/dist/operations/input-contract.d.ts.map +1 -0
  83. package/dist/operations/input-contract.js +29 -0
  84. package/dist/operations/input-contract.js.map +1 -0
  85. package/dist/templates/__tests__/manifest.test.d.ts +18 -0
  86. package/dist/templates/__tests__/manifest.test.d.ts.map +1 -0
  87. package/dist/templates/__tests__/manifest.test.js +123 -0
  88. package/dist/templates/__tests__/manifest.test.js.map +1 -0
  89. package/dist/templates/manifest.d.ts +186 -0
  90. package/dist/templates/manifest.d.ts.map +1 -0
  91. package/dist/templates/manifest.js +165 -0
  92. package/dist/templates/manifest.js.map +1 -0
  93. package/package.json +2 -2
  94. package/src/__tests__/cli-meta-suggested-next.test.ts +76 -0
  95. package/src/__tests__/evidence-atom-schema.test.ts +499 -0
  96. package/src/config/__tests__/manifest.test.ts +176 -0
  97. package/src/config/manifest.ts +218 -0
  98. package/src/docs/__tests__/__snapshots__/provenance.test.ts.snap +252 -0
  99. package/src/docs/__tests__/provenance.test.ts +648 -0
  100. package/src/docs/provenance.ts +601 -0
  101. package/src/docs-taxonomy.ts +55 -0
  102. package/src/doctor.ts +111 -0
  103. package/src/errors.ts +4 -0
  104. package/src/evidence-atom-schema.ts +628 -0
  105. package/src/exit-codes.ts +39 -0
  106. package/src/index.ts +129 -0
  107. package/src/invariants/__tests__/adr-056-release.test.ts +102 -0
  108. package/src/invariants/__tests__/adr-070-orchestration.test.ts +186 -0
  109. package/src/invariants/__tests__/registry.test.ts +136 -0
  110. package/src/invariants/adr-056-release.ts +154 -0
  111. package/src/invariants/adr-070-orchestration.ts +317 -0
  112. package/src/invariants/adr-073-saga.ts +167 -0
  113. package/src/invariants/index.ts +222 -0
  114. package/src/operations/__tests__/input-contract.test.ts +188 -0
  115. package/src/operations/docs.ts +16 -0
  116. package/src/operations/input-contract.ts +301 -0
  117. package/src/templates/__tests__/manifest.test.ts +140 -0
  118. package/src/templates/manifest.ts +208 -0
@@ -0,0 +1,301 @@
1
+ /**
2
+ * OperationInputContract — schema-first input contract for CLEO operations.
3
+ *
4
+ * This module is the SINGLE SOURCE OF TRUTH for the schema-first input
5
+ * validation surface that powers the `mutate(operation, input)` DX
6
+ * (Saga T9855 / E7). Every CLEO operation that accepts structured input
7
+ * MUST be describable as an {@link OperationInputContract}: a JSON Schema
8
+ * draft-07 document, a stable operation identifier, and at least one
9
+ * worked example payload.
10
+ *
11
+ * Validators consume an {@link OperationInputContract} and produce a
12
+ * {@link ValidationResult} discriminated union — either the typed value
13
+ * (`ok: true`) or an array of {@link ValidationError} entries with
14
+ * actionable, JSON-Pointer-anchored remediation hints (`ok: false`).
15
+ *
16
+ * ZERO runtime dependencies: `contracts` is a leaf package. JSON Schema
17
+ * documents are modeled as the loose alias {@link JsonSchema} so this
18
+ * module does not pull in a JSON Schema typings package.
19
+ *
20
+ * @packageDocumentation
21
+ * @module @cleocode/contracts/operations/input-contract
22
+ *
23
+ * @see {@link https://json-schema.org/draft-07/schema}
24
+ *
25
+ * @epic T9855
26
+ * @task T9914
27
+ */
28
+
29
+ // ---------------------------------------------------------------------------
30
+ // JSON Schema
31
+ // ---------------------------------------------------------------------------
32
+
33
+ /**
34
+ * Loose alias for a JSON Schema draft-07 document.
35
+ *
36
+ * Intentionally typed as `Record<string, unknown>` to keep the contracts
37
+ * package free of any JSON Schema typings runtime/type dependency. The
38
+ * actual draft-07 shape is enforced by the validator implementation
39
+ * (T9915) at the point of use, not by the type system here.
40
+ *
41
+ * @example
42
+ * ```ts
43
+ * const titleSchema: JsonSchema = {
44
+ * type: 'object',
45
+ * required: ['title'],
46
+ * properties: {
47
+ * title: { type: 'string', minLength: 1 },
48
+ * },
49
+ * };
50
+ * ```
51
+ */
52
+ export type JsonSchema = Record<string, unknown>;
53
+
54
+ // ---------------------------------------------------------------------------
55
+ // Examples
56
+ // ---------------------------------------------------------------------------
57
+
58
+ /**
59
+ * A single worked example payload for an {@link OperationInputContract}.
60
+ *
61
+ * Examples are MANDATORY (the contract requires at least one) — they
62
+ * double as documentation for human readers AND as conformance fixtures
63
+ * for the validator self-test that ships with every CLEO release.
64
+ *
65
+ * @typeParam T - The validated, typed input shape produced by the contract.
66
+ *
67
+ * @example
68
+ * ```ts
69
+ * const example: OperationInputExample<{ title: string }> = {
70
+ * name: 'minimal',
71
+ * value: { title: 'Ship saga T9855' },
72
+ * description: 'Smallest valid input — title is the only required field.',
73
+ * };
74
+ * ```
75
+ */
76
+ export interface OperationInputExample<T> {
77
+ /**
78
+ * Short, human-readable identifier for the example. Conventionally
79
+ * kebab-case (`'minimal'`, `'with-all-fields'`, `'edge-empty-array'`).
80
+ */
81
+ name: string;
82
+
83
+ /**
84
+ * A concrete value that validates successfully against the contract's
85
+ * {@link OperationInputContract.schema | schema}. Strongly typed via
86
+ * the `T` generic so example tables stay in sync with the operation
87
+ * payload shape at compile time.
88
+ */
89
+ value: T;
90
+
91
+ /**
92
+ * Optional prose explaining why this example matters — what edge case
93
+ * it covers, what default it exercises, etc. Surfaced in generated docs.
94
+ */
95
+ description?: string;
96
+ }
97
+
98
+ // ---------------------------------------------------------------------------
99
+ // OperationInputContract
100
+ // ---------------------------------------------------------------------------
101
+
102
+ /**
103
+ * Schema-first input contract for a single CLEO operation.
104
+ *
105
+ * Pairs a stable operation identifier with the JSON Schema draft-07
106
+ * document that describes the operation's accepted input shape, plus a
107
+ * non-empty (by convention) catalogue of worked examples. The validator
108
+ * implementation (T9915) ingests an {@link OperationInputContract} and a
109
+ * raw payload, returning a {@link ValidationResult}.
110
+ *
111
+ * Together with the {@link OperationInputContractRegistry}, this type is
112
+ * the foundation of the schema-first `mutate(operation, input)` DX
113
+ * surface (Saga T9855 / E7).
114
+ *
115
+ * @typeParam T - The validated, typed input shape produced when the
116
+ * raw payload passes validation. The generic propagates through
117
+ * {@link ValidationResult} so callers receive a strongly-typed `value`
118
+ * in the success branch.
119
+ *
120
+ * @example
121
+ * ```ts
122
+ * interface CreateTaskInput {
123
+ * title: string;
124
+ * acceptance: string;
125
+ * }
126
+ *
127
+ * const createTaskContract: OperationInputContract<CreateTaskInput> = {
128
+ * operation: 'tasks.create',
129
+ * schema: {
130
+ * type: 'object',
131
+ * required: ['title', 'acceptance'],
132
+ * properties: {
133
+ * title: { type: 'string', minLength: 1, maxLength: 200 },
134
+ * acceptance: { type: 'string', minLength: 1 },
135
+ * },
136
+ * additionalProperties: false,
137
+ * },
138
+ * examples: [
139
+ * {
140
+ * name: 'minimal',
141
+ * value: { title: 'Ship E7', acceptance: 'PR merged' },
142
+ * },
143
+ * ],
144
+ * };
145
+ * ```
146
+ */
147
+ export interface OperationInputContract<T> {
148
+ /**
149
+ * Stable, fully-qualified operation identifier in
150
+ * `<domain>.<verb>` form (e.g. `'tasks.create'`, `'docs.publish'`).
151
+ * Used as the registry key in {@link OperationInputContractRegistry}.
152
+ */
153
+ operation: string;
154
+
155
+ /**
156
+ * JSON Schema draft-07 document describing the accepted input shape.
157
+ * The validator MUST treat absent properties as not-present (it does
158
+ * NOT inject `default` values) so callers can distinguish "user
159
+ * omitted" from "user supplied default".
160
+ */
161
+ schema: JsonSchema;
162
+
163
+ /**
164
+ * Catalogue of worked example payloads. Conventionally non-empty so
165
+ * generated docs always have at least one runnable sample. Each
166
+ * example's {@link OperationInputExample.value | value} is statically
167
+ * typed to the contract's `T` parameter.
168
+ */
169
+ examples: ReadonlyArray<OperationInputExample<T>>;
170
+ }
171
+
172
+ // ---------------------------------------------------------------------------
173
+ // ValidationError
174
+ // ---------------------------------------------------------------------------
175
+
176
+ /**
177
+ * A single validation failure produced by the input validator.
178
+ *
179
+ * Every field is REQUIRED — there are no optional remediation hints.
180
+ * This shape is the wire format the `mutate` DX surface returns to
181
+ * callers, so it MUST be stable, machine-parseable, AND human-readable.
182
+ *
183
+ * @example
184
+ * ```ts
185
+ * const err: ValidationError = {
186
+ * path: '/title',
187
+ * expected: 'string with minLength 1',
188
+ * received: 'empty string',
189
+ * fix: 'Provide a non-empty title (1-200 chars).',
190
+ * errorCode: 'E_INPUT_MIN_LENGTH',
191
+ * schemaPath: '#/properties/title/minLength',
192
+ * };
193
+ * ```
194
+ */
195
+ export interface ValidationError {
196
+ /**
197
+ * RFC 6901 JSON Pointer to the failing input location, anchored at
198
+ * the root of the payload (e.g. `'/title'`, `'/owners/0/email'`).
199
+ * An empty string `''` denotes the root document itself.
200
+ */
201
+ path: string;
202
+
203
+ /**
204
+ * Human-readable description of what the validator expected at
205
+ * {@link ValidationError.path | path} (e.g. `'string'`,
206
+ * `'integer >= 0'`, `'one of: pending | active | done'`).
207
+ */
208
+ expected: string;
209
+
210
+ /**
211
+ * Human-readable description of what was actually received at
212
+ * {@link ValidationError.path | path}. NEVER includes the raw value
213
+ * itself — describes type/cardinality only — so logs of errors do
214
+ * not accidentally leak user payloads.
215
+ */
216
+ received: string;
217
+
218
+ /**
219
+ * Actionable, imperative remediation hint targeted at the caller
220
+ * (e.g. `'Provide a non-empty title (1-200 chars).'`). Surfaced
221
+ * directly in CLI output and validator return envelopes.
222
+ */
223
+ fix: string;
224
+
225
+ /**
226
+ * Stable, screaming-snake-case error code (e.g.
227
+ * `'E_INPUT_MIN_LENGTH'`, `'E_INPUT_REQUIRED'`). Stable across
228
+ * releases so callers can branch on it programmatically.
229
+ */
230
+ errorCode: string;
231
+
232
+ /**
233
+ * RFC 6901 JSON Pointer into the contract's
234
+ * {@link OperationInputContract.schema | schema} that produced the
235
+ * failure (e.g. `'#/properties/title/minLength'`). Lets tooling jump
236
+ * straight to the offending schema clause.
237
+ */
238
+ schemaPath: string;
239
+ }
240
+
241
+ // ---------------------------------------------------------------------------
242
+ // ValidationResult
243
+ // ---------------------------------------------------------------------------
244
+
245
+ /**
246
+ * Discriminated union returned by the input validator.
247
+ *
248
+ * Narrows on the `ok` boolean: when `ok === true`, the strongly-typed
249
+ * `value` is present; when `ok === false`, a non-empty `errors` array
250
+ * lists every failure (validators are encouraged to surface ALL errors
251
+ * in one pass, not bail on the first).
252
+ *
253
+ * @typeParam T - The validated, typed input shape produced on success.
254
+ *
255
+ * @example
256
+ * ```ts
257
+ * function handle(result: ValidationResult<{ title: string }>) {
258
+ * if (result.ok) {
259
+ * // result.value is { title: string }
260
+ * return createTask(result.value);
261
+ * }
262
+ * // result.errors is ValidationError[]
263
+ * for (const e of result.errors) {
264
+ * console.error(`${e.path}: ${e.fix}`);
265
+ * }
266
+ * }
267
+ * ```
268
+ */
269
+ export type ValidationResult<T> =
270
+ | { readonly ok: true; readonly value: T }
271
+ | { readonly ok: false; readonly errors: ValidationError[] };
272
+
273
+ // ---------------------------------------------------------------------------
274
+ // Registry
275
+ // ---------------------------------------------------------------------------
276
+
277
+ /**
278
+ * Registry of every {@link OperationInputContract} known to the CLEO
279
+ * runtime, keyed by the contract's `operation` identifier (e.g.
280
+ * `'tasks.create'`).
281
+ *
282
+ * The value type uses `unknown` for the contract's generic so registry
283
+ * lookups stay assignable across operations with different input
284
+ * shapes. Callers that need the concrete `T` MUST narrow via an
285
+ * operation-specific accessor — direct `registry[op]` reads are
286
+ * intentionally not type-narrowed by operation name.
287
+ *
288
+ * @example
289
+ * ```ts
290
+ * const registry: OperationInputContractRegistry = {
291
+ * 'tasks.create': createTaskContract,
292
+ * 'docs.publish': publishDocsContract,
293
+ * };
294
+ *
295
+ * const contract = registry['tasks.create'];
296
+ * if (contract) {
297
+ * // validate(contract, payload) → ValidationResult<unknown>
298
+ * }
299
+ * ```
300
+ */
301
+ export type OperationInputContractRegistry = Record<string, OperationInputContract<unknown>>;
@@ -0,0 +1,140 @@
1
+ /**
2
+ * Contract tests for the TemplateManifest schema.
3
+ *
4
+ * Asserts:
5
+ *
6
+ * 1. A valid entry for every {@link TemplateKind} parses successfully.
7
+ * 2. An entry with an unknown `kind` is rejected.
8
+ * 3. An entry missing `installPath` is rejected.
9
+ * 4. The {@link PlaceholderSpec} `source` field is exhaustively typed —
10
+ * every member of {@link PLACEHOLDER_SOURCES} parses, and a bogus
11
+ * source value is rejected.
12
+ *
13
+ * @task T9875
14
+ * @epic T9874
15
+ * @saga T9855
16
+ */
17
+
18
+ import { describe, expect, it } from 'vitest';
19
+ import {
20
+ PLACEHOLDER_SOURCES,
21
+ PlaceholderSpecSchema,
22
+ TEMPLATE_KINDS,
23
+ type TemplateKind,
24
+ type TemplateManifestEntry,
25
+ TemplateManifestEntrySchema,
26
+ } from '../manifest.js';
27
+
28
+ /**
29
+ * Build a valid baseline entry parameterized by `kind` so each
30
+ * assertion below stays minimal.
31
+ */
32
+ function baseEntry(kind: TemplateKind): TemplateManifestEntry {
33
+ return {
34
+ id: `sample-${kind}`,
35
+ kind,
36
+ sourcePath: `packages/core/templates/${kind}s/sample.tmpl`,
37
+ installPath: `.cleo/${kind}s/sample`,
38
+ substitution: 'regex-tmpl',
39
+ placeholders: [
40
+ {
41
+ name: 'NODE_VERSION',
42
+ source: 'project-context',
43
+ sourcePath: 'engines.node',
44
+ defaultValue: 24,
45
+ },
46
+ ],
47
+ updateStrategy: 'overwrite-on-bump',
48
+ };
49
+ }
50
+
51
+ describe('TemplateManifestEntrySchema (T9875)', () => {
52
+ it('accepts a valid entry for every TemplateKind', () => {
53
+ for (const kind of TEMPLATE_KINDS) {
54
+ const entry = baseEntry(kind);
55
+ const parsed = TemplateManifestEntrySchema.parse(entry);
56
+ expect(parsed.kind, `kind '${kind}' must round-trip`).toBe(kind);
57
+ expect(parsed.installPath).toBe(entry.installPath);
58
+ }
59
+ });
60
+
61
+ it('rejects an entry with an unknown kind', () => {
62
+ const bogus = {
63
+ ...baseEntry('workflow'),
64
+ kind: 'not-a-real-kind',
65
+ };
66
+ const result = TemplateManifestEntrySchema.safeParse(bogus);
67
+ expect(result.success).toBe(false);
68
+ });
69
+
70
+ it('rejects an entry missing installPath', () => {
71
+ const { installPath: _drop, ...rest } = baseEntry('config');
72
+ const result = TemplateManifestEntrySchema.safeParse(rest);
73
+ expect(result.success).toBe(false);
74
+ });
75
+
76
+ it('accepts an entry whose placeholders array is empty', () => {
77
+ const entry = { ...baseEntry('doc'), placeholders: [] };
78
+ const result = TemplateManifestEntrySchema.safeParse(entry);
79
+ expect(result.success).toBe(true);
80
+ });
81
+
82
+ it('accepts a defaultValue of every supported literal type and null', () => {
83
+ const types = [
84
+ { defaultValue: 'string-default' },
85
+ { defaultValue: 42 },
86
+ { defaultValue: true },
87
+ { defaultValue: null },
88
+ {},
89
+ ] as const;
90
+ for (const extra of types) {
91
+ const result = PlaceholderSpecSchema.safeParse({
92
+ name: 'X',
93
+ source: 'literal',
94
+ sourcePath: 'X',
95
+ ...extra,
96
+ });
97
+ expect(result.success, `defaultValue case ${JSON.stringify(extra)} must parse`).toBe(true);
98
+ }
99
+ });
100
+ });
101
+
102
+ describe('PlaceholderSpecSchema source enum (T9875)', () => {
103
+ it('exhaustively accepts every member of PLACEHOLDER_SOURCES', () => {
104
+ for (const source of PLACEHOLDER_SOURCES) {
105
+ const result = PlaceholderSpecSchema.safeParse({
106
+ name: 'PLACEHOLDER',
107
+ source,
108
+ sourcePath: 'some.path',
109
+ });
110
+ expect(result.success, `source '${source}' must parse`).toBe(true);
111
+ }
112
+ });
113
+
114
+ it('rejects an unknown source value', () => {
115
+ const result = PlaceholderSpecSchema.safeParse({
116
+ name: 'PLACEHOLDER',
117
+ source: 'not-a-source',
118
+ sourcePath: 'some.path',
119
+ });
120
+ expect(result.success).toBe(false);
121
+ });
122
+
123
+ it('rejects an empty name', () => {
124
+ const result = PlaceholderSpecSchema.safeParse({
125
+ name: '',
126
+ source: 'project-context',
127
+ sourcePath: 'some.path',
128
+ });
129
+ expect(result.success).toBe(false);
130
+ });
131
+
132
+ it('rejects an empty sourcePath', () => {
133
+ const result = PlaceholderSpecSchema.safeParse({
134
+ name: 'X',
135
+ source: 'project-context',
136
+ sourcePath: '',
137
+ });
138
+ expect(result.success).toBe(false);
139
+ });
140
+ });
@@ -0,0 +1,208 @@
1
+ /**
2
+ * TemplateManifest contract — SSoT for every template CLEO ships, installs,
3
+ * or rewrites during `cleo init` / `cleo upgrade` / `cleo scaffold-*`.
4
+ *
5
+ * A {@link TemplateManifestEntry} declares one template file: where its
6
+ * source lives in the monorepo, where it installs into a consumer project,
7
+ * how its placeholders are substituted, which placeholders it accepts, and
8
+ * how it MUST be reconciled when the shipped version moves ahead of the
9
+ * deployed copy.
10
+ *
11
+ * This contract is the leaf type. The CORE-side template registry
12
+ * (T9877) consumes it; the CLI verbs (`cleo init --workflows`,
13
+ * `cleo upgrade`, the scaffold sweeper) read the manifest at runtime to
14
+ * decide what to write, what to skip, and what to diff-prompt the user on.
15
+ *
16
+ * @example minimal workflow template entry
17
+ * ```ts
18
+ * import { TemplateManifestEntrySchema, type TemplateManifestEntry } from '@cleocode/contracts';
19
+ *
20
+ * const entry: TemplateManifestEntry = TemplateManifestEntrySchema.parse({
21
+ * id: 'ci.yml',
22
+ * kind: 'workflow',
23
+ * sourcePath: 'packages/core/templates/workflows/ci.yml.tmpl',
24
+ * installPath: '.github/workflows/ci.yml',
25
+ * substitution: 'regex-tmpl',
26
+ * placeholders: [
27
+ * {
28
+ * name: 'NODE_VERSION',
29
+ * source: 'project-context',
30
+ * sourcePath: 'engines.node',
31
+ * defaultValue: 24,
32
+ * },
33
+ * ],
34
+ * updateStrategy: 'overwrite-on-bump',
35
+ * });
36
+ * ```
37
+ *
38
+ * @task T9875
39
+ * @epic T9874
40
+ * @saga T9855
41
+ * @see ADR-076 (canonical doc routing — same boundary discipline applies here)
42
+ */
43
+
44
+ import { z } from 'zod';
45
+
46
+ // ─── TemplateKind ─────────────────────────────────────────────────────────────
47
+
48
+ /**
49
+ * Allowed categories of template the manifest can describe.
50
+ *
51
+ * - `workflow` — GitHub Actions / CI workflow files.
52
+ * - `config` — Configuration files (e.g. `.editorconfig`, `tsconfig.json`).
53
+ * - `agent` — Agent definition files shipped to `.claude/agents/` etc.
54
+ * - `skill` — Skill markdown shipped to `.claude/skills/` etc.
55
+ * - `provider` — Provider-specific bootstrap files (Anthropic, OpenAI, …).
56
+ * - `doc` — Documentation scaffolds (e.g. README.md, AGENTS.md).
57
+ */
58
+ export const TEMPLATE_KINDS = ['workflow', 'config', 'agent', 'skill', 'provider', 'doc'] as const;
59
+
60
+ /** Discriminator for the category of file a template represents. */
61
+ export type TemplateKind = (typeof TEMPLATE_KINDS)[number];
62
+
63
+ // ─── TemplateSubstitution ─────────────────────────────────────────────────────
64
+
65
+ /**
66
+ * Allowed substitution strategies a template can request.
67
+ *
68
+ * - `regex-tmpl` — `{{KEY}}` placeholder substitution via regex.
69
+ * - `static` — No substitution; the file is copied byte-for-byte.
70
+ * - `json-merge` — The template is parsed as JSON and merged into any
71
+ * existing JSON file at `installPath`; placeholders inside
72
+ * string values still go through `regex-tmpl`.
73
+ */
74
+ export const TEMPLATE_SUBSTITUTIONS = ['regex-tmpl', 'static', 'json-merge'] as const;
75
+
76
+ /** Strategy the installer uses to materialize a template's `sourcePath`. */
77
+ export type TemplateSubstitution = (typeof TEMPLATE_SUBSTITUTIONS)[number];
78
+
79
+ // ─── UpdateStrategy ───────────────────────────────────────────────────────────
80
+
81
+ /**
82
+ * How an installed template is reconciled with the shipped copy on
83
+ * `cleo upgrade` / `cleo init --force`.
84
+ *
85
+ * - `overwrite-on-bump` — Always overwrite when the manifest version is
86
+ * newer than the deployed copy.
87
+ * - `diff-prompt` — Show a diff and ask the user before overwriting.
88
+ * - `immutable` — Never overwrite once installed.
89
+ * - `manifest-merge` — Apply structural merge (e.g. JSON deep-merge,
90
+ * respecting existing user keys).
91
+ */
92
+ export const TEMPLATE_UPDATE_STRATEGIES = [
93
+ 'overwrite-on-bump',
94
+ 'diff-prompt',
95
+ 'immutable',
96
+ 'manifest-merge',
97
+ ] as const;
98
+
99
+ /** Reconciliation policy for an installed template on upgrade. */
100
+ export type UpdateStrategy = (typeof TEMPLATE_UPDATE_STRATEGIES)[number];
101
+
102
+ // ─── PlaceholderSpec ──────────────────────────────────────────────────────────
103
+
104
+ /**
105
+ * Allowed resolver sources a {@link PlaceholderSpec} can reference.
106
+ *
107
+ * - `project-context` — `.cleo/project-context.json` (detected ecosystem hints).
108
+ * - `project-info` — `.cleo/project-info.json` (per-project metadata).
109
+ * - `.cleo/config` — Per-project config (`<projectRoot>/.cleo/config.json`).
110
+ * - `~/.cleo/config` — User-global config (`$XDG_CONFIG_HOME/cleo/config.json`).
111
+ * - `tool-resolver` — Resolved via the per-language tool resolver
112
+ * (e.g. `pnpm` vs `npm` chosen by `primaryType`).
113
+ * - `literal` — Hard-coded value baked into the manifest entry.
114
+ */
115
+ export const PLACEHOLDER_SOURCES = [
116
+ 'project-context',
117
+ 'project-info',
118
+ '.cleo/config',
119
+ '~/.cleo/config',
120
+ 'tool-resolver',
121
+ 'literal',
122
+ ] as const;
123
+
124
+ /** Resolver source enum for {@link PlaceholderSpec.source}. */
125
+ export type PlaceholderSource = (typeof PLACEHOLDER_SOURCES)[number];
126
+
127
+ /**
128
+ * Zod schema for a single placeholder declaration on a template entry.
129
+ *
130
+ * Each placeholder is resolved at install time by reading `sourcePath` from
131
+ * the named `source`. If resolution returns `undefined`, the installer
132
+ * falls back to `defaultValue`; if neither yields a value, installation
133
+ * fails with `E_PLACEHOLDER_UNRESOLVED`.
134
+ */
135
+ export const PlaceholderSpecSchema = z.object({
136
+ /**
137
+ * Placeholder identifier as it appears in the template body
138
+ * (e.g. `NODE_VERSION` matches `{{NODE_VERSION}}`).
139
+ */
140
+ name: z.string().min(1, 'placeholder name must be non-empty'),
141
+ /** Resolver source the installer consults for this placeholder. */
142
+ source: z.enum(PLACEHOLDER_SOURCES),
143
+ /**
144
+ * Path expression evaluated against `source` (e.g. `engines.node` against
145
+ * `project-context`, `defaults.branchModel` against `.cleo/config`).
146
+ * For `literal` source, this MAY be the literal value's identifier.
147
+ */
148
+ sourcePath: z.string().min(1, 'placeholder sourcePath must be non-empty'),
149
+ /**
150
+ * Fallback value used when `source[sourcePath]` resolves to `undefined`.
151
+ * `null` is permitted to explicitly mark "no default — failure required".
152
+ */
153
+ defaultValue: z.union([z.string(), z.number(), z.boolean(), z.null()]).optional(),
154
+ });
155
+
156
+ /**
157
+ * Zod-inferred input shape for a placeholder declaration.
158
+ *
159
+ * Identical to {@link PlaceholderSpec} — there are no schema transforms.
160
+ */
161
+ export type PlaceholderSpecInput = z.infer<typeof PlaceholderSpecSchema>;
162
+
163
+ /** Declared placeholder on a {@link TemplateManifestEntry}. */
164
+ export type PlaceholderSpec = PlaceholderSpecInput;
165
+
166
+ // ─── TemplateManifestEntry ────────────────────────────────────────────────────
167
+
168
+ /**
169
+ * Zod schema for a single template manifest entry.
170
+ *
171
+ * Validates the full descriptor a template registry consumer needs to
172
+ * install a template file:
173
+ *
174
+ * - `id` — Stable identifier (kebab-case, matches install basename
175
+ * or a domain-unique slug).
176
+ * - `kind` — One of {@link TEMPLATE_KINDS}.
177
+ * - `sourcePath` — Repo-relative path of the template source.
178
+ * - `installPath` — Project-relative path where the rendered file lands.
179
+ * - `substitution` — One of {@link TEMPLATE_SUBSTITUTIONS}.
180
+ * - `placeholders` — Declared placeholders the installer must resolve.
181
+ * - `updateStrategy` — Reconciliation policy on upgrade.
182
+ */
183
+ export const TemplateManifestEntrySchema = z.object({
184
+ /** Stable identifier for this template entry. */
185
+ id: z.string().min(1, 'id must be non-empty'),
186
+ /** Category of file this template represents. */
187
+ kind: z.enum(TEMPLATE_KINDS),
188
+ /** Repo-relative path of the template source file. */
189
+ sourcePath: z.string().min(1, 'sourcePath must be non-empty'),
190
+ /** Project-relative path where the rendered template installs. */
191
+ installPath: z.string().min(1, 'installPath must be non-empty'),
192
+ /** Substitution strategy the installer applies to `sourcePath`. */
193
+ substitution: z.enum(TEMPLATE_SUBSTITUTIONS),
194
+ /** Declared placeholders this template requires. May be empty. */
195
+ placeholders: z.array(PlaceholderSpecSchema),
196
+ /** Reconciliation policy on upgrade. */
197
+ updateStrategy: z.enum(TEMPLATE_UPDATE_STRATEGIES),
198
+ });
199
+
200
+ /**
201
+ * Zod-inferred input shape for a template manifest entry.
202
+ *
203
+ * Identical to {@link TemplateManifestEntry} — there are no schema transforms.
204
+ */
205
+ export type TemplateManifestEntryInput = z.infer<typeof TemplateManifestEntrySchema>;
206
+
207
+ /** Public type for a fully-validated template manifest entry. */
208
+ export type TemplateManifestEntry = TemplateManifestEntryInput;