@icebreakers/monorepo 5.5.10 → 5.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +2 -0
  2. package/dist/baseline-DPfotf4y.mjs +146 -0
  3. package/dist/bundle-B9vRch4R.mjs +49 -0
  4. package/dist/catalog-CDEyc1uA.mjs +299 -0
  5. package/dist/cli.mjs +1487 -156
  6. package/dist/commands-TS8ABFdP.mjs +13820 -0
  7. package/dist/config-C38c_Q8L.mjs +66 -0
  8. package/dist/{create-flow-C811m80z.mjs → create-flow-CCr2hfSY.mjs} +103 -40
  9. package/dist/deps-CUdI2DaB.mjs +47 -0
  10. package/dist/execute-PX1hT0qv.mjs +68 -0
  11. package/dist/execute-Vi4qHe-D.mjs +663 -0
  12. package/dist/format-DZ7L34rf.mjs +28 -0
  13. package/dist/index-CoCTFWZJ.d.mts +2150 -0
  14. package/dist/index.d.mts +1741 -111
  15. package/dist/index.mjs +60 -6
  16. package/dist/inputs-_xIVONmB.mjs +50 -0
  17. package/dist/npm-B25nrSyz.mjs +82 -0
  18. package/dist/plan-B5aE_WNF.mjs +75 -0
  19. package/dist/run-Lu7y1bNf.mjs +165 -0
  20. package/dist/save-CdCf630Z.mjs +79 -0
  21. package/dist/scan-4nboHNXP.mjs +293 -0
  22. package/dist/template-drift-BBhnrHY1.mjs +2740 -0
  23. package/dist/tooling-entry.d.mts +1 -1
  24. package/dist/tooling-entry.mjs +2 -1
  25. package/dist/transaction-DAhY8EpG.mjs +168 -0
  26. package/dist/tsconfig-CGntrzBM.mjs +1483 -0
  27. package/dist/{tooling-BfXlmCi-.mjs → vitest-DkGh4Ygo.mjs} +108 -167
  28. package/dist/workspace-tasks-CnB8kkS0.mjs +4435 -0
  29. package/package.json +25 -7
  30. package/resources/api-report/runner.cjs +76 -0
  31. package/resources/devcontainer/setup.mjs +36 -0
  32. package/resources/knip/reporter.mjs +46 -0
  33. package/resources/maintenance/migration-lanes.mjs +141 -0
  34. package/resources/maintenance/migration-lock.mjs +119 -0
  35. package/resources/maintenance/migrations.mjs +215 -0
  36. package/resources/maintenance/presets.mjs +130 -0
  37. package/resources/maintenance/validate.mjs +233 -0
  38. package/resources/maintenance/workflow.yml +151 -0
  39. package/resources/skills/repoctl/SKILL.md +4 -2
  40. package/resources/skills/repoctl/references/commands.md +224 -13
  41. package/resources/skills/repoctl/references/config.md +70 -6
  42. package/resources/skills/repoctl/references/dependencies.md +37 -0
  43. package/resources/skills/repoctl/references/knip.md +34 -0
  44. package/resources/skills/repoctl/references/templates.md +26 -2
  45. package/dist/commands-CIzCAxyY.mjs +0 -5672
  46. package/dist/config-p842Knhq.mjs +0 -114
  47. package/dist/index-DDQKKYet.d.mts +0 -1025
  48. package/dist/types-m8JLwKzl.mjs +0 -499
  49. package/dist/workspace-MCKewElu.mjs +0 -123
