@skitterbyte/skitterspec-linear 19.3.0 → 19.5.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 (71) hide show
  1. package/assets/claude-md-section.md +20 -1
  2. package/assets/core/SETUP.md +5 -0
  3. package/assets/core/env.config.json.example +1 -0
  4. package/assets/core/env.config.md +143 -8
  5. package/assets/core/linear.config.json.example +2 -2
  6. package/assets/core/linear.config.md +49 -16
  7. package/assets/hooks/main-guard.cjs +40 -6
  8. package/assets/hooks/review-gate.cjs +42 -7
  9. package/assets/rules/commit-trailers.md +24 -1
  10. package/assets/rules/spec-planning.md +81 -18
  11. package/assets/rules/spec-reports.md +1 -1
  12. package/assets/skills/spec/SKILL.md +55 -2
  13. package/assets/skills/spec-bug/SKILL.md +36 -3
  14. package/assets/skills/spec-cancel/SKILL.md +37 -0
  15. package/assets/skills/spec-claim/SKILL.md +41 -2
  16. package/assets/skills/spec-complete/SKILL.md +115 -0
  17. package/assets/skills/spec-hotfix/SKILL.md +51 -4
  18. package/assets/skills/spec-incident/SKILL.md +22 -0
  19. package/assets/skills/spec-linear-setup/SKILL.md +23 -1
  20. package/assets/skills/spec-next/SKILL.md +12 -5
  21. package/assets/skills/spec-push/SKILL.md +22 -0
  22. package/assets/skills/spec-review/SKILL.md +34 -0
  23. package/assets/skills/spec-start/SKILL.md +50 -3
  24. package/assets/skills/spec-status/SKILL.md +18 -3
  25. package/assets/skills/spec-sync/SKILL.md +1 -0
  26. package/assets/skills/spec-to-main/SKILL.md +47 -1
  27. package/package.json +1 -1
  28. package/src/cli.js +1188 -79
  29. package/src/env/base.js +104 -0
  30. package/src/env/bootstrap.js +22 -3
  31. package/src/env/classify.js +12 -4
  32. package/src/env/config.js +77 -5
  33. package/src/env/disposition.js +62 -0
  34. package/src/env/handoff.js +81 -0
  35. package/src/env/host.js +262 -0
  36. package/src/env/hotfix.js +237 -9
  37. package/src/env/hotfixland.js +105 -10
  38. package/src/env/inflight.js +98 -0
  39. package/src/env/integrate.js +136 -9
  40. package/src/env/live.js +8 -7
  41. package/src/env/mainguard.js +20 -5
  42. package/src/env/phases.js +28 -0
  43. package/src/env/project.js +223 -0
  44. package/src/env/provision.js +30 -8
  45. package/src/env/resolve.js +147 -25
  46. package/src/env/review.js +21 -7
  47. package/src/env/reviewers.js +7 -10
  48. package/src/env/serve.js +27 -11
  49. package/src/env/specstate.js +101 -0
  50. package/src/env/supervise.js +15 -2
  51. package/src/env/teardown.js +46 -3
  52. package/src/init.js +49 -9
  53. package/src/vendor/linear/cli-sanitise.js +8 -3
  54. package/src/vendor/linear/cli-sync.js +64 -10
  55. package/src/vendor/linear/config.js +27 -21
  56. package/src/vendor/linear/doctor.js +2 -0
  57. package/src/vendor/provider-kit/index.js +4 -0
  58. package/src/vendor/provider-kit/src/apply.js +58 -6
  59. package/src/vendor/provider-kit/src/assignment.js +78 -1
  60. package/src/vendor/provider-kit/src/config.js +34 -1
  61. package/src/vendor/provider-kit/src/credentials.js +7 -2
  62. package/src/vendor/provider-kit/src/list-rows.js +35 -11
  63. package/src/vendor/provider-kit/src/released.js +48 -4
  64. package/src/vendor/provider-kit/src/specs.js +18 -7
  65. package/src/vendor/provider-kit/src/splice.js +64 -0
  66. package/src/vendor/provider-kit/src/status.js +137 -0
  67. package/src/vendor/sync-core/index.js +14 -1
  68. package/src/vendor/sync-core/src/compare.js +81 -6
  69. package/src/vendor/sync-core/src/normalize.js +50 -7
  70. package/src/vendor/sync-core/src/push.js +65 -5
  71. package/src/vendor/sync-core/src/summary.js +257 -0
