@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
@@ -14,22 +14,46 @@ function expandStateArgs(args, config) {
14
14
  return (args || []).flatMap((arg) => (LIFECYCLE_BUCKETS.includes(arg) ? stateNamesFor(arg, config) : [arg]))
15
15
  }
16
16
 
17
- // The spec's status beside the board's, and whether they disagree. A board
18
- // state that maps to no bucket never disagrees: it is somewhere push does not
19
- // manage, which is not a claim about the spec. Nor does a row whose spec is not
20
- // on this machine — there is nothing to disagree WITH.
17
+ // A spec's bucket is a CODE FACT — whether `/spec-start`, `/spec-complete` or
18
+ // `/spec-cancel` has run — and the board holds the planning status. So almost
19
+ // every difference between the two is the board doing its job: a backlog spec
20
+ // the board calls Ready or Blocked, an in-flight one it calls In Review. Neither
21
+ // is a claim about the repo, and flagging them would teach a reader to ignore
22
+ // the column.
23
+ //
24
+ // One difference IS worth a reader's time: the board says the work is finished
25
+ // (Done or Cancelled) and the repo has not done the matching cleanup. Only that
26
+ // pairing disagrees, and it carries the command that would close it.
27
+ const LIVE_BUCKETS = ['backlog', 'in-progress']
28
+ const FINISHED_BUCKETS = ['complete', 'cancelled']
29
+
30
+ // `{ board, cleanup }` when the board has finished what the repo has not, else
31
+ // null. Done against a spec in flight is `/spec-complete`; every other pairing
32
+ // (Cancelled, or Done on a spec that never started) is `/spec-cancel`, because
33
+ // there is no work here to complete.
34
+ function boardDisagreement(specBucket, boardBucket) {
35
+ if (!LIVE_BUCKETS.includes(specBucket) || !FINISHED_BUCKETS.includes(boardBucket)) return null
36
+ const cleanup = specBucket === 'in-progress' && boardBucket === 'complete' ? '/spec-complete' : '/spec-cancel'
37
+ return { board: boardBucket, cleanup }
38
+ }
39
+
40
+ // The spec's status beside the board's, and whether they disagree in the one
41
+ // way above. A board state that maps to no bucket never disagrees: it is
42
+ // somewhere push does not manage, which is not a claim about the spec. Nor does
43
+ // a row whose spec is not on this machine — there is nothing to disagree WITH.
21
44
  function specColumn(stateName, spec, config) {
22
45
  const specStatus = spec ? spec.bucket : null
23
46
  const seen = stateName == null ? null : remoteStateReading({ state: { name: stateName } }, config)
24
- const disagrees = Boolean(specStatus && seen && seen.mapped && seen.bucket !== specStatus)
25
- return { specStatus, disagrees }
47
+ const found = specStatus && seen && seen.mapped ? boardDisagreement(specStatus, seen.bucket) : null
48
+ return found ? { specStatus, disagrees: true, cleanup: found.cleanup } : { specStatus, disagrees: false }
26
49
  }
27
50
 