@@ -0,0 +1,215 @@
1
+ /** Shared by preparation and the embedded publisher; policy comes from the built-in registry. */
2
+ export function validateMaintenanceMigration({ plan, policy, read, templateVersion, validateLanes, hash, equal, Buffer, fail }) {
3
+ const migration = plan?.migrations
4
+ const committed = policy ? read(policy.ledgerPath) : null
5
+ if (!migration?.ledger) {
6
+ if (committed !== null) {
7
+ let history
8
+ try {
9
+ history = JSON.parse(committed.toString())
10
+ }
11
+ catch {
12
+ fail('invalid committed migration history')
13
+ }
14
+ if (!history || history.schemaVersion !== 1 || history.attempt !== null || !history.entries
15
+ || typeof history.entries !== 'object' || Array.isArray(history.entries)
16
+ || Object.values(history.entries).some(entry => !entry || entry.status !== 'completed')) {
17
+ fail('interrupted migrations require a reviewed manual upgrade')
18
+ }
19
+ }
20
+ if (migration?.steps?.some(step => ['pending', 'failed'].includes(step.status))) {
21
+ fail('active migration has no reviewed ledger')
22
+ }
23
+ return null
24
+ }
25
+ const reject = message => fail(`invalid migration ledger: ${message}`)
26
+ if (!policy || migration.ledger.path !== policy.ledgerPath || !Array.isArray(plan.files)
27
+ || !Array.isArray(plan.inputs) || !Array.isArray(migration.steps) || !Array.isArray(migration.recovery)) {
28
+ reject('missing fixed policy or plan')
29
+ }
30
+ const versionParts = (value) => {
31
+ const match = typeof value === 'string' && /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([\dA-Z-]+(?:\.[\dA-Z-]+)*))?(?:\+[\dA-Z-]+(?:\.[\dA-Z-]+)*)?$/i.exec(value)
32
+ if (!match || match.slice(1, 4).some(part => !Number.isSafeInteger(Number(part)))) {
33
+ return null
34
+ }
35
+ const prerelease = match[4]?.split('.') ?? []
36
+ return prerelease.some(part => /^\d+$/.test(part) && part.length > 1 && part.startsWith('0')) ? null : { core: match.slice(1, 4).map(Number), prerelease }
37
+ }
38
+ const version = value => versionParts(value) !== null
39
+ const compare = (left, right) => {
40
+ const a = versionParts(left)
41
+ const b = versionParts(right)
42
+ for (let index = 0; index < 3; index++) {
43
+ if (a.core[index] !== b.core[index]) {
44
+ return Math.sign(a.core[index] - b.core[index])
45
+ }
46
+ }
47
+ if (!a.prerelease.length || !b.prerelease.length) {
48
+ return Number(!a.prerelease.length) - Number(!b.prerelease.length)
49
+ }
50
+ for (let index = 0; index < Math.max(a.prerelease.length, b.prerelease.length); index++) {
51
+ const x = a.prerelease[index]
52
+ const y = b.prerelease[index]
53
+ if (x === y) {
54
+ continue
55
+ }
56
+ if (x === undefined || y === undefined) {
57
+ return x === undefined ? -1 : 1
58
+ }
59
+ const numericX = /^\d+$/.test(x)
60
+ const numericY = /^\d+$/.test(y)
61
+ if (numericX && numericY) {
62
+ return BigInt(x) < BigInt(y) ? -1 : 1
63
+ }
64
+ return numericX !== numericY ? (numericX ? -1 : 1) : x < y ? -1 : 1
65
+ }
66
+ return 0
67
+ }
68
+ const decode = (value) => {
69
+ if (typeof value !== 'string') {
70
+ reject('missing reviewed bytes')
71
+ }
72
+ const bytes = Buffer.from(value, 'base64')
73
+ if (bytes.toString('base64') !== value) {
74
+ reject('noncanonical reviewed bytes')
75
+ }
76
+ return bytes
77
+ }
78
+ const parse = (bytes) => {
79
+ try {
80
+ return JSON.parse(bytes.toString())
81
+ }
82
+ catch {
83
+ reject('malformed JSON')
84
+ }
85
+ }
86
+ const before = committed
87
+ const previous = before === null ? { schemaVersion: 1, evaluatedVersion: null, entries: {}, attempt: null } : parse(before)
88
+ if (!previous || previous.schemaVersion !== 1 || !previous.entries || typeof previous.entries !== 'object' || Array.isArray(previous.entries)
89
+ || (previous.evaluatedVersion !== null && !version(previous.evaluatedVersion))) {
90
+ reject('invalid committed history')
91
+ }
92
+ if (previous.attempt !== null || migration.recovery.length || migration.steps.some(step => step.status === 'failed')) {
93
+ reject('interrupted migrations require a reviewed manual upgrade')
94
+ }
95
+ if (!equal(Object.keys(previous).sort(), ['attempt', 'entries', 'evaluatedVersion', 'schemaVersion'])
96
+ || Object.entries(previous.entries).some(([id, entry]) => !/^[a-z][a-z\d-]*$/.test(id) || !entry
97
+ || !equal(Object.keys(entry).sort(), ['fromVersion', 'status', 'toVersion', 'version'])
98
+ || entry.status !== 'completed' || !version(entry.version) || !version(entry.toVersion)
99
+ || (entry.fromVersion !== null && (!version(entry.fromVersion) || compare(entry.fromVersion, entry.toVersion) > 0))
100
+ || compare(entry.version, entry.toVersion) > 0 || previous.evaluatedVersion === null || compare(entry.toVersion, previous.evaluatedVersion) > 0)) {
101
+ reject('history must contain only completed records')
102
+ }
103
+ if (migration.fromVersion !== previous.evaluatedVersion || !version(migration.toVersion) || migration.toVersion !== templateVersion()
104
+ || (migration.fromVersion !== null && compare(migration.fromVersion, migration.toVersion) > 0)
105
+ || new Set(migration.steps.map(step => step.id)).size !== migration.steps.length) {
106
+ reject('source cursor or target version differs')
107
+ }
108
+ const active = migration.steps.filter(step => step.status === 'pending')
109
+ if (!active.length || migration.steps.some(step => !['pending', 'completed', 'skipped'].includes(step.status))) {
110
+ reject('no publishable migration')
111
+ }
112
+ const ledgerFiles = plan.files.filter(file => file.path === policy.ledgerPath)
113
+ const ledger = ledgerFiles[0]
114
+ if (ledgerFiles.length !== 1 || ledger.group !== policy.group || ledger.status !== (before === null ? 'add' : 'modify')
115
+ || ledger.baseline || (before === null) !== (ledger.beforeHash === null) || !ledger.afterHash) {
116
+ reject('missing exact completed ledger operation')
117
+ }
118
+ const completedBytes = decode(ledger.content)
119
+ if (hash(completedBytes) !== ledger.afterHash) {
120
+ reject('completed content digest differs')
121
+ }
122
+ const pending = parse(decode(migration.ledger.pending))
123
+ const failed = parse(decode(migration.ledger.failed))
124
+ const attempt = pending?.attempt
125
+ if (!attempt || !Array.isArray(attempt.files) || !Array.isArray(attempt.inputs) || !attempt.files.length
126
+ || new Set(attempt.files.map(file => file.path)).size !== attempt.files.length
127
+ || !equal(Object.keys(attempt).sort(), ['discovery', 'files', 'id', 'inputs'])
128
+ || hash(Buffer.from(JSON.stringify({ files: attempt.files, inputs: attempt.inputs, discovery: attempt.discovery }))) !== attempt.id) {
129
+ reject('invalid reviewed journal')
130
+ }
131
+ const sortFiles = files => [...files].sort((a, b) => a.path.localeCompare(b.path))
132
+ const journalFiles = plan.files.filter(file => file.path !== policy.ledgerPath && file.group === policy.group
133
+ && (['add', 'modify', 'delete', 'identical'].includes(file.status) || file.baseline))
134
+ const sortInputs = inputs => [...inputs].sort((a, b) => `${a.area}:${a.path}`.localeCompare(`${b.area}:${b.path}`))
135
+ if (!equal(sortFiles(attempt.files), sortFiles(journalFiles)) || !equal(attempt.discovery, plan.discovery)
136
+ || !equal(sortInputs(attempt.inputs), sortInputs(plan.inputs.filter(input => !(input.area === 'target' && input.path === policy.ledgerPath))))) {
137
+ reject('journal differs from the reviewed plan')
138
+ }
139
+ const entries = { ...previous.entries }
140
+ const pendingEntries = { ...previous.entries }
141
+ const failedEntries = { ...previous.entries }
142
+ const migrationPaths = new Set()
143
+ for (const step of active) {
144
+ const definition = policy.migrations.find(item => item.id === step.id && item.version === step.version)
145
+ if (!definition || previous.entries[step.id] || !Array.isArray(step.files) || !step.files.length
146
+ || compare(step.version, migration.toVersion) > 0
147
+ || (migration.fromVersion !== null && compare(step.version, migration.fromVersion) <= 0)
148
+ || new Set(step.files).size !== step.files.length || step.files.some(filename => !definition.paths.includes(filename))) {
149
+ reject('unknown migration identity or output path')
150
+ }
151
+ let detected = false
152
+ for (const filename of definition.legacyPaths) {
153
+ const bytes = read(filename)
154
+ if (bytes === null) {
155
+ continue
156
+ }
157
+ detected = true
158
+ const legacy = parse(bytes)
159
+ const operation = attempt.files.find(file => file.path === filename)
160
+ if (!legacy || typeof legacy !== 'object' || Array.isArray(legacy)
161
+ || (filename.endsWith('/pre.json') && (legacy.mode !== 'pre' || typeof legacy.tag !== 'string' || !legacy.tag.trim()))
162
+ || !step.files.includes(filename) || !operation || operation.status !== 'delete' || operation.content !== null || operation.afterHash !== null) {
163
+ reject('legacy source or its reviewed removal differs')
164
+ }
165
+ if (filename.endsWith('/pre.json')) {
166
+ validateLanes(attempt.files.find(file => file.path === 'pnpm-workspace.yaml'), legacy.tag)
167
+ }
168
+ }
169
+ if (!detected) {
170
+ reject('committed legacy source is absent')
171
+ }
172
+ for (const filename of step.files) {
173
+ migrationPaths.add(filename)
174
+ }
175
+ const entry = { version: step.version, status: 'completed', fromVersion: migration.fromVersion, toVersion: migration.toVersion }
176
+ entries[step.id] = entry
177
+ pendingEntries[step.id] = { ...entry, status: 'pending' }
178
+ failedEntries[step.id] = { ...entry, status: 'failed' }
179
+ }
180
+ if (!equal([...migrationPaths].sort(), attempt.files.map(file => file.path).sort())) {
181
+ reject('journal has missing or unclaimed migration outputs')
182
+ }
183
+ const expected = { schemaVersion: 1, evaluatedVersion: migration.toVersion, entries, attempt: null }
184
+ if (!equal(parse(completedBytes), expected)
185
+ || !equal(pending, { schemaVersion: 1, evaluatedVersion: previous.evaluatedVersion, entries: pendingEntries, attempt })
186
+ || !equal(failed, { schemaVersion: 1, evaluatedVersion: previous.evaluatedVersion, entries: failedEntries, attempt })) {
187
+ reject('completed, pending or failed history transition differs')
188
+ }
189
+ const operations = []
190
+ for (const file of [...attempt.files, ledger]) {
191
+ const digest = value => value === null || (typeof value === 'string' && /^[a-f0-9]{64}$/.test(value))
192
+ if (!digest(file.beforeHash) || !digest(file.afterHash)
193
+ || (file.status === 'identical' && (file.beforeHash !== file.afterHash || file.content !== null))
194
+ || (file.status !== 'identical' && (file.beforeHash === file.afterHash
195
+ || (file.status === 'add' ? file.beforeHash !== null : file.beforeHash === null)
196
+ || (file.status === 'delete' ? file.afterHash !== null || file.content !== null : file.afterHash === null || typeof file.content !== 'string')))) {
197
+ reject('invalid migration file action')
198
+ }
199
+ if (!plan.inputs.some(input => input.area === 'target' && input.path === file.path && input.hash === file.beforeHash)) {
200
+ reject('missing file precondition')
201
+ }
202
+ if (['add', 'modify', 'delete'].includes(file.status)) {
203
+ operations.push(file)
204
+ }
205
+ if (file.baseline) {
206
+ operations.push(file.baseline)
207
+ }
208
+ }
209
+ for (const file of operations) {
210
+ if (file.content === null ? file.afterHash !== null : hash(decode(file.content)) !== file.afterHash) {
211
+ reject('migration output digest differs')
212
+ }
213
+ }
214
+ return { path: policy.ledgerPath, operations }
215
+ }
@@ -0,0 +1,130 @@
1
+ /** Embedded with the publisher: fixed workflow policy and committed JSON are the only authorities. */
2
+ export function validatePresetMaintenance({ report, expected, git, hash, fail, Buffer }) {
3
+ const allowed = new Set()
4
+ const checks = []
5
+ const verification = {
6
+ paths: allowed,
7
+ verify: () => {
8
+ for (const check of checks) {
9
+ check()
10
+ }
11
+ },
12
+ }
13
+ if (report.presets === undefined) {
14
+ return verification
15
+ }
16
+ const { versions, plan, checkout } = report.presets
17
+ if (!Array.isArray(versions) || new Set(versions.map(change => change.packageName)).size !== versions.length
18
+ || versions.some(change => !['changed', 'unchanged'].includes(change.status))) {
19
+ fail('invalid preset version evidence')
20
+ }
21
+ const manifest = sha => JSON.parse(git(['show', `${sha}:package.json`]).toString())
22
+ const fromManifest = manifest(expected.base)
23
+ const toManifest = manifest(expected.head)
24
+ const exact = value => typeof value === 'string' && /^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-[0-9A-Z.-]+)?(?:\+[0-9A-Z.-]+)?$/i.test(value)
25
+ const version = (root, name) => {
26
+ const entries = ['dependencies', 'devDependencies', 'optionalDependencies'].flatMap(key => Object.hasOwn(root[key] ?? {}, name) ? [root[key][name]] : [])
27
+ return entries.length === 1 && exact(entries[0]) ? entries[0] : null
28
+ }
29
+ const changes = new Map()
30
+ for (const change of versions) {
31
+ if (!exact(change.from) || !exact(change.to) || version(fromManifest, change.packageName) !== change.from
32
+ || version(toManifest, change.packageName) !== change.to || (change.from === change.to) !== (change.status === 'unchanged')) {
33
+ fail('preset version differs from committed exact dependencies')
34
+ }
35
+ changes.set(change.packageName, change)
36
+ }
37
+ if (plan === null) {
38
+ return verification
39
+ }
40
+ if (!plan || plan.schemaVersion !== 1 || plan.kind !== 'organization-preset-assets'
41
+ || !['ready', 'unchanged'].includes(plan.status) || !Array.isArray(plan.files) || !Array.isArray(plan.conflicts) || plan.conflicts.length
42
+ || new Set(plan.files.map(file => file.path)).size !== plan.files.length) {
43
+ fail('preset plan is missing, duplicated or conflicted')
44
+ }
45
+ if (!checkout || !['false', 'true', 'input'].includes(checkout.autocrlf) || !['native', 'lf', 'crlf'].includes(checkout.eol)
46
+ || !Array.isArray(checkout.before) || checkout.before.some(file => typeof file.path !== 'string' || typeof file.content !== 'string')
47
+ || new Set(checkout.before.map(file => file.path)).size !== checkout.before.length) {
48
+ fail('invalid preset checkout evidence')
49
+ }
50
+ const preconditions = new Map(checkout.before.map(file => [file.path, file.content]))
51
+ const paths = plan.files.flatMap(file => [file.path, file.baseline?.path])
52
+ if (preconditions.size !== paths.length || paths.some(filename => !preconditions.has(filename))) {
53
+ fail('preset checkout evidence does not match the reviewed paths')
54
+ }
55
+ // Use Git's own path/attribute conversion; filters and fsmonitor are disabled by the caller.
56
+ const blobHash = (filename, content) => {
57
+ const object = git(['-c', `core.autocrlf=${checkout.autocrlf}`, '-c', `core.eol=${checkout.eol}`, '-c', 'core.safecrlf=false', 'hash-object', '-w', `--path=${filename}`, '--stdin'], content).toString().trim()
58
+ return hash(git(['cat-file', 'blob', object]))
59
+ }
60
+ const baselinePath = target => `.repoctl/baselines/presets/${hash(target)}.json`
61
+ const baseline = (bytes, file, targetVersion) => {
62
+ const record = JSON.parse(bytes.toString())
63
+ const content = typeof record.upstream?.content === 'string' ? Buffer.from(record.upstream.content, 'base64') : null
64
+ if (record.schemaVersion !== 1 || record.path !== file.path || record.source?.packageName !== file.source.packageName
65
+ || record.source?.path !== file.source.path || !exact(record.source?.version)
66
+ || (targetVersion && record.source.version !== targetVersion) || !content
67
+ || content.toString('base64') !== record.upstream.content || hash(content) !== record.upstream.hash) {
68
+ fail('preset baseline identity, version or upstream hash is invalid')
69
+ }
70
+ return record
71
+ }
72
+ const applied = plan.files.some(file => file.beforeHash !== file.afterHash)
73
+ for (const file of plan.files) {
74
+ const change = changes.get(file.source?.packageName)
75
+ const policy = (expected.presetAssets ?? []).find(asset => asset.packageName === file.source?.packageName && asset.source === file.source?.path && asset.target === file.path)
76
+ if (!policy || change?.status !== 'changed' || file.source.version !== change.to
77
+ || !['modify', 'identical'].includes(file.status) || !file.beforeHash || !file.afterHash || typeof file.content !== 'string') {
78
+ fail('preset asset is outside the fixed workflow policy or changed provider')
79
+ }
80
+ const filename = baselinePath(file.path)
81
+ const next = file.baseline
82
+ if (!next || next.path !== filename || !next.beforeHash || !next.afterHash || typeof next.content !== 'string') {
83
+ fail('preset asset requires an existing baseline at its exact target digest')
84
+ }
85
+ let previous
86
+ let original
87
+ try {
88
+ previous = git(['show', `${expected.head}:${filename}`])
89
+ original = git(['show', `${expected.base}:${filename}`])
90
+ }
91
+ catch {
92
+ fail('new preset ownership requires explicit adoption')
93
+ }
94
+ baseline(original, file)
95
+ baseline(previous, file)
96
+ const upstream = Buffer.from(next.content, 'base64')
97
+ const content = Buffer.from(file.content, 'base64')
98
+ if (upstream.toString('base64') !== next.content || hash(upstream) !== next.afterHash
99
+ || content.toString('base64') !== file.content || hash(content) !== file.afterHash) {
100
+ fail('preset plan bytes or baseline digest differ')
101
+ }
102
+ baseline(upstream, file, change.to)
103
+ for (const operation of [file, next]) {
104
+ const encoded = preconditions.get(operation.path)
105
+ const before = Buffer.from(encoded, 'base64')
106
+ if (before.toString('base64') !== encoded || hash(before) !== operation.beforeHash) {
107
+ fail('preset raw precondition differs from its reviewed plan')
108
+ }
109
+ const beforeHash = blobHash(operation.path, before)
110
+ if (hash(git(['show', `${expected.head}:${operation.path}`])) !== beforeHash) {
111
+ fail('preset source precondition differs from committed ownership')
112
+ }
113
+ const entry = report.files.find(entry => entry.path === operation.path)
114
+ if (entry && (entry.beforeHash !== beforeHash || !entry.beforeMode || !entry.afterMode)) {
115
+ fail('preset patch differs from its reviewed plan or removes ownership')
116
+ }
117
+ if (applied && entry) {
118
+ allowed.add(operation.path)
119
+ }
120
+ // The authorized patch may update .gitattributes; bind after bytes using its next rules.
121
+ checks.push(() => {
122
+ const afterHash = blobHash(operation.path, Buffer.from(operation.content, 'base64'))
123
+ if (entry ? entry.afterHash !== afterHash : applied && beforeHash !== afterHash) {
124
+ fail('preset patch differs from its reviewed plan or omits a changed asset')
125
+ }
126
+ })
127
+ }
128
+ }
129
+ return verification
130
+ }
@@ -0,0 +1,233 @@
1
+ import { validateMaintenanceLanes } from './migration-lanes.mjs'
2
+ import { maintenanceTemplateVersion } from './migration-lock.mjs'
3
+ import { validateMaintenanceMigration } from './migrations.mjs'
4
+ import { validatePresetMaintenance } from './presets.mjs'
5
+
6
+ /** This exact function is embedded into the exported workflow; it uses only Node built-ins. */
7
+ export async function validateMaintenanceArtifact({ cwd, directory, expected, request }) {
8
+ const { Buffer } = await import('node:buffer')
9
+ const { isDeepStrictEqual } = await import('node:util')
10
+ const fs = await import('node:fs/promises')
11
+ const path = await import('node:path')
12
+ const { createHash } = await import('node:crypto')
13
+ const { execFileSync } = await import('node:child_process')
14
+ const hash = value => createHash('sha256').update(value).digest('hex')
15
+ const fail = (message) => {
16
+ throw new Error(`Maintenance publication blocked: ${message}`)
17
+ }
18
+ // Git filters and fsmonitor are executable configuration, including during status/checkout.
19
+ const gitOptions = ['--no-optional-locks', '-c', 'core.fsmonitor=false']
20
+ const execGit = (args, input) => execFileSync('git', [...gitOptions, ...args], { cwd, input, maxBuffer: 32 * 1024 * 1024 })
21
+ let filterKeys
22
+ try {
23
+ filterKeys = execGit(['config', '--null', '--name-only', '--get-regexp', '^filter\\..*\\.(clean|smudge|process|required)$']).toString().split('\0').filter(Boolean)
24
+ }
25
+ catch (error) {
26
+ if (error.status !== 1 || error.stdout?.length) {
27
+ fail('cannot inspect Git filter configuration')
28
+ }
29
+ filterKeys = []
30
+ }
31
+ const disabled = new Map([['core.fsmonitor', 'false']])
32
+ for (const driver of new Set(filterKeys.map(key => key.slice(0, key.lastIndexOf('.'))))) {
33
+ for (const setting of ['clean', 'smudge', 'process', 'required']) {
34
+ const key = `${driver}.${setting}`
35
+ const value = setting === 'required' ? 'false' : ''
36
+ disabled.set(key, value)
37
+ gitOptions.push('-c', `${key}=${value}`)
38
+ }
39
+ }
40
+ const git = (args, input) => execGit(args, input)
41
+ const readArtifact = async (filename, limit) => {
42
+ const file = path.join(directory, filename)
43
+ const stat = await fs.lstat(file)
44
+ if (!stat.isFile() || stat.nlink !== 1 || stat.size > limit) {
45
+ fail(`invalid artifact file ${filename}`)
46
+ }
47
+ return fs.readFile(file)
48
+ }
49
+ const report = JSON.parse((await readArtifact('report.json', 5 * 1024 * 1024)).toString())
50
+ if (report.schemaVersion !== 1 || report.kind !== 'repoctl-maintenance-upgrade'
51
+ || report.repository !== expected.repository || report.runId !== String(expected.runId)
52
+ || report.runAttempt !== String(expected.runAttempt) || report.head !== expected.head
53
+ || report.base !== expected.base || report.branch !== 'repoctl/managed-assets') {
54
+ fail('artifact belongs to another repository, commit or workflow attempt')
55
+ }
56
+ if (report.status === 'unchanged') {
57
+ return { ready: false, reason: 'No managed asset changes.' }
58
+ }
59
+ if (report.status !== 'ready' || !Array.isArray(report.errors) || report.errors.length
60
+ || !['changed', 'unchanged'].includes(report.versions?.status)
61
+ || (report.versions.status === 'changed' && (report.plan?.status !== 'ready'
62
+ || !Array.isArray(report.plan.files) || report.plan.files.some(file => file.status === 'conflict')))
63
+ || (report.versions.status === 'unchanged' && !report.presets?.versions?.some(change => change.status === 'changed'))
64
+ || !Array.isArray(report.checks) || report.checks.some(check => !['passed', 'skipped'].includes(check.status))
65
+ || !['lockfile', 'install'].every(name => report.checks.some(check => check.name === name && check.status === 'passed'))
66
+ || !report.checks.some(check => ['lint', 'typecheck', 'test'].includes(check.name) && check.status === 'passed')) {
67
+ fail('the plan or validation did not complete successfully')
68
+ }
69
+ if (!expected.appConfigured) {
70
+ fail('configure REPOCTL_APP_CLIENT_ID and REPOCTL_APP_PRIVATE_KEY with contents, pull requests and workflows write access')
71
+ }
72
+ const patch = await readArtifact('changes.patch', 32 * 1024 * 1024)
73
+ if (!patch.length || hash(patch) !== report.patchHash || !Array.isArray(report.files) || !report.files.length) {
74
+ fail('patch is missing or its digest changed')
75
+ }
76
+ const safePath = filename => typeof filename === 'string' && /^[\w./-]+$/.test(filename)
77
+ && !filename.startsWith('/') && !filename.split('/').some(part => ['', '.', '..', '.git'].includes(part))
78
+ const sourcePaths = new Set(git(['ls-tree', '-r', '--name-only', expected.head]).toString().trim().split('\n'))
79
+ const readSource = filename => sourcePaths.has(filename) ? git(['show', `${expected.head}:${filename}`]) : null
80
+ const migration = validateMaintenanceMigration({
81
+ plan: report.plan,
82
+ policy: expected.migrationPolicy,
83
+ read: readSource,
84
+ templateVersion: () => maintenanceTemplateVersion({ lock: readSource('pnpm-lock.yaml'), toolVersion: report.versions.to, fail }),
85
+ validateLanes: (operation, tag) => validateMaintenanceLanes({ read: readSource, sourcePaths, operation, tag, Buffer, fail }),
86
+ hash,
87
+ equal: isDeepStrictEqual,
88
+ Buffer,
89
+ fail,
90
+ })
91
+ if (migration && !report.files.some(file => file.path === migration.path)) {
92
+ fail('migration ledger is missing from the reviewed patch')
93
+ }
94
+ const presets = validatePresetMaintenance({ report, expected, git, hash, fail, Buffer })
95
+ const owned = new Set(git(['ls-tree', '-r', '--name-only', expected.head]).toString().split('\n').filter(name => /^\.repoctl\/baselines\/presets\/[a-f0-9]{64}\.json$/.test(name)))
96
+ const presetOwned = filename => owned.has(`.repoctl/baselines/presets/${hash(filename)}.json`)
97
+ || (filename.startsWith('.repoctl/baselines/root/') && owned.has(filename.replace('/root/', '/presets/')))
98
+ const allowed = filename => presets.paths.has(filename) || (!presetOwned(filename) && (filename === 'pnpm-lock.yaml'
99
+ || (report.versions.status === 'changed' && (expected.targets.some(target => filename === target || filename.startsWith(`${target}/`))
100
+ || /^\.repoctl\/baselines\/root\/[a-f0-9]{64}\.json$/.test(filename) || filename === migration?.path))))
101
+ const names = report.files.map(file => file.path)
102
+ if (new Set(names).size !== names.length || names.some(filename => !safePath(filename) || !allowed(filename))) {
103
+ fail('patch includes an unapproved or duplicate path')
104
+ }
105
+ const mode = value => value === null || ['100644', '100755'].includes(value)
106
+ const digest = value => value === null || (typeof value === 'string' && /^[a-f0-9]{64}$/.test(value))
107
+ if (report.files.some(file => !mode(file.beforeMode) || !mode(file.afterMode)
108
+ || !digest(file.beforeHash) || !digest(file.afterHash)
109
+ || (file.beforeMode === null) !== (file.beforeHash === null)
110
+ || (file.afterMode === null) !== (file.afterHash === null))) {
111
+ fail('unsupported Git mode or malformed file digest')
112
+ }
113
+ const patchFile = path.join(directory, 'changes.patch')
114
+ const patchPaths = git(['apply', '--numstat', '-z', '--', patchFile]).toString().split('\0').filter(Boolean).map((entry) => {
115
+ const match = /^(?:\d+|-)\t(?:\d+|-)\t(.+)$/u.exec(entry)
116
+ if (!match) {
117
+ fail('patch contains unsupported path evidence')
118
+ }
119
+ return match[1]
120
+ }).sort()
121
+ if (JSON.stringify(patchPaths) !== JSON.stringify([...names].sort())) {
122
+ fail('patch paths differ from the reviewed report')
123
+ }
124
+ let repository
125
+ let branch
126
+ let artifact
127
+ try {
128
+ repository = (await request('GET /repos/{owner}/{repo}', expected.coordinates)).data
129
+ branch = (await request('GET /repos/{owner}/{repo}/branches/{branch}', { ...expected.coordinates, branch: expected.defaultBranch })).data
130
+ artifact = (await request('GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}', { ...expected.coordinates, artifact_id: expected.artifactId })).data
131
+ }
132
+ catch (error) {
133
+ fail(`repository permission or source verification failed: ${error.message}`)
134
+ }
135
+ if (repository.full_name !== expected.repository || repository.default_branch !== expected.defaultBranch
136
+ || branch.commit?.sha !== expected.head || git(['rev-parse', 'HEAD']).toString().trim() !== expected.head
137
+ || git(['status', '--porcelain', '--untracked-files=all']).length) {
138
+ fail('the trusted default branch moved or the publication checkout is dirty')
139
+ }
140
+ if (String(artifact.id) !== String(expected.artifactId) || artifact.expired
141
+ || artifact.name !== `repoctl-maintenance-${expected.runId}-${expected.runAttempt}`
142
+ || String(artifact.workflow_run?.id) !== String(expected.runId) || artifact.workflow_run?.head_sha !== expected.head
143
+ || typeof expected.artifactDigest !== 'string' || !/^[a-f0-9]{64}$/.test(expected.artifactDigest.replace(/^sha256:/, ''))
144
+ || artifact.digest?.replace(/^sha256:/, '') !== expected.artifactDigest.replace(/^sha256:/, '')) {
145
+ fail('artifact identity, immutable digest or originating workflow run does not match')
146
+ }
147
+ const tree = new Map(git(['ls-tree', '-r', '-z', expected.head]).toString().split('\0').filter(Boolean).map((entry) => {
148
+ const [metadata, filename] = entry.split('\t')
149
+ return [filename, metadata.split(' ')[0]]
150
+ }))
151
+ for (const file of report.files) {
152
+ if ((tree.get(file.path) ?? null) !== file.beforeMode
153
+ || (tree.has(file.path) ? hash(git(['show', `${expected.head}:${file.path}`])) : null) !== file.beforeHash) {
154
+ fail(`source precondition changed: ${file.path}`)
155
+ }
156
+ }
157
+ const hooks = path.join(directory, 'empty-hooks')
158
+ await fs.mkdir(hooks, { recursive: true })
159
+ // Persist the same policy for the subsequent create-pull-request action.
160
+ for (const [key, value] of disabled) {
161
+ git(['config', '--local', '--replace-all', key, value])
162
+ }
163
+ git(['config', '--local', 'core.hooksPath', hooks])
164
+ // A named working base avoids create-pull-request's detached-HEAD rebase onto an unverified latest base.
165
+ git(['check-ref-format', '--branch', expected.defaultBranch])
166
+ git(['checkout', '-B', expected.defaultBranch, expected.head])
167
+ git(['update-ref', `refs/remotes/origin/${expected.defaultBranch}`, expected.head])
168
+ git(['apply', '--check', '--index', '--whitespace=nowarn', patchFile])
169
+ git(['apply', '--index', '--whitespace=nowarn', patchFile])
170
+ const actual = git(['diff', '--cached', '--name-only', '-z', '--no-renames', '--no-ext-diff', '--no-textconv']).toString().split('\0').filter(Boolean).sort()
171
+ if (JSON.stringify(actual) !== JSON.stringify([...names].sort())) {
172
+ fail('patch paths differ from the reviewed report')
173
+ }
174
+ const index = new Map(git(['ls-files', '--stage', '-z']).toString().split('\0').filter(Boolean).map((entry) => {
175
+ const [metadata, filename] = entry.split('\t')
176
+ const [mode, object, stage] = metadata.split(' ')
177
+ if (stage !== '0') {
178
+ fail(`unmerged index entry: ${filename}`)
179
+ }
180
+ return [filename, { mode, object }]
181
+ }))
182
+ for (const file of report.files) {
183
+ const next = index.get(file.path)
184
+ const stat = await fs.lstat(path.join(cwd, file.path)).catch((error) => {
185
+ if (error.code === 'ENOENT') {
186
+ return null
187
+ }
188
+ throw error
189
+ })
190
+ if ((next?.mode ?? null) !== file.afterMode || (stat && !stat.isFile()) || Boolean(next) !== Boolean(stat)
191
+ || (next ? hash(git(['cat-file', 'blob', next.object])) : null) !== file.afterHash) {
192
+ fail(`patched file bytes or mode differ from the report: ${file.path}`)
193
+ }
194
+ }
195
+ presets.verify()
196
+ // Bind every completed migration output to the verified patch using its resulting attributes.
197
+ for (const operation of migration?.operations ?? []) {
198
+ let afterHash = null
199
+ if (operation.content !== null) {
200
+ const object = git(['-c', 'core.safecrlf=false', 'hash-object', '-w', `--path=${operation.path}`, '--stdin'], Buffer.from(operation.content, 'base64')).toString().trim()
201
+ afterHash = hash(git(['cat-file', 'blob', object]))
202
+ }
203
+ const entry = report.files.find(file => file.path === operation.path)
204
+ const previous = entry ? null : readSource(operation.path)
205
+ if (afterHash !== (entry ? entry.afterHash : previous === null ? null : hash(previous))) {
206
+ fail('migration output differs from the completed journal')
207
+ }
208
+ }
209
+ // Git blob identity is exact; checkout bytes may differ through built-in EOL/encoding rules.
210
+ try {
211
+ git(['diff', '--exit-code', '--no-ext-diff', '--no-textconv', '--ignore-submodules=none', '--', ...names])
212
+ }
213
+ catch {
214
+ fail('patched checkout contents are not Git-equivalent to the verified index')
215
+ }
216
+ const body = [
217
+ '<!-- repoctl-maintenance:v1 -->',
218
+ `Synchronize repoctl root assets: ${report.versions.from} → ${report.versions.to}.`,
219
+ ...(report.presets?.versions.filter(change => change.status === 'changed').map(change => `Preset ${change.packageName}: ${change.from} → ${change.to}.`) ?? []),
220
+ `Validated source: ${report.head}; comparison: ${report.base}.`,
221
+ '',
222
+ ...(report.plan?.files ?? []).map(file => `- ${file.path}: ${file.status} (${file.reason})`),
223
+ '',
224
+ ...(report.presets?.plan?.files.map(file => `- ${file.path}: ${file.status} (${file.reason})`) ?? []),
225
+ ...report.checks.map(check => `- ${check.name}: ${check.status}`),
226
+ '',
227
+ `Complete plan, patch and logs: https://github.com/${expected.repository}/actions/runs/${expected.runId}`,
228
+ 'No automatic merge or package publication is performed.',
229
+ ].join('\n')
230
+ const bodyFile = path.join(directory, 'verified-body.md')
231
+ await fs.writeFile(bodyFile, `${body}\n`)
232
+ return { ready: true, branch: report.branch, bodyFile, targetVersion: report.versions.to }
233
+ }