@@ -32,6 +32,7 @@ const fs = require('node:fs')
32
32
  const path = require('node:path')
33
33
  const crypto = require('node:crypto')
34
34
  const { spawn } = require('node:child_process')
35
+ const { signalGroup } = require('./supervise.js')
35
36
 
36
37
  const BUNDLED_ADAPTERS = { coderabbit: require('./reviewers/coderabbit.js') }
37
38
 
@@ -287,7 +288,9 @@ function runReviewer(entry, ctx) {
287
288
  // Through a shell, deliberately: the config holds a command LINE, with
288
289
  // pipes and quoting the project chose. It is read from a committed config
289
290
  // in the project's own repo — the same trust level as a package script.
290
- child = spawnFn('/bin/sh', ['-c', rendered], {
291
+ // `sh` from PATH on Windows — Git for Windows' — where `/bin/sh` does not
292
+ // exist and no reviewer could run at all (chore-windows-ci).
293
+ child = spawnFn(process.platform === 'win32' ? 'sh' : '/bin/sh', ['-c', rendered], {
291
294
  cwd: worktree,
292
295
  stdio: ['ignore', 'pipe', 'pipe'],
293
296
  // THE CHILD LEADS ITS OWN PROCESS GROUP, and the timeout below depends
@@ -314,15 +317,9 @@ function runReviewer(entry, ctx) {
314
317
  timedOut = true
315
318
  // The group, not the shell: `/bin/sh -c "cr review"` killed on its own
316
319
  // leaves the reviewer running and holding the port/rate-limit slot.
317
- try {
318
- process.kill(-child.pid, 'SIGKILL')
319
- } catch {
320
- try {
321
- child.kill('SIGKILL')
322
- } catch {
323
- /* already gone */
324
- }
325
- }
320
+ // `signalGroup` is the group on POSIX and the process tree on Windows,
321
+ // which has no groups (env/supervise.js).
322
+ signalGroup(child.pid, 'SIGKILL')
326
323
  }, entry.timeout * 1000)
327
324
 
328
325
  const settle = (spawnError) => {
package/src/env/serve.js CHANGED
@@ -38,8 +38,10 @@ const {
38
38
  } = require('./resolve.js')
39
39
  const { readRegistry } = require('./registry.js')
40
40
  const { loadEnvConfig } = require('./config.js')
41
+ const { primaryAnchor, attachProject, repoRootOf, prefixOf, fromRepoPath, toRepoPath } = require('./project.js')
41
42
  const { specDocsIn, classifyDirtyTree, dirtyPaths } = require('./classify.js')
42
43
  const { liveStateFor } = require('./live.js')
44
+ const { preferRemoteBase } = require('./host.js')
43
45
  const {
44
46
  rawGitReader,
45
47
  collectReview,
@@ -218,8 +220,11 @@ ${body}
218
220
  * file in the tree IS evidence that the tree is being used for something else,
219
221
  * and that answer must stay unchanged — see the stays-silent test.
220
222
  */
221
- function isProjectBookkeeping(p) {
222
- return String(p).startsWith('specs/.core/')
223
+ //
224
+ // `p` is a repo path; the project's `specs/.core/` is under its prefix.
225
+ function isProjectBookkeeping(p, prefix = '') {
226
+ const rel = fromRepoPath(String(p), prefix)
227
+ return rel !== null && rel.startsWith('specs/.core/')
223
228
  }
224
229
 
225
230
  function docsWorktree(wt, spec, config) {
@@ -245,18 +250,22 @@ function docsWorktree(wt, spec, config) {
245
250
  // which is what `--docs` showed from the CLI — a served page that listed a
246
251
  // file the run's own report did not would be a different page from the one
247
252
  // the reader was told about.
248
- const intruders = foreign.filter((p) => !isProjectBookkeeping(p))
253
+ const intruders = foreign.filter((p) => !isProjectBookkeeping(p, prefixOf(config)))
249
254
  if (!owned.length || intruders.length) return null
250
255
  return { owned }
251
256
  }
252
257
 
253
258
  function viewFor(dir, config, spec, git, { fallback = false } = {}) {
254
259
  if (!spec) return null
260
+ // Every tree a view names is a git ROOT, so the reader bound to it prints
261
+ // root-relative paths and takes root-relative pathspecs. `dir` is the project
262
+ // folder, which is the root unless the project sits in a subfolder.
263
+ const root = repoRootOf(dir, config)
255
264
  // LIVE COMES FIRST, because while a spec is live its worktree still exists —
256
265
  // detached — and would win the check below while holding none of the work.
257
266
  // `live take` checks the branch out HERE, and a fix made while live is made
258
267
  // here too, so this checkout is the tree that answers.
259
- if (spec.branch && headBranchOf(git) === spec.branch) return { kind: 'live', tree: dir }
268
+ if (spec.branch && headBranchOf(git) === spec.branch) return { kind: 'live', tree: root }
260
269
  const wt = spec.worktreePath
261
270
  if (wt && wt !== dir && fs.existsSync(wt)) {
262
271
  // A DOCS WORKTREE IS NOT A CODE WORKTREE, and this used to be unreachable.
@@ -286,7 +295,7 @@ function viewFor(dir, config, spec, git, { fallback = false } = {}) {
286
295
  if (docs) return { kind: 'docs', tree: wt, owned: docs.owned }
287
296
  return { kind: 'worktree', tree: wt }
288
297
  }
289
- const found = specDocsIn(dir, spec, config, trimmedGitReader(dir))
298
+ const found = specDocsIn(root, spec, config, trimmedGitReader(root))
290
299
  // `error` is cannot-tell — not a page, and not an error page either (rule 4:
291
300
  // the harmless branch).
292
301
  if (found.error) return null
@@ -309,9 +318,9 @@ function viewFor(dir, config, spec, git, { fallback = false } = {}) {
309
318
  // omits them in the first place. A direct request is someone opening an
310
319
  // address they were given, and that has to keep resolving.
311
320
  if (!fallback) return null
312
- const committed = committedDocsFor(dir, config, spec)
321
+ const committed = committedDocsFor(root, config, spec)
313
322
  if (!committed) return null
314
- return { kind: 'docs-committed', tree: dir, owned: committed }
323
+ return { kind: 'docs-committed', tree: root, owned: committed }
315
324
  }
316
325
 
317
326
  /**
@@ -321,9 +330,9 @@ function viewFor(dir, config, spec, git, { fallback = false } = {}) {
321
330
  * that is no spec at all must stay a 404 rather than render an empty page with
322
331
  * a commit button on it.
323
332
  */
324
- function committedDocsFor(dir, config, spec) {
325
- const git = trimmedGitReader(dir)
326
- const out = git(['ls-files', '--', `specs/*/${spec.folder}/*`])
333
+ function committedDocsFor(root, config, spec) {
334
+ const git = trimmedGitReader(root)
335
+ const out = git(['ls-files', '--', toRepoPath(`specs/*/${spec.folder}/*`, prefixOf(config))])
327
336
  if (out == null) return null
328
337
  const paths = String(out)
329
338
  .split('\n')
@@ -557,7 +566,11 @@ function renderSpecPage(dir, config, spec, { branch = false } = {}) {
557
566
  const out = git(argv)
558
567
  return out == null ? null : String(out).trim() || null
559
568
  }
560
- const base = () => spec.baseRef || resolveBaseBranch(config, trimmed)
569
+ // PR mode measures the diff against the REMOTE image of base — local base is
570
+ // allowed to go stale there. `preferRemoteBase` never fetches and falls back
571
+ // to the local name, so the render stays offline-safe.
572
+ const base = () =>
573
+ spec.baseRef || preferRemoteBase(config, resolveBaseBranch(config, trimmed), trimmed)
561
574
 
562
575
  const now = new Date().toISOString()
563
576
  let mode = 'working'
@@ -1030,6 +1043,9 @@ if (require.main === module) {
1030
1043
  }
1031
1044
  const { dir, port, host, token } = JSON.parse(fs.readFileSync(settingsFile, 'utf-8'))
1032
1045
  const { config } = loadEnvConfig(dir)
1046
+ // `dir` is the project folder the CLI anchored on; re-derive where it sits in
1047
+ // its repo so worktree paths resolve beside the repo, as the CLI's do.
1048
+ attachProject(config, primaryAnchor(dir, trimmedGitReader(dir)))
1033
1049
  const server = createReviewServer({ ...serverHooks(dir, config), token })
1034
1050
  startReviewServer(server, { port, host }).then(
1035
1051
  () => {},
@@ -0,0 +1,101 @@
1
+ 'use strict'
2
+
3
+ /**
4
+ * What a spec's own copy says about it — the reader behind `skitterspec status`.
5
+ *
6
+ * Point it at a worktree (or any checkout) and a spec folder name, and it reports
7
+ * the bucket the spec sits in THERE, its phase progress, and any `Status:` /
8
+ * `Developer:` header it still carries. Pure but for the injected `io`, so the
9
+ * command layer is testable without a worktree and this without a CLI.
10
+ *
11
+ * THE BUCKET IS READ FROM THE ROOT IT IS GIVEN. On the base branch an in-flight
12
+ * spec still sits in `backlog/`, which is the very lie this exists to correct, so
13
+ * the caller hands it the worktree's root, never the checkout it is standing in.
14
+ *
15
+ * A MISSING `Status:` HEADER IS NOT UNKNOWN. Under `sync.fieldOwnership`
16
+ * `workflowState: "pull"` new specs carry no `Status:` or `Developer:` line —
17
+ * the board owns both — so `status: null` is the expected shape, and the bucket
18
+ * and progress still answer. Only a spec that cannot be found or read is
19
+ * `found: false`, and the caller renders that as `status unknown` rather than
20
+ * dropping it (Decision 5).
21
+ */
22
+
23
+ const fs = require('node:fs')
24
+ const path = require('node:path')
25
+
26
+ const { phaseProgress } = require('./phases.js')
27
+
28
+ // Most live first: a spec that exists in two buckets mid-`git mv` is reported
29
+ // where it is going, not where it was.
30
+ const SEARCH = ['in-progress', 'backlog', 'complete', 'cancelled']
31
+
32
+ const defaultIo = {
33
+ readdir: (dir) => fs.readdirSync(dir),
34
+ readFile: (file) => fs.readFileSync(file, 'utf8'),
35
+ }
36
+
37
+ // A header line's value, or null when the line is absent, empty, or the `—`
38
+ // placeholder the templates write before anyone is named.
39
+ function header(text, field) {
40
+ const m = new RegExp(`^>\\s*\\*\\*${field}:\\*\\*[ \\t]*(.*)$`, 'm').exec(text)
41
+ if (!m) return null
42
+ const value = m[1].trim()
43
+ return value && value !== '—' && value !== '-' ? value : null
44
+ }
45
+
46
+ // Inline phases, for the legacy overview with no phase files: `## Phase N …`
47
+ // headings carrying the same emoji the phase files do. Nothing countable is
48
+ // null, never zero — "no phases" and "could not see the phases" differ.
49
+ function inlineProgress(text) {
50
+ const headings = text.split('\n').filter((l) => /^#{2,3}\s+Phase\s+\d+\b/.test(l))
51
+ if (!headings.length) return null
52
+ return phaseProgress(headings.map((h) => ({ content: h.replace(/^#+/, '#') })))
53
+ }
54
+
55
+ function tryRead(io, fn) {
56
+ try {
57
+ return fn()
58
+ } catch {
59
+ return null
60
+ }
61
+ }
62
+
63
+ /**
64
+ * @param {string} root the checkout to read — a spec's worktree, normally
65
+ * @param {string} folder the spec's folder name (`feat-x`)
66
+ * @param {object} [io] `{ readdir, readFile }`, each throwing on failure
67
+ * @returns {{ found: true, bucket, legacy, phasesDone, phasesTotal, currentPhase, status, developer }
68
+ * | { found: false, reason }}
69
+ */
70
+ function readSpecState(root, folder, io = defaultIo) {
71
+ for (const bucket of SEARCH) {
72
+ const dir = path.join(root, 'specs', bucket, folder)
73
+ const files = tryRead(io, () => io.readdir(dir))
74
+ if (files) {
75
+ const overview = tryRead(io, () => io.readFile(path.join(dir, '00-overview.md')))
76
+ if (overview === null) return { found: false, reason: `${bucket}/${folder} has no readable 00-overview.md` }
77
+ const phaseFiles = files.filter((f) => /^(?!00-)\d{2}-.*\.md$/.test(f)).sort()
78
+ const phases = phaseFiles.map((f) => ({ file: f, content: tryRead(io, () => io.readFile(path.join(dir, f))) }))
79
+ const progress = phases.length ? phaseProgress(phases) : inlineProgress(overview)
80
+ return state(bucket, false, overview, progress)
81
+ }
82
+ const bare = tryRead(io, () => io.readFile(path.join(root, 'specs', bucket, `${folder}.md`)))
83
+ if (bare !== null) return state(bucket, true, bare, inlineProgress(bare))
84
+ }
85
+ return { found: false, reason: `no spec named ${folder} under specs/` }
86
+ }
87
+
88
+ function state(bucket, legacy, text, progress) {
89
+ return {
90
+ found: true,
91
+ bucket,
92
+ legacy,
93
+ phasesDone: progress ? progress.done : null,
94
+ phasesTotal: progress ? progress.total : null,
95
+ currentPhase: progress ? progress.current : null,
96
+ status: header(text, 'Status'),
97
+ developer: header(text, 'Developer'),
98
+ }
99
+ }
100
+
101
+ module.exports = { readSpecState, SEARCH }
@@ -12,7 +12,7 @@
12
12
 
13
13
  const fs = require('node:fs')
14
14
  const path = require('node:path')
15
- const { spawn } = require('node:child_process')
15
+ const { spawn, spawnSync } = require('node:child_process')
16
16
 
17
17
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
18
18
 
@@ -34,7 +34,18 @@ function isAlive(pid) {
34
34
  // Signal a detached process's whole group (its leader pid is `pid`, so the group
35
35
  // id is `-pid`) — reaches children like vite/tsc that a bare `pnpm dev` spawns.
36
36
  // Falls back to signalling just the leader if the group send fails.
37
- function signalGroup(pid, sig) {
37
+ //
38
+ // WINDOWS HAS NO PROCESS GROUPS: `-pid` throws, the fallback kills only the
39
+ // `sh` wrapper, and the server it started survives — holding its port and its
40
+ // worktree, which then cannot be removed (chore-windows-ci). `taskkill /T` walks
41
+ // the tree instead; `/F` for both signals, because a console process ignores
42
+ // the polite close a bare `taskkill` sends. Run with an argument list, never a
43
+ // shell. `opts` is injectable for tests.
44
+ function signalGroup(pid, sig, { platform = process.platform, run = spawnSync } = {}) {
45
+ if (platform === 'win32') {
46
+ run('taskkill', ['/pid', String(pid), '/T', '/F'], { stdio: 'ignore', windowsHide: true })
47
+ return
48
+ }
38
49
  try {
39
50
  process.kill(-pid, sig)
40
51
  } catch {
@@ -81,6 +92,8 @@ function startProcess(proc, { cwd, rootDir, spawnImpl = spawn }) {
81
92
  cwd,
82
93
  env: { ...process.env, ...proc.env },
83
94
  detached: true,
95
+ // No console window per dev server on Windows; nothing anywhere else.
96
+ windowsHide: true,
84
97
  stdio: ['ignore', out, out],
85
98
  })
86
99
  child.unref()
@@ -23,6 +23,7 @@
23
23
 
24
24
  const { expandTokens } = require('./resolve.js')
25
25
  const { composeFileArg } = require('./provision.js')
26
+ const { shellPath } = require('./project.js')
26
27
 
27
28
  /**
28
29
  * @param {object} spec resolved spec: { slug, branch, worktreePath, projectName, ... }
@@ -59,6 +60,28 @@ function planDown(spec, config, flags, ctx) {
59
60
  if (config.guards.refuseTeardownIfUnpushed && worktreeState.unpushed && !landed) {
60
61
  return blocked('worktree has unpushed commits not yet merged into the base branch')
61
62
  }
63
+ // PR mode: `merged` already includes the host's answer (the CLI folds a
64
+ // merged PR in before planning), so an UNLANDED branch here really is one
65
+ // the host has not merged — or one whose lookup failed, and deleting a
66
+ // worktree on a lookup that failed is the destructive reading of an absence
67
+ // (`.claude/rules/negative-checks.md` rule 4). Refused at plan time rather
68
+ // than left to `git branch -d`'s error, because this message can name the
69
+ // PR and the exit where git's cannot. `--force` bypasses, and still plans
70
+ // `-d` below, so a genuinely unlanded branch fails loudly rather than
71
+ // being -D'd.
72
+ if (config.land && config.land.strategy === 'pr' && !landed) {
73
+ const prState = worktreeState.prState
74
+ const at = worktreeState.prUrl ? ` — see ${worktreeState.prUrl}` : ''
75
+ if (prState === 'open' || prState === 'draft') {
76
+ return blocked(
77
+ `the PR for ${spec.branch} is still ${prState}${at}; it lands when the host merges`,
78
+ )
79
+ }
80
+ if (prState === 'none') {
81
+ return blocked(`${spec.branch} has no PR and is not merged into the base branch`)
82
+ }
83
+ return blocked(`cannot confirm the PR for ${spec.branch} merged${at}`)
84
+ }
62
85
  }
63
86
 
64
87
  // Docker teardown only applies to a Docker-escalated spec. A worktree-only spec
@@ -109,7 +132,7 @@ function planDown(spec, config, flags, ctx) {
109
132
  commands.push(
110
133
  force
111
134
  ? `git worktree remove --force ${spec.worktreePath}`
112
- : `git worktree remove ${spec.worktreePath}`,
135
+ : `git worktree remove ${shellPath(spec.worktreePath)}`,
113
136
  )
114
137
 
115
138
  // --- delete the branch ---
@@ -160,6 +183,11 @@ function planDown(spec, config, flags, ctx) {
160
183
  // may well be on a remote this clone cannot see (pushed from another machine),
161
184
  // and the honest answer to "is there a remote branch?" is then "cannot tell",
162
185
  // which routes to doing nothing.
186
+ //
187
+ // A host that auto-deletes the branch on merge (common PR-mode hygiene) makes
188
+ // this delete a no-op: `git push --delete` errors with "remote ref does not
189
+ // exist", which is loud and destroys nothing. The skills report that as
190
+ // already-gone, never as a failed teardown.
163
191
  const remoteCommands = []
164
192
  const policy = (config.teardown && config.teardown.deleteRemoteBranch) || 'prompt'
165
193
  if (spec.branch && landed && worktreeState.remoteBranch && policy !== 'never') {
@@ -184,6 +212,21 @@ function planDown(spec, config, flags, ctx) {
184
212
  }
185
213
  }
186
214
 
215
+ // A live PR left behind by a cancelled spec is noise with a merge button on
216
+ // it, so a FORCED teardown past an open/draft PR also plans the abandon —
217
+ // composed by the caller (the host adapter's business), quarantined with the
218
+ // remote delete because closing a shared PR reaches outside this machine.
219
+ // Unforced never gets here with an open PR (the guard above refused), and a
220
+ // missing command (unknown host, no id) plans nothing: the refusal/report
221
+ // already named the PR, and a person closes it.
222
+ if (
223
+ config.land && config.land.strategy === 'pr' &&
224
+ (worktreeState.prState === 'open' || worktreeState.prState === 'draft') &&
225
+ ctx && ctx.prAbandonCommand
226
+ ) {
227
+ remoteCommands.push(ctx.prAbandonCommand)
228
+ }
229
+
187
230
  return {
188
231
  blocked: false,
189
232
  reason: null,
@@ -240,8 +283,8 @@ function planDownCheckout(spec, config, flags, ctx) {
240
283
  }
241
284
 
242
285
  const commands = []
243
- if (onBranch !== false) commands.push(`git -C ${checkoutPath} switch ${base}`)
244
- commands.push(`git -C ${checkoutPath} branch ${landed ? '-D' : '-d'} ${spec.branch}`)
286
+ if (onBranch !== false) commands.push(`git -C ${shellPath(checkoutPath)} switch ${base}`)
287
+ commands.push(`git -C ${shellPath(checkoutPath)} branch ${landed ? '-D' : '-d'} ${spec.branch}`)
245
288
  return { ...result, commands }
246
289
  }
247
290
 
package/src/init.js CHANGED
@@ -3,10 +3,12 @@
3
3
  const fs = require('fs')
4
4
  const path = require('path')
5
5
  const crypto = require('crypto')
6
+ const { execFileSync } = require('child_process')
6
7
 
7
8
  const { ensureWorktreeDirTrusted } = require('./env/trust.js')
8
9
  const { ensureHooks } = require('./env/hooks.js')
9
10
  const { repoInfo, expandTokens } = require('./env/resolve.js')
11
+ const { primaryAnchor } = require('./env/project.js')
10
12
 
11
13
  const ASSETS = path.join(__dirname, '..', 'assets')
12
14
 
@@ -286,8 +288,11 @@ const RETIRED_FILES = [
286
288
  path.join('specs', 'complete', '00-index.md'),
287
289
  ]
288
290
 
291
+ // `/`-separated on every platform: these are the manifest's keys and the
292
+ // report's lines, and a Windows install recording `specs\\.core\\…` would read
293
+ // as a different file to every other machine (chore-windows-ci).
289
294
  function rel(dir, p) {
290
- return path.relative(dir, p) || '.'
295
+ return path.relative(dir, p).split(path.sep).join('/') || '.'
291
296
  }
292
297
 
293
298
  function ensureDir(p) {
@@ -310,8 +315,22 @@ const MANIFEST_VERSION = 1
310
315
  // reset each init() alongside `report`.
311
316
  const writtenHashes = {}
312
317
 
318
+ // Every judgement about a managed file compares content with its line endings
319
+ // normalised. On Windows with `core.autocrlf=true` a checkout rewrites LF to
320
+ // CRLF, and an exact compare read that conversion as the user's edit: every
321
+ // skill, command and rule became "your edit — kept" and stopped updating.
322
+ // Assets ship LF, so hashes of LF files — every manifest already written — are
323
+ // unchanged by this.
324
+ function normalizeEol(content) {
325
+ return content.replace(/\r\n/g, '\n')
326
+ }
327
+
328
+ function sameContent(a, b) {
329
+ return normalizeEol(a) === normalizeEol(b)
330
+ }
331
+
313
332
  function sha1(content) {
314
- return crypto.createHash('sha1').update(content).digest('hex')
333
+ return crypto.createHash('sha1').update(normalizeEol(content)).digest('hex')
315
334
  }
316
335
 
317
336
  // The full managed set for a target dir: repo-relative path, absolute path, and
@@ -349,10 +368,18 @@ function readManifest(dir) {
349
368
  try {
350
369
  const parsed = JSON.parse(fs.readFileSync(path.join(dir, MANIFEST_FILE), 'utf8'))
351
370
  if (parsed && typeof parsed === 'object' && parsed.files && typeof parsed.files === 'object') {
371
+ // KEYS ARE `/`-SEPARATED ON READ, whoever wrote them. A Windows install
372
+ // before chore-windows-ci recorded `.claude\\skills\\…`; looked up by the
373
+ // `/` paths every caller now uses, its records went missing — and a
374
+ // missing record is what turns a user's edited retired file into one
375
+ // that gets deleted. No managed path contains a backslash, so this
376
+ // cannot merge two genuine entries.
377
+ const files = {}
378
+ for (const [key, hash] of Object.entries(parsed.files)) files[key.replace(/\\/g, '/')] = hash
352
379
  return {
353
380
  version: parsed.version || MANIFEST_VERSION,
354
- files: parsed.files,
355
- baselined: Object.keys(parsed.files).length > 0,
381
+ files,
382
+ baselined: Object.keys(files).length > 0,
356
383
  }
357
384
  }
358
385
  } catch {
@@ -406,10 +433,13 @@ function writeManifest(dir, files) {
406
433
  // `pruneRetiredManaged` passes no `bundled` on purpose: the package no longer
407
434
  // ships that file, so there is nothing to compare it against.
408
435
  function managedState(dir, relPath, manifest, bundled) {
436
+ // Manifest keys are `/`-separated; a caller holding an OS path still finds
437
+ // its file's record (chore-windows-ci).
438
+ relPath = String(relPath).split(path.sep).join('/')
409
439
  const abs = path.join(dir, relPath)
410
440
  if (!fs.existsSync(abs)) return 'missing'
411
441
  const onDisk = fs.readFileSync(abs, 'utf8')
412
- if (bundled !== undefined && onDisk === bundled) return 'pristine'
442
+ if (bundled !== undefined && sameContent(onDisk, bundled)) return 'pristine'
413
443
  const known = manifest.files[relPath]
414
444
  if (known) return sha1(onDisk) === known ? 'pristine' : 'customized'
415
445
  return manifest.baselined ? 'adopted' : 'customized'
@@ -715,8 +745,18 @@ function trustWorktreeRoot(dir) {
715
745
  report.warnings.push('could not read worktree.root — skipped trusting the worktree dir')
716
746
  return
717
747
  }
718
- const { repo, repoSlug } = repoInfo(dir)
719
- const rootAbs = path.resolve(dir, expandTokens(root, { repo, repoSlug }))
748
+ // Resolved against the REPO's root, and named for it, exactly as `spec-env`
749
+ // resolves it — `dir` is the project folder, which is a subfolder of the repo
750
+ // for some projects (feat-subfolder-project). Not a repo → `dir`, as before.
751
+ const anchor = primaryAnchor(dir, (args) => {
752
+ try {
753
+ return execFileSync('git', ['-C', dir, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim()
754
+ } catch {
755
+ return null
756
+ }
757
+ })
758
+ const { repo, repoSlug } = repoInfo(anchor.root)
759
+ const rootAbs = path.resolve(anchor.root, expandTokens(root, { repo, repoSlug }))
720
760
  const res = ensureWorktreeDirTrusted(dir, rootAbs)
721
761
  const label = '.claude/settings.local.json (trusted worktree root)'
722
762
  if (res.reason === 'malformed') {
@@ -777,7 +817,7 @@ function checkSync(dir, { claudeMd = true, log = console.log } = {}) {
777
817
  else if (state === 'customized') rows.push([relPath, 'your edit — kept (--force overwrites)'])
778
818
  else if (state === 'adopted')
779
819
  rows.push([relPath, 'adopted upstream — yours kept, theirs not installed (--force takes theirs)'])
780
- else if (fs.readFileSync(abs, 'utf8') !== bundled) rows.push([relPath, 'out of date — would be updated'])
820
+ else if (!sameContent(fs.readFileSync(abs, 'utf8'), bundled)) rows.push([relPath, 'out of date — would be updated'])
781
821
  }
782
822
  const section = claudeMd ? claudeMdSectionState(dir) : 'fresh'
783
823
  // A healthy area says NOTHING. A report that lists what is already fine is a
@@ -876,7 +916,7 @@ function resyncManagedFile(dir, target, manifest, force) {
876
916
  return report[state].push({ relPath, added, removed, hunks })
877
917
  }
878
918
  // pristine — update only if the bundled content actually changed
879
- if (fs.readFileSync(abs, 'utf8') === bundled) {
919
+ if (sameContent(fs.readFileSync(abs, 'utf8'), bundled)) {
880
920
  // The file is ours and current, but the manifest disagreed — record the
881
921
  // repair rather than healing in silence: a file that quietly starts
882
922
  // updating again is as opaque as one that quietly stopped.
@@ -36,7 +36,9 @@ function collectMarkdown(target) {
36
36
  // Skip VCS/deps, and `.core` — skitterspec's own manifest-managed docs.
37
37
  // Reflowing a managed file makes the next `update` see it as customized and
38
38
  // freeze the shipped version, silently pinning stale docs.
39
- if (/(^|\/)(node_modules|\.git|\.core)$/.test(p)) return
39
+ // Either separator: on Windows `p` is `specs\\.core`, and a `/`-only test
40
+ // walked straight into the managed docs it exists to protect.
41
+ if (/(^|[\\/])(node_modules|\.git|\.core)$/.test(p)) return
40
42
  for (const name of fs.readdirSync(p).sort()) walk(path.join(p, name))
41
43
  } else if (st.isFile() && p.endsWith('.md')) {
42
44
  out.push(p)
@@ -95,10 +97,13 @@ async function specSanitise(argv, { cwd = process.cwd(), out = process.stdout }
95
97
 
96
98
  const excludeRes = opts.exclude.map(globToRe)
97
99
  const excluded = (rel) => excludeRes.some((re) => re.test(rel))
100
+ // Repo paths are `/`-separated everywhere — what `--exclude` globs are
101
+ // written against, and what the report prints.
102
+ const relOf = (f) => path.relative(cwd, f).split(path.sep).join('/')
98
103
  const files = new Set()
99
104
  for (const p of opts.paths) {
100
105
  for (const f of collectMarkdown(path.resolve(cwd, p))) {
101
- if (!excluded(path.relative(cwd, f))) files.add(f)
106
+ if (!excluded(relOf(f))) files.add(f)
102
107
  }
103
108
  }
104
109
 
@@ -108,7 +113,7 @@ async function specSanitise(argv, { cwd = process.cwd(), out = process.stdout }
108
113
  for (const file of [...files].sort()) {
109
114
  const src = fs.readFileSync(file, 'utf-8')
110
115
  const res = sanitizeSpecMarkdown(src, opts.width ? { width: opts.width } : {})
111
- const rel = path.relative(cwd, file)
116
+ const rel = relOf(file)
112
117
  if (res.refused) {
113
118
  refusedFiles++
114
119
  out.write(`skipped ${rel} (would alter structure — left untouched)\n`)