trackfw 3.1.0 → 4.0.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.
@@ -0,0 +1,217 @@
1
+ 'use strict'
2
+
3
+ // update-engine.js — shared state machine for `trackfw update` and
4
+ // `trackfw update harness` (ML-6C of ROADMAP-2026-07-29-barrier-governanca-
5
+ // e-autoridade-do-orquestrador). Both commands report one of exactly four
6
+ // states per target (`updated`, `skipped`, `missing`, `failed`) and emit the
7
+ // same JSON document shape — see docs/cli-parity.md, section
8
+ // "`trackfw update` vs `trackfw update harness`" for the frozen contract.
9
+ //
10
+ // Key invariant enforced here: a `missing` target is NEVER installed unless
11
+ // `installMissing` is explicitly true. This is the single most
12
+ // safety-critical rule in the contract, so it is centralized in
13
+ // `runFileTarget` rather than re-implemented per target.
14
+
15
+ const fs = require('fs')
16
+ const os = require('os')
17
+ const path = require('path')
18
+ const crypto = require('crypto')
19
+
20
+ function sha256(buf) {
21
+ return crypto.createHash('sha256').update(buf).digest('hex')
22
+ }
23
+
24
+ function collectDirEntries(dir) {
25
+ const out = []
26
+ function walk(current, rel) {
27
+ let entries
28
+ try {
29
+ entries = fs.readdirSync(current, { withFileTypes: true })
30
+ } catch (_) {
31
+ return
32
+ }
33
+ entries.sort((a, b) => a.name.localeCompare(b.name))
34
+ for (const entry of entries) {
35
+ const childRel = rel ? path.join(rel, entry.name) : entry.name
36
+ const childAbs = path.join(current, entry.name)
37
+ if (entry.isDirectory()) walk(childAbs, childRel)
38
+ else out.push([childRel, sha256(fs.readFileSync(childAbs))])
39
+ }
40
+ }
41
+ walk(dir, '')
42
+ return out
43
+ }
44
+
45
+ // hashPath — returns null when the path does not exist, a content hash for
46
+ // a file, or a hash of the recursive (relative-path, content-hash) listing
47
+ // for a directory. Used to detect "nothing changed" without caring whether
48
+ // the target is a single file or a directory of generated artifacts.
49
+ function hashPath(target) {
50
+ if (!fs.existsSync(target)) return null
51
+ const stat = fs.lstatSync(target)
52
+ if (stat.isDirectory()) return JSON.stringify(collectDirEntries(target))
53
+ return sha256(fs.readFileSync(target))
54
+ }
55
+
56
+ function copyPath(src, dst) {
57
+ if (!fs.existsSync(src)) return
58
+ const stat = fs.lstatSync(src)
59
+ if (stat.isDirectory()) {
60
+ fs.mkdirSync(dst, { recursive: true })
61
+ for (const entry of fs.readdirSync(src, { withFileTypes: true })) {
62
+ copyPath(path.join(src, entry.name), path.join(dst, entry.name))
63
+ }
64
+ } else {
65
+ fs.mkdirSync(path.dirname(dst), { recursive: true })
66
+ fs.copyFileSync(src, dst)
67
+ }
68
+ }
69
+
70
+ // silenceConsole — apply()s reused from generators/init.js and friends log
71
+ // their own progress via console.log; those messages are only meaningful
72
+ // against the real root, not the scratch copy used to predict --dry-run
73
+ // state. Suppressed during simulation only.
74
+ function silenceConsole(fn) {
75
+ const original = console.log
76
+ console.log = () => {}
77
+ try {
78
+ return fn()
79
+ } finally {
80
+ console.log = original
81
+ }
82
+ }
83
+
84
+ /**
85
+ * runFileTarget — computes updated/skipped/missing/failed for a target whose
86
+ * only observable effect is writing under a fixed set of paths (files or
87
+ * directories) relative to `root`, by diffing content hashes before/after
88
+ * invoking `apply(root)`.
89
+ *
90
+ * - `--dry-run`: `apply` runs against a scratch temp directory seeded only
91
+ * with copies of the paths that already exist under `root` — the real
92
+ * `root` is never touched.
93
+ * - real run: `apply` runs directly against `root`.
94
+ * - `missing` (nothing present under any of `relPaths`) never triggers
95
+ * `apply` unless `installMissing` is true.
96
+ */
97
+ function runFileTarget({ id, path: displayPath, root, relPaths, apply, dryRun, installMissing }) {
98
+ const before = relPaths.map(rel => hashPath(path.join(root, rel)))
99
+ const allMissingBefore = before.every(h => h === null)
100
+
101
+ if (allMissingBefore && !installMissing) {
102
+ return { id, state: 'missing', path: displayPath }
103
+ }
104
+
105
+ try {
106
+ let after
107
+ if (dryRun) {
108
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'trackfw-update-'))
109
+ try {
110
+ for (const rel of relPaths) copyPath(path.join(root, rel), path.join(tmp, rel))
111
+ silenceConsole(() => apply(tmp))
112
+ after = relPaths.map(rel => hashPath(path.join(tmp, rel)))
113
+ } finally {
114
+ fs.rmSync(tmp, { recursive: true, force: true })
115
+ }
116
+ } else {
117
+ apply(root)
118
+ after = relPaths.map(rel => hashPath(path.join(root, rel)))
119
+ }
120
+
121
+ const allMissingAfter = after.every(h => h === null)
122
+ if (allMissingBefore && allMissingAfter) return { id, state: 'missing', path: displayPath }
123
+ const unchanged = before.length === after.length && before.every((h, i) => h === after[i])
124
+ return { id, state: unchanged ? 'skipped' : 'updated', path: displayPath }
125
+ } catch (e) {
126
+ return { id, state: 'failed', path: displayPath, message: e.message }
127
+ }
128
+ }
129
+
130
+ function summarize(targets) {
131
+ const summary = { updated: 0, skipped: 0, missing: 0, failed: 0 }
132
+ for (const t of targets) summary[t.state] += 1
133
+ return summary
134
+ }
135
+
136
+ // tildeify — the contract's JSON example shows global paths abbreviated as
137
+ // `~/...`; emitting the absolute path would both break byte-parity with the
138
+ // other runtimes and leak the local username into committed/shared output.
139
+ //
140
+ // Both operands are run through path.normalize before comparison: a raw
141
+ // process.env.HOME can contain a redundant separator (e.g. macOS's default
142
+ // $TMPDIR ends in "/", so a test harness building HOME as `"$TMPDIR/foo"`
143
+ // yields ".../T//foo"), while `absPath` here is always produced via
144
+ // path.join, which normalizes internally — comparing the two without
145
+ // normalizing homeRoot first made the prefix check silently fail and fall
146
+ // through to the absolute-path branch. Mirrors Python's _tildeify
147
+ // (pypi/trackfw/commands/update_harness.py), which normalizes both sides
148
+ // via os.path.normpath for the same reason.
149
+ //
150
+ // A second, subtler case (ML-6H): path.normalize PRESERVES a trailing
151
+ // separator when the input already has one (macOS's default $TMPDIR itself
152
+ // ends in "/", so a HOME built as "$TMPDIR/foo" collapses the internal
153
+ // "//" but still ends in a single trailing "/"). The prefix check below
154
+ // then appended ANOTHER path.sep, comparing against ".../foo//" — which
155
+ // normalizedPath (which never carries a trailing separator, since it comes
156
+ // from path.join) never starts with — so the check silently failed and
157
+ // fell through to the absolute-path branch even though homeRoot had
158
+ // already been normalized. Stripping a trailing separator from
159
+ // normalizedHome (root "/" excepted) before the prefix check closes this.
160
+ function tildeify(homeRoot, absPath) {
161
+ let normalizedHome = path.normalize(homeRoot)
162
+ if (normalizedHome.length > path.sep.length && normalizedHome.endsWith(path.sep)) {
163
+ normalizedHome = normalizedHome.slice(0, -path.sep.length)
164
+ }
165
+ const normalizedPath = path.normalize(absPath)
166
+ if (normalizedPath === normalizedHome) return '~'
167
+ if (normalizedPath.startsWith(normalizedHome + path.sep)) return '~' + normalizedPath.slice(normalizedHome.length)
168
+ return normalizedPath
169
+ }
170
+
171
+ // validateTargets — throws (usage error) when the caller asked for an id
172
+ // that does not exist in the declared universe for this command. Returns
173
+ // the requested id list unchanged (or null when no filter was requested).
174
+ function validateTargets(allIds, wanted) {
175
+ if (!wanted || !wanted.length) return null
176
+ for (const id of wanted) {
177
+ if (!allIds.includes(id)) throw new Error(`Unknown update target: ${id}`)
178
+ }
179
+ return wanted
180
+ }
181
+
182
+ function buildDocument(scope, dryRun, targets) {
183
+ return {
184
+ scope,
185
+ dry_run: dryRun,
186
+ targets: targets.map(t => {
187
+ const entry = { id: t.id, state: t.state, path: t.path }
188
+ if (t.state === 'failed' && t.message) entry.message = t.message
189
+ return entry
190
+ }),
191
+ summary: summarize(targets),
192
+ }
193
+ }
194
+
195
+ function humanReport(scope, dryRun, targets) {
196
+ const lines = [`trackfw update — scope: ${scope}${dryRun ? ' (dry-run)' : ''}`, '']
197
+ for (const t of targets) {
198
+ const mark = { updated: '✓', skipped: '·', missing: '—', failed: '✗' }[t.state] || '?'
199
+ const suffix = t.state === 'failed' && t.message ? ` (${t.message})` : ''
200
+ lines.push(` ${mark} ${t.id.padEnd(24)} ${t.state.padEnd(8)} ${t.path}${suffix}`)
201
+ }
202
+ const summary = summarize(targets)
203
+ lines.push('', `updated=${summary.updated} skipped=${summary.skipped} missing=${summary.missing} failed=${summary.failed}`)
204
+ return lines.join('\n')
205
+ }
206
+
207
+ module.exports = {
208
+ hashPath,
209
+ copyPath,
210
+ runFileTarget,
211
+ summarize,
212
+ tildeify,
213
+ validateTargets,
214
+ buildDocument,
215
+ humanReport,
216
+ silenceConsole,
217
+ }
@@ -1288,7 +1288,9 @@ module.exports = {
1288
1288
  listDir,
1289
1289
  tryListDir,
1290
1290
  resolveReqFiles,
1291
+ resolveStateDirs,
1291
1292
  resolveWIPDirs,
1293
+ resolveDoneDirs,
1292
1294
  readGovernanceMode,
1293
1295
  readWIPConfig,
1294
1296
  parseSquadFromFrontmatter,