28
- // The cell itself: `in-progress`, `≠ backlog` when it disagrees, `—` when the
29
- // spec is not here.
30
- function specCell({ specStatus, disagrees }) {
51
+ // The cell itself: `in-progress`, `≠ in-progress → /spec-cancel` when the board
52
+ // finished it, `—` when the spec is not here.
53
+ function specCell({ specStatus, disagrees, cleanup }) {
31
54
  if (!specStatus) return '—'
32
- return disagrees ? `≠ ${specStatus}` : specStatus
55
+ if (!disagrees) return specStatus
56
+ return cleanup ? `≠ ${specStatus} → ${cleanup}` : `≠ ${specStatus}`
33
57
  }
34
58
 
35
- module.exports = { expandStateArgs, specColumn, specCell }
59
+ module.exports = { expandStateArgs, specColumn, specCell, boardDisagreement }
@@ -1,5 +1,25 @@
1
1
  'use strict'
2
2
 
3
+ const { execFileSync } = require('node:child_process')
4
+ const { primaryAnchor, fromRepoPath } = require('../../../env/project.js')
5
+
6
+ /**
7
+ * The project's prefix within its repo, read from `dir` — `''` at the root, and
8
+ * `''` whenever git cannot answer (today's behaviour). What `ticketsInRange`
9
+ * needs to read a commit's root-relative paths against the project's
10
+ * `ignorePaths`.
11
+ */
12
+ function projectPrefixOf(dir) {
13
+ const git = (args) => {
14
+ try {
15
+ return execFileSync('git', ['-C', dir, ...args], { encoding: 'utf-8', stdio: ['ignore', 'pipe', 'ignore'] }).trim()
16
+ } catch {
17
+ return null
18
+ }
19
+ }
20
+ return primaryAnchor(dir, git).prefix
21
+ }
22
+
3
23
  /**
4
24
  * Which tickets a release contains.
5
25
  *
@@ -99,7 +119,14 @@ function asGlobal(pattern) {
99
119
  * @param {string[]|null|undefined} paths repo-relative paths the commit changed
100
120
  * @param {string[]} ignorePaths repo-relative prefixes that are bookkeeping
101
121
  */
102
- function onlyIgnoredPaths(paths, ignorePaths) {
122
+ //
123
+ // `paths` are what `git log --name-only` prints — from the REPO ROOT — while
124
+ // `ignorePaths` are the project's, like every path in its config. For a project
125
+ // in a subfolder of its repo (`prefix`, spec feat-subfolder-project) each path
126
+ // is made project-relative first, and a path OUTSIDE the project is never
127
+ // bookkeeping: a commit that touched `Sql/` did real work. Prefix '' compares
128
+ // exactly as before.
129
+ function onlyIgnoredPaths(paths, ignorePaths, prefix = '') {
103
130
  if (!Array.isArray(paths) || !paths.length) return false
104
131
  const prefixes = (Array.isArray(ignorePaths) ? ignorePaths : [])
105
132
  .filter((p) => typeof p === 'string' && p.trim())
@@ -113,7 +140,9 @@ function onlyIgnoredPaths(paths, ignorePaths) {
113
140
  // An unreadable entry is an unknown, not an ignored one — it makes the whole
114
141
  // commit count, per the bias above.
115
142
  if (!file) return false
116
- return prefixes.some((prefix) => file === prefix || file.startsWith(`${prefix}/`))
143
+ const rel = fromRepoPath(file, prefix)
144
+ if (rel === null) return false
145
+ return prefixes.some((p) => rel === p || rel.startsWith(`${p}/`))
117
146
  })
118
147
  }
119
148
 
@@ -140,14 +169,18 @@ function onlyIgnoredPaths(paths, ignorePaths) {
140
169
  */
141
170
  function ticketsInRange(commits, options = {}) {
142
171
  const ignorePaths = (options && options.ignorePaths) || []
172
+ const prefix = (options && options.prefix) || ''
143
173
  const refPattern = options && options.refPattern
144
174
  const foreign = ((options && options.foreignPatterns) || []).map(asGlobal).filter(Boolean)
145
175
  const seen = new Map()
146
176
  let unreferenced = 0
147
177
  let ignored = 0
148
178
  let historical = 0
179
+ let merges = 0
180
+ let sawMergeFlag = false
149
181
  for (const commit of commits || []) {
150
- if (onlyIgnoredPaths(commit && commit.paths, ignorePaths)) {
182
+ if (commit && commit.isMerge !== undefined) sawMergeFlag = true
183
+ if (onlyIgnoredPaths(commit && commit.paths, ignorePaths, prefix)) {
151
184
  // Not counted as unreferenced either: that number exists to surface a
152
185
  // MISSED trailer, and a paperwork commit is not a gap someone should hunt.
153
186
  ignored++
@@ -157,8 +190,15 @@ function ticketsInRange(commits, options = {}) {
157
190
  if (!refs.length) {
158
191
  // A POSITIVE signal, never an absence: only a trailer that actually
159
192
  // carries an older tracker's ref makes a commit historical. A commit with
160
- // no trailer at all is still the gap `unreferenced` is there to name.
193
+ // no trailer at all is still the gap `unreferenced` is there to name —
194
+ // unless it is a MERGE commit, which is transport: under PR landing the
195
+ // host writes one per merged PR, and counting each as a missed trailer
196
+ // buries the real gaps. A merge that CARRIES a trailer still counted
197
+ // above, deliberately — a hand merge is where a ticket's only trailer
198
+ // sometimes lives, which is why these are read rather than skipped
199
+ // (`--no-merges` was tried and dropped for exactly that loss).
161
200
  if (foreign.some((p) => refsInBody(commit && commit.body, p).length)) historical++
201
+ else if (commit && commit.isMerge) merges++
162
202
  else unreferenced++
163
203
  continue
164
204
  }
@@ -171,6 +211,9 @@ function ticketsInRange(commits, options = {}) {
171
211
  total: (commits || []).length,
172
212
  }
173
213
  if (foreign.length) report.historical = historical
214
+ // Present only when a caller supplied the flag at all, so a provider that
215
+ // passes no parent info sees exactly the report shape it always did.
216
+ if (sawMergeFlag) report.merges = merges
174
217
  return report
175
218
  }
176
219
 
@@ -209,6 +252,7 @@ function refuseRemovedVerb(out, program, verb) {
209
252
  }
210
253
 
211
254
  module.exports = {
255
+ projectPrefixOf,
212
256
  ticketsInRange,
213
257
  refuseRemovedVerb,
214
258
  nameTickets,
@@ -21,10 +21,10 @@ const {
21
21
  findSpecFolder,
22
22
  resolveSpec,
23
23
  liveWorktreePaths,
24
- resolvePrimaryCheckout,
25
24
  } = require('../../../env/resolve.js')
26
25
  const { loadEnvConfig } = require('../../../env/config.js')
27
- const { readSnapshot, parseFrontmatter, lintPhases, fieldsOf, projectionOf, compareStored } = require('../../sync-core')
26
+ const { primaryAnchor, attachProject, projectIn } = require('../../../env/project.js')
27
+ const { readSnapshot, parseFrontmatter, lintPhases, fieldsOf, projectionOf, compareStored, comparableDescription } = require('../../sync-core')
28
28
 
29
29
  function makeSpecHelpers({ program = 'spec-sync' } = {}) {
30
30
  // Resolve a spec argument to its snapshot dir. Accepts a spec name/folder
@@ -136,9 +136,16 @@ function makeSpecHelpers({ program = 'spec-sync' } = {}) {
136
136
  }
137
137
  let primary
138
138
  let env
139
+ let prefix = ''
139
140
  try {
140
- primary = resolvePrimaryCheckout(dir, git) || dir
141
+ // The project folder in the primary checkout, with where it sits in its
142
+ // repo attached — worktrees are laid out beside the REPO, and each holds
143
+ // the project at the same prefix (feat-subfolder-project).
144
+ const anchor = primaryAnchor(dir, git)
145
+ primary = anchor.dir || dir
146
+ prefix = anchor.prefix
141
147
  env = loadEnvConfig(primary)
148
+ attachProject(env.config, anchor)
142
149
  } catch {
143
150
  return here
144
151
  }
@@ -147,7 +154,7 @@ function makeSpecHelpers({ program = 'spec-sync' } = {}) {
147
154
  // symlinks (macOS /var → /private/var) where `resolveSpec` does not.
148
155
  const real = (p) => {
149
156
  try {
150
- return fs.realpathSync(p)
157
+ return fs.realpathSync.native(p)
151
158
  } catch {
152
159
  return path.resolve(p)
153
160
  }
@@ -156,8 +163,10 @@ function makeSpecHelpers({ program = 'spec-sync' } = {}) {
156
163
  const byName = new Map(here.map((s) => [s.spec, s]))
157
164
  for (const listed of liveWorktreePaths(git)) {
158
165
  const tree = real(listed)
159
- if (tree === self) continue
160
- for (const s of listSpecs(tree, config)) {
166
+ // The project folder inside this worktree — where its specs are.
167
+ const project = real(projectIn(listed, prefix))
168
+ if (project === self) continue
169
+ for (const s of listSpecs(project, config)) {
161
170
  let own = null
162
171
  try {
163
172
  own = real(resolveSpec(s.spec, primary, env.config, { searchDirs: [tree] }).worktreePath)
@@ -227,7 +236,9 @@ function makeSpecHelpers({ program = 'spec-sync' } = {}) {
227
236
  bad++
228
237
  continue
229
238
  }
230
- const r = compareStored(sent, got, config)
239
+ // Summary mode compares the block alone: the text around it is the
240
+ // team's. Right after a write a missing block IS a loss, so it reads as ''.
241
+ const r = compareStored(sent, comparableDescription(got, config) ?? '', config)
231
242
  if (r.ok) continue
232
243
  bad++
233
244
  lines.push(
@@ -0,0 +1,64 @@
1
+ 'use strict'
2
+
3
+ /**
4
+ * `spec-sync splice <spec> --live <file> [--phase <ref>]` — the body to write,
5
+ * for an apply the ENGINE is not doing (the skills' MCP path).
6
+ *
7
+ * Under `mapping.description: "summary"` a plan carries the block alone, and
8
+ * writing that over the whole description would delete the team's text around
9
+ * it. So the skill reads the live body, hands it here, and writes back exactly
10
+ * what this prints — the splice is the engine's, never composed in a skill.
11
+ * In `spec` mode it prints the projection as it is: the whole body is the
12
+ * repo's there.
13
+ *
14
+ * Exit codes: 0 with the body on stdout; 1 when nothing must be written — a
15
+ * damaged block (a delimiter someone edited), an unknown phase ref, or a live
16
+ * file that could not be read. Nothing is printed to stdout then, so a caller
17
+ * that pipes stdout into a write can never write a partial or empty body.
18
+ */
19
+
20
+ const fs = require('node:fs')
21
+
22
+ const { projectionOf, descriptionMode, spliceBlock } = require('../../sync-core')
23
+
24
+ function spliceBody(snapshotDir, config, live, phaseRef) {
25
+ const projection = projectionOf(snapshotDir, config)
26
+ let planned = projection.description
27
+ if (phaseRef) {
28
+ const want = String(phaseRef).replace(/\.md$/, '')
29
+ const sub = (projection.subIssues || []).find((s) => s.ref === want)
30
+ if (!sub) return { ok: false, reason: `no phase ${want} in the projection` }
31
+ planned = sub.goal
32
+ }
33
+ if (planned == null) return { ok: false, reason: 'the projection has no body for that object' }
34
+ if (descriptionMode(config) !== 'summary') return { ok: true, text: planned }
35
+ const text = spliceBlock(live, planned, config)
36
+ if (text == null) {
37
+ return { ok: false, reason: "its summary block's delimiters were edited — write nothing; repair them and re-run" }
38
+ }
39
+ return { ok: true, text }
40
+ }
41
+
42
+ function specSyncSplice({ snapshotDir, config, flags, out, err, program = 'spec-sync' }) {
43
+ const say = (msg) => (err || out).write(`${program} splice: ${msg}\n`)
44
+ if (!flags.live) {
45
+ say('pass --live <file> holding the description the tracker has now (an empty file for a new issue)')
46
+ return 1
47
+ }
48
+ let live
49
+ try {
50
+ live = fs.readFileSync(flags.live, 'utf-8')
51
+ } catch (error) {
52
+ say(`cannot read --live: ${error.message}`)
53
+ return 1
54
+ }
55
+ const r = spliceBody(snapshotDir, config, live, flags.phase)
56
+ if (!r.ok) {
57
+ say(r.reason)
58
+ return 1
59
+ }
60
+ out.write(r.text)
61
+ return 0
62
+ }
63
+
64
+ module.exports = { spliceBody, specSyncSplice }
@@ -0,0 +1,137 @@
1
+ 'use strict'
2
+
3
+ /**
4
+ * `readStatus` — what the tracker says about one spec's ticket, read live.
5
+ *
6
+ * Under `sync.fieldOwnership: "pull"` the tracker is the record for status and
7
+ * assignee, so the repo reads them when it needs to SAY something and never
8
+ * stores what it read. Every provider's adapter already answers `readIssue`
9
+ * with the same normalised shape — `state: { name }`, `assignee: { id, name }`
10
+ * — and each provider's `config.remote.stateName` hook reads its own status
11
+ * (GitHub's board column, Azure's System.State), so one function serves all
12
+ * four.
13
+ *
14
+ * THREE ANSWERS, and the third is most of them: a reading, a reading whose
15
+ * state maps to no bucket (`bucket: null` — somewhere the repo does not manage,
16
+ * never a disagreement), and cannot-tell. No adapter, no credential, a network
17
+ * failure and a missing ticket are all cannot-tell; none is evidence about the
18
+ * spec, so a caller that accuses on one is wrong (`negative-checks.md`).
19
+ */
20
+
21
+ const path = require('node:path')
22
+
23
+ const { remoteStateReading, ownershipOf } = require('../../sync-core')
24
+ const { makeSpecHelpers } = require('./specs.js')
25
+ const { boardDisagreement } = require('./list-rows.js')
26
+ const { doctorRow } = require('./doctor.js')
27
+
28
+ const firstLine = (error) => String((error && error.message) || error).split('\n')[0]
29
+
30
+ /**
31
+ * @param {object} p
32
+ * - `adapter` an API adapter with `readIssue`
33
+ * - `ref` the ticket's identifier, as the adapter takes it
34
+ * - `config` the provider config (for the state mapping)
35
+ * @returns {Promise<{ ok: true, state: string|null, bucket: string|null, assignee: object|null }
36
+ * | { ok: false, reason: string }>}
37
+ */
38
+ async function readStatus({ adapter, ref, config }) {
39
+ if (!adapter || typeof adapter.readIssue !== 'function') return { ok: false, reason: 'no API adapter' }
40
+ if (!ref) return { ok: false, reason: 'not linked' }
41
+ let issue
42
+ try {
43
+ issue = await adapter.readIssue(ref)
44
+ } catch (error) {
45
+ return { ok: false, reason: firstLine(error) }
46
+ }
47
+ if (!issue) return { ok: false, reason: `${ref} not found` }
48
+ const reading = remoteStateReading(issue, config)
49
+ const assignee = issue.assignee && issue.assignee.id ? { id: issue.assignee.id, name: issue.assignee.name || null } : null
50
+ return {
51
+ ok: true,
52
+ state: reading ? reading.name : null,
53
+ bucket: reading && reading.mapped ? reading.bucket : null,
54
+ assignee,
55
+ }
56
+ }
57
+
58
+ /**
59
+ * `spec-sync ownership [--json]` — who owns a spec's status and assignee here.
60
+ *
61
+ * This is the question the shared skills ask before writing a `Status:` header,
62
+ * a `Developer:` line or a State-log row: the base skills are tracker-free and
63
+ * cannot read a provider config, so they ask the provider's CLI rather than
64
+ * deciding from which provider is installed. Offline, and always exit 0 — a
65
+ * missing config never reaches here (the CLI reports sync is off first), and
66
+ * that is the skills' cannot-tell, which writes the headers as before.
67
+ */
68
+ function specSyncOwnership(config, flags, out, program = 'spec-sync') {
69
+ const owners = { workflowState: ownershipOf(config, 'workflowState'), assignee: ownershipOf(config, 'assignee') }
70
+ if (flags && flags.json) {
71
+ out.write(JSON.stringify(owners, null, 2) + '\n')
72
+ return 0
73
+ }
74
+ out.write(`${program} ownership: status ${owners.workflowState} · assignee ${owners.assignee}\n`)
75
+ return 0
76
+ }
77
+
78
+ /**
79
+ * `spec-sync board <spec> [--json]` — has the board finished what this repo has
80
+ * not? Asked by `/spec-start` and `/spec-next` in pre-flight and by
81
+ * `/spec-status`, so a ticket someone Cancelled or closed as Done reaches the
82
+ * person holding the branch rather than waiting for them to look.
83
+ *
84
+ * SILENT UNLESS IT HAS SOMETHING TO SAY. One line when the board says Done or
85
+ * Cancelled against a spec still in `backlog`/`in-progress`, naming the command
86
+ * that closes it — and nothing at all otherwise: agreement, a board that merely
87
+ * re-planned, an unlinked spec, no credential, an unreadable ticket. Every one of
88
+ * those is either healthy or cannot-tell, and a line about it would teach the
89
+ * reader to skip the one line that matters (`negative-checks.md`). `--json`
90
+ * always answers, so a caller can tell the cases apart. Always exits 0: this
91
+ * reports, and nothing refuses on it.
92
+ *
93
+ * @param {object} p
94
+ * - `snapshotDir` the resolved spec folder (its bucket is its parent folder)
95
+ * - `config` the provider config
96
+ * - `credential` `{ ok, adapter, error }` — the provider's API adapter, or why not
97
+ * - `flags`, `out`, `tracker` (the name in messages), `program`
98
+ */
99
+ async function specSyncBoard({ snapshotDir, config, credential, flags = {}, out, tracker, program = 'spec-sync' }) {
100
+ const spec = path.basename(snapshotDir)
101
+ const bucket = path.basename(path.dirname(snapshotDir))
102
+ const overviewFile = (config.snapshot && config.snapshot.overviewFile) || '00-overview.md'
103
+ const ref = makeSpecHelpers({ program }).linkedIdentifier(path.join(snapshotDir, overviewFile), config)
104
+ const answer = (body, line) => {
105
+ if (flags.json) out.write(JSON.stringify({ spec, bucket, issue: ref || null, ...body }, null, 2) + '\n')
106
+ else if (line) out.write(`${program} board: ${line}\n`)
107
+ return 0
108
+ }
109
+
110
+ if (!ref) return answer({ reading: null, reason: 'not linked' })
111
+ if (!credential || !credential.ok) {
112
+ return answer({ reading: null, reason: (credential && credential.error ? String(credential.error) : 'no API transport').split('\n')[0] })
113
+ }
114
+ const reading = await readStatus({ adapter: credential.adapter, ref, config })
115
+ if (!reading.ok) return answer({ reading: null, reason: reading.reason })
116
+
117
+ const { ok, ...seen } = reading
118
+ const found = reading.bucket ? boardDisagreement(bucket, reading.bucket) : null
119
+ if (!found) return answer({ reading: seen, disagrees: false })
120
+ return answer(
121
+ { reading: seen, disagrees: true, cleanup: found.cleanup },
122
+ `${ref} is ${reading.state} on ${tracker}, but ${spec} is ${bucket} here — ${found.cleanup} closes it`,
123
+ )
124
+ }
125
+
126
+ /**
127
+ * The doctor's one line on ownership: who holds status and assignee here. Always
128
+ * `ok` — both answers are valid configurations, and the line exists so a reader
129
+ * can see which one is in force without opening the config.
130
+ */
131
+ function ownershipDoctorRow(config) {
132
+ const status = ownershipOf(config, 'workflowState')
133
+ const assignee = ownershipOf(config, 'assignee')
134
+ return doctorRow('ownership', 'Ownership', 'ok', `status ${status} · assignee ${assignee}`)
135
+ }
136
+
137
+ module.exports = { readStatus, specSyncOwnership, specSyncBoard, ownershipDoctorRow }
@@ -13,13 +13,14 @@
13
13
  * stored matches what was sent — it merges nothing (see `src/verify.js`).
14
14
  */
15
15
 
16
- const { ownsField, normalizeLocal, LIFECYCLE_BUCKETS, lintPhases, readSnapshot, parseFrontmatter, remoteWorkflowState, remoteStateReading, stateNamesFor, titleFromText, validateStates, stateSuggestions, effectiveStates, specHeaders, linkedIncident, phaseModeFor } = require('./src/normalize.js')
16
+ const { ownsField, ownershipOf, normalizeLocal, LIFECYCLE_BUCKETS, lintPhases, readSnapshot, parseFrontmatter, remoteWorkflowState, remoteStateReading, stateNamesFor, titleFromText, validateStates, stateSuggestions, effectiveStates, specHeaders, linkedIncident, phaseModeFor } = require('./src/normalize.js')
17
17
  const { planChanges, snapshotOf, isEmptyPlan, hashField, stableStringify, remoteDescriptionEdited, remoteSubIssueEdited } = require('./src/compare.js')
18
18
  const { readBase, writeBase } = require('./src/base.js')
19
19
  const { push, recordPush, projectionOf } = require('./src/push.js')
20
20
  const { writeFrontmatter, deleteFrontmatter, stampSubIssueId, stampIssueId, findPhaseFileByTitle, listPhaseFiles } = require('./src/write.js')
21
21
  const { detectLegacyMirror } = require('./src/legacy.js')
22
22
  const { compareStored, stream } = require('./src/verify.js')
23
+ const { descriptionMode, delimitersFor, blockOf, wrapBlock, spliceBlock, comparableDescription, progressOf, DELIMITERS } = require('./src/summary.js')
23
24
  const { identityDialect, dialectOf } = require('./src/dialect.js')
24
25
  const { fieldsOf } = require('./src/fields.js')
25
26
  const { renderTaskBlock, findTaskBlocks, wrapEmphasisAware, collapseHyphenAware, inferWidth, fenceMask, DEFAULT_WIDTH } = require('./src/task-block.js')
@@ -27,6 +28,7 @@ const { planRetarget, applyRetarget, deriveRecordedKey, isEmptyRetarget, dirtyPa
27
28
 
28
29
  module.exports = {
29
30
  ownsField,
31
+ ownershipOf,
30
32
  normalizeLocal,
31
33
  // Exported for `spec-sync list`: an `inline`-mode spec has no phase sub-issues
32
34
  // to read, so the listing must resolve the mode rather than assume `subissue`.
@@ -61,6 +63,17 @@ module.exports = {
61
63
  listPhaseFiles,
62
64
  detectLegacyMirror,
63
65
  compareStored,
66
+ // The summary block: what a ticket carries under `mapping.description:
67
+ // "summary"`, and the splice that writes it beside the team's own text.
68
+ descriptionMode,
69
+ delimitersFor,
70
+ blockOf,
71
+ wrapBlock,
72
+ spliceBlock,
73
+ comparableDescription,
74
+ // How far along a spec is, from its own checkboxes (null: no checkboxes).
75
+ progressOf,
76
+ DELIMITERS,
64
77
  // The tolerant reduction behind both `compareStored` and the snapshot's
65
78
  // `descriptionStream` hash — exported so a provider can reduce a read-back the
66
79
  // same way rather than writing a second one that disagrees.
@@ -24,6 +24,7 @@ const { createHash } = require('node:crypto')
24
24
  // two reductions that disagree would be two different answers to one question.
25
25
  // Dialect-parameterised: the provider's `config.dialect` names the transforms.
26
26
  const { stream } = require('./verify.js')
27
+ const { comparableDescription } = require('./summary.js')
27
28
 
28
29
  // Deterministic JSON: object keys sorted recursively; array order preserved.
29
30
  // undefined normalises to null.
@@ -132,7 +133,10 @@ function remoteDescriptionEdited(snapshot, remote, config) {
132
133
  if (!remote || typeof remote !== 'object') return null
133
134
  // A provider whose remote shape differs supplies `config.remote.description`.
134
135
  const hook = config && config.remote && config.remote.description
135
- const text = typeof hook === 'function' ? hook(remote) : 'description' in remote ? remote.description : undefined
136
+ const raw = typeof hook === 'function' ? hook(remote) : 'description' in remote ? remote.description : undefined
137
+ // In summary mode only the block is the repo's: text around it is the team's
138
+ // and is never drift. A block that is missing or damaged is cannot-tell.
139
+ const text = comparableDescription(raw, config)
136
140
  if (typeof text !== 'string') return null
137
141
 
138
142
  return hashField(stream(text, config)) !== recorded
@@ -194,6 +198,49 @@ function snapshotOf(projection, config) {
194
198
  }
195
199
  }
196
200
 
201
+ /**
202
+ * The `stateNames` record for a snapshot: the tracker state name each item was
203
+ * last SENT, `{ issue, subIssues: { <id>: name } }`, or null when there is
204
+ * nothing to record (no provider hook, nothing ever sent).
205
+ *
206
+ * An item this push sent a state for (`sent`) records today's resolution. Any
207
+ * other item keeps the name the previous snapshot had for it, or gets none —
208
+ * the absence `planChanges` reads as cannot-tell. Writing today's name for an
209
+ * item that was not sent would record a claim about the tracker nobody made.
210
+ *
211
+ * @param {object} projection the projection, carrying `stateName`s
212
+ * @param {object|null} previous the snapshot being replaced
213
+ * @param {{ issue?: boolean, subIssues?: Set<string> }|null} sent
214
+ */
215
+ function stateNamesRecord(projection, previous, sent) {
216
+ const p = projection || {}
217
+ const before = (previous && previous.stateNames) || {}
218
+ const beforeSubs = before.subIssues || {}
219
+ const sentSubs = (sent && sent.subIssues) || new Set()
220
+ const has = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key)
221
+ const out = { subIssues: {} }
222
+ if (sent && sent.issue && p.stateName !== undefined) out.issue = p.stateName
223
+ else if (has(before, 'issue')) out.issue = before.issue
224
+ for (const s of p.subIssues || []) {
225
+ if (!s || s.id == null) continue
226
+ const id = String(s.id)
227
+ if (sentSubs.has(id) && s.stateName !== undefined) out.subIssues[id] = s.stateName
228
+ else if (has(beforeSubs, id)) out.subIssues[id] = beforeSubs[id]
229
+ }
230
+ if (!has(out, 'issue') && !Object.keys(out.subIssues).length) return null
231
+ return out
232
+ }
233
+
234
+ // Has the state an unchanged item maps to moved under it — a state-map edit in
235
+ // the config rather than a move of the spec? Only a RECORDED name can say: an
236
+ // item with none is cannot-tell and plans nothing, so an upgrade or a config
237
+ // change never turns into a workspace-wide resend. A bucket that now sends no
238
+ // state (`null`) has nothing to resend.
239
+ function remapped(recorded, current) {
240
+ if (recorded === undefined || current === undefined || current === null) return false
241
+ return recorded !== current
242
+ }
243
+
197
244
  /**
198
245
  * Diff the local projection against the last-pushed snapshot.
199
246
  * @returns {{ issue?: object, subIssues: {create,update} }}
@@ -205,10 +252,13 @@ function snapshotOf(projection, config) {
205
252
  * `plan.issue` (when present) is the spec issue's description + state; the push
206
253
  * skill applies its provider's project/grouping choice on top of it.
207
254
  */
208
- function planChanges(projection, snapshot) {
255
+ function planChanges(projection, snapshot, { linked = false } = {}) {
209
256
  const p = projection || {}
210
257
  const snap = snapshot || {}
211
258
  const snapS = snap.subIssues || {}
259
+ const names = snap.stateNames || {}
260
+ const recordedSub = (id) =>
261
+ names.subIssues && Object.prototype.hasOwnProperty.call(names.subIssues, id) ? names.subIssues[id] : undefined
212
262
 
213
263
  // Ids the last push minted that no phase claims any more. A phase file's stamp
214
264
  // is the only link back to its sub-issue, and it lives in frontmatter — so a
@@ -235,13 +285,21 @@ function planChanges(projection, snapshot) {
235
285
  subIssues.create.push({ ref: s.ref, name: s.name, goal: s.goal, state: s.state })
236
286
  }
237
287
  } else if (snapS[String(s.id)] !== subIssueHash(s)) {
238
- subIssues.update.push({ ref: s.ref, id: s.id, name: s.name, goal: s.goal, state: s.state })
288
+ const update = { ref: s.ref, id: s.id, name: s.name, goal: s.goal, state: s.state }
289
+ // No hash on record for an id the spec carries: the snapshot was lost or
290
+ // predates it, so this is a resend, not a move the spec made.
291
+ if (snapS[String(s.id)] === undefined) update.stateResend = 'unknown'
292
+ subIssues.update.push(update)
293
+ } else if (remapped(recordedSub(String(s.id)), s.stateName)) {
294
+ // STATE ONLY: the phase itself is unchanged, so its title and body stay
295
+ // as they are on the tracker.
296
+ subIssues.update.push({ ref: s.ref, id: s.id, state: s.state, stateResend: 'remap' })
239
297
  }
240
298
  }
241
299
 
242
300
  const plan = { subIssues }
243
301
  if (unstamped.length) plan.unstamped = unstamped
244
- const issue = issueChanges(p, snap)
302
+ const issue = issueChanges(p, snap, { linked })
245
303
  if (issue) plan.issue = issue
246
304
  return plan
247
305
  }
@@ -259,11 +317,22 @@ function planChanges(projection, snapshot) {
259
317
  * that is the failure worth avoiding. The push rewrites the snapshot in the new
260
318
  * shape, so a spec passes through `unknown` exactly once.
261
319
  */
262
- function issueChanges(projection, snapshot) {
320
+ function issueChanges(projection, snapshot, { linked = false } = {}) {
263
321
  const p = projection || {}
264
322
  const snap = snapshot || {}
265
323
  const both = () => {
266
- const out = { description: p.description ?? null, state: p.status ?? null }
324
+ const out = { description: p.description ?? null }
325
+ // UNDER `pull`, THE UNKNOWN PATH SENDS NO STATE. Without split hashes there
326
+ // is no positive signal that the spec moved, and the tracker owns the state
327
+ // — so the harmless reading of "cannot tell" flips: re-asserting would drag
328
+ // back a ticket someone moved on the board. Only a CREATE still sends it,
329
+ // because an issue with no state yet gets its first one from the repo.
330
+ // `linked` is what tells the two apart: an adopted issue has no snapshot
331
+ // either, and its board status is a person's, not ours.
332
+ if (!p.statePulled || !linked) out.state = p.status ?? null
333
+ // A linked issue with no split hashes is a resend: nothing says the spec
334
+ // moved, so the apply must not drag the issue out of a later state.
335
+ if (linked && out.state != null) out.stateResend = 'unknown'
267
336
  // ASSERT, NEVER CLEAR, on this path. There are no split hashes here, so
268
337
  // whether an assignee was ever pushed is unknown — and the harmless reading
269
338
  // of "unknown" is to send one we have and stay silent about one we don't.
@@ -290,6 +359,11 @@ function issueChanges(projection, snapshot) {
290
359
  const changed = {}
291
360
  if (fields.description !== want.description) changed.description = p.description ?? null
292
361
  if (fields.state !== want.state) changed.state = p.status ?? null
362
+ else if (!p.statePulled && remapped(snap.stateNames && snap.stateNames.issue, p.stateName)) {
363
+ // The tracker owns a pulled state, so a remap never re-asserts it there.
364
+ changed.state = p.status ?? null
365
+ changed.stateResend = 'remap'
366
+ }
293
367
 
294
368
  // ASSIGNEE — AN ABSENT SNAPSHOT KEY MEANS "NEVER PUSHED", NOT "WAS NULL".
295
369
  //
@@ -330,6 +404,7 @@ module.exports = {
330
404
  issueChanges,
331
405
  specIssueFieldHashes,
332
406
  snapshotOf,
407
+ stateNamesRecord,
333
408
  isEmptyPlan,
334
409
  hashField,
335
410
  stableStringify,