@warren-dean/code-kit 0.34.0 → 0.36.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.
@@ -12,6 +12,7 @@ import { matchesAny } from './glob.mjs';
12
12
  import { CLI, projectWorktrees } from './rules.mjs';
13
13
  import { shortSession } from './laneclaims.mjs';
14
14
  import { isHandle } from './teamfacts.mjs';
15
+ import { hasStreams, otherStreamsPlan, otherStreamsSpec } from './streams.mjs';
15
16
 
16
17
  export { shortSession };
17
18
  export const SESSIONS_DIR = '.claude/state/sessions';
@@ -100,9 +101,37 @@ export function sessions(root, now = Date.now()) {
100
101
  .sort((a, b) => Date.parse(b.started) - Date.parse(a.started));
101
102
  }
102
103
 
103
- /** SESS-2: the live lead session, or null. */
104
- export const leadSession = (root, now = Date.now()) =>
105
- sessions(root, now).find((s) => s.live && s.role === 'lead') ?? null;
104
+ const leads = (root, now) => sessions(root, now).filter((s) => s.live && s.role === 'lead');
105
+
106
+ /**
107
+ * SESS-2, STRM-2: the live lead session of `stream`, or null: the session leading that stream, or else
108
+ * one leading with no stream of its own, which leads every stream that has no lead (and the whole project
109
+ * without streams).
110
+ */
111
+ export const leadSession = (root, now = Date.now(), stream = null) => {
112
+ const live = leads(root, now);
113
+ return (
114
+ (stream ? live.find((s) => (s.stream ?? null) === stream) : null) ??
115
+ live.find((s) => !s.stream) ??
116
+ (stream ? null : (live[0] ?? null))
117
+ );
118
+ };
119
+
120
+ /** STRM-2: the live session leading exactly `stream` (null: leading with no stream of its own), or null. */
121
+ const ownLead = (root, now, stream) =>
122
+ leads(root, now).find((s) => (s.stream ?? null) === (stream ?? null)) ?? null;
123
+
124
+ /** STRM-2: every live lead session: [{ ...record }], the longest-leading first. */
125
+ export const leadSessions = (root, now = Date.now()) =>
126
+ leads(root, now).sort(
127
+ (a, b) => Date.parse(a.leadSince ?? a.started) - Date.parse(b.leadSince ?? b.started),
128
+ );
129
+
130
+ /**
131
+ * STRM-2: the lead that writes in the main checkout: the one leading longest. Every other stream's lead
132
+ * works in a worktree of its own.
133
+ */
134
+ export const mainCheckoutLead = (root, now = Date.now()) => leadSessions(root, now)[0] ?? null;
106
135
 
107
136
  /**
108
137
  * SESS-2: a session starting (or resumed). It's the lead when no other live session is; otherwise a
@@ -113,12 +142,19 @@ export const leadSession = (root, now = Date.now()) =>
113
142
  export function startSession(root, id, now = Date.now(), { model = null } = {}) {
114
143
  const at = new Date(now).toISOString();
115
144
  const had = readSession(root, id);
116
- const lead = leadSession(root, now);
145
+ // STRM-2: a session of a stream leads it when nobody else does; one with no stream yet leads only when
146
+ // no session leads anything.
147
+ const stream = had?.stream ?? null;
148
+ const lead = stream ? ownLead(root, now, stream) : (leads(root, now)[0] ?? null);
149
+ const role = lead && lead.id !== id ? 'working' : 'lead';
117
150
  return write(root, {
118
151
  id,
119
152
  person: had?.person ?? personHere(root),
120
153
  login: loginHere(root) ?? had?.login ?? null,
121
- role: lead && lead.id !== id ? 'working' : 'lead',
154
+ stream,
155
+ role,
156
+ leadSince:
157
+ role === 'lead' ? (had?.role === 'lead' && had.leadSince ? had.leadSince : at) : null,
122
158
  started: had?.started ?? at,
123
159
  seen: at,
124
160
  ended: null,
@@ -138,15 +174,15 @@ export function seeSession(root, id, now = Date.now(), facts = () => ({})) {
138
174
  if (!id) return null;
139
175
  const had = readSession(root, id);
140
176
  if (!had || had.ended) return startSession(root, id, now, facts());
141
- // A lead that went quiet past SESSION_LIVE_MS, while another session took the lead, works now.
142
- const lead = had.role === 'lead' ? leadSession(root, now) : null;
177
+ // A lead that went quiet past SESSION_LIVE_MS, while another session took its stream's lead, works now.
178
+ const lead = had.role === 'lead' ? ownLead(root, now, had.stream ?? null) : null;
143
179
  const demoted = lead && lead.id !== id;
144
180
  if (!demoted && now - Date.parse(had.seen) < SEEN_EVERY_MS) return had;
145
181
  const { model } = facts();
146
182
  return write(root, {
147
183
  ...had,
148
184
  seen: new Date(now).toISOString(),
149
- ...(demoted ? { role: 'working' } : {}),
185
+ ...(demoted ? { role: 'working', leadSince: null } : {}),
150
186
  ...(model ? { model } : {}),
151
187
  });
152
188
  }
@@ -170,12 +206,35 @@ export function endSession(root, id, now = Date.now()) {
170
206
  return write(root, { ...had, ended: new Date(now).toISOString() });
171
207
  }
172
208
 
173
- /** SESS-2: the person chose this session to lead: it does, and the session that led becomes a working one. */
174
- export function makeLead(root, id, now = Date.now()) {
209
+ /**
210
+ * SESS-2, STRM-2: the person chose this session to lead `stream` (or, with none, the project, or the
211
+ * stream it already belongs to): it does, and the session that led that stream becomes a working one.
212
+ * The leads of other streams lead on.
213
+ */
214
+ export function makeLead(root, id, now = Date.now(), stream = undefined) {
215
+ const had = readSession(root, id) ?? startSession(root, id, now);
216
+ const mine = stream === undefined ? (had.stream ?? null) : stream;
175
217
  for (const s of sessions(root, now))
176
- if (s.role === 'lead' && s.id !== id) write(root, { ...strip(s), role: 'working' });
218
+ if (s.role === 'lead' && s.id !== id && (s.stream ?? null) === mine)
219
+ write(root, { ...strip(s), role: 'working', leadSince: null });
220
+ const at = new Date(now).toISOString();
221
+ return write(root, {
222
+ ...had,
223
+ stream: mine,
224
+ role: 'lead',
225
+ leadSince:
226
+ had.role === 'lead' && (had.stream ?? null) === mine && had.leadSince ? had.leadSince : at,
227
+ seen: at,
228
+ ended: null,
229
+ });
230
+ }
231
+
232
+ /** STRM-2: a working session joins `stream`: its task and next step are that stream's. */
233
+ export function joinStream(root, id, stream, now = Date.now()) {
177
234
  const had = readSession(root, id) ?? startSession(root, id, now);
178
- return write(root, { ...had, role: 'lead', seen: new Date(now).toISOString(), ended: null });
235
+ if (had.role === 'lead' && (had.stream ?? null) !== stream)
236
+ return makeLead(root, id, now, stream);
237
+ return write(root, { ...had, stream });
179
238
  }
180
239
 
181
240
  const strip = ({ live: _live, ...r }) => r;
@@ -254,10 +313,35 @@ export function sessionWriteProblem({ project, root, rel, actor, session, now =
254
313
  const leased = taskRefusal(project, session, rel, now);
255
314
  if (leased) return leased;
256
315
  const me = readSession(project, session);
257
- if (actor?.kind !== 'lead' || me?.role !== 'working') return null;
316
+ if (actor?.kind !== 'lead') return null;
317
+ // STRM-2: one lead writes in the main checkout; every other stream's lead works in its own worktree.
318
+ if (me?.role === 'lead' && root === main(project)) {
319
+ const holder = mainCheckoutLead(project, now);
320
+ if (holder && holder.id !== session)
321
+ return `${rel} is in the main checkout, where the ${holder.stream ?? 'project'} lead (${memberOf(holder)}) works: two leads in one checkout block each other's git. Lead the ${me.stream ?? 'project'} stream from a worktree of your own on its lead branch (lead/${me.stream ?? 'work'}): start the session with \`claude --worktree\`, or move it into one (EnterWorktree).`;
322
+ return null;
323
+ }
324
+ if (me?.role !== 'working') return null;
258
325
  if (root === main(project))
259
326
  return `this is a working session (another session leads the project), and ${rel} is in the main checkout, which every session shares: your uncommitted files there would block the other sessions' git. Work in a worktree of your own: start the session with \`claude --worktree\`, or move it into one (EnterWorktree), then record your task and go on.`;
260
327
  if (!me.task)
261
328
  return `this is a working session (another session leads the project): record what you're doing before you change code, so the other sessions see it and leave your files alone:\n node "${CLI}" task "<what you're doing, in a line>" --touches "<globs of the paths you'll change>"`;
262
329
  return null;
263
330
  }
331
+
332
+ /**
333
+ * STRM-4: why a stream's lead may not write `rel`: another stream's plan or spec is that stream's
334
+ * lead's. A lead with no stream of its own, and every other actor, are judged as before.
335
+ */
336
+ export function streamWriteProblem(project, config, actor, rel, session, now = Date.now()) {
337
+ if (actor?.kind !== 'lead' || !session || !rel || !hasStreams(config)) return null;
338
+ const me = readSession(project, session);
339
+ if (me?.role !== 'lead') return null;
340
+ const theirs =
341
+ otherStreamsPlan(config, rel, me.stream) ?? otherStreamsSpec(config, rel, me.stream);
342
+ if (!theirs) return null;
343
+ const lead = leadSession(project, now, theirs);
344
+ // A lead with no stream of its own writes the plans of the streams without a lead of theirs.
345
+ if (!me.stream && !(lead?.stream === theirs && lead.id !== session)) return null;
346
+ return `${rel} is the ${theirs} stream's${lead && lead.stream === theirs ? `, led by ${memberOf(lead)}` : ''}, and this session leads ${me.stream ?? 'the streams without a lead of their own'}. Each stream's lead writes its own plan and specs. Ask the ${theirs} lead for the change, or, for something both streams need from core, \`node "${CLI}" core ask "<what>" --story <ST-n>\`.`;
347
+ }
@@ -3,23 +3,28 @@
3
3
  // (`git commit`, `code-kit merge`) look only at the simple commands it runs, each from its own start.
4
4
  // Rules about text the command carries (a commit trailer, a path in a redirect) still read it whole.
5
5
 
6
- /** The command with each heredoc's body taken out: the lines after `<<WORD` up to the line `WORD`. */
7
- export function withoutHeredocs(cmd) {
8
- const out = [];
6
+ /** The command's lines and its heredocs' bodies apart: a body is the lines after `<<WORD` up to the line `WORD`. */
7
+ function heredocsApart(cmd) {
8
+ const kept = [];
9
+ const bodies = [];
9
10
  let until = null;
10
11
  for (const line of String(cmd).split('\n')) {
11
12
  if (until) {
12
13
  if (line.trim() === until) until = null;
14
+ else bodies.push(line);
13
15
  continue;
14
16
  }
15
- out.push(line);
17
+ kept.push(line);
16
18
  // `<<WORD`, `<<-WORD`, `<<'WORD'` or `<<"WORD"`; not a `<<<` here-string, whose text is on the line.
17
19
  const m = line.match(/(?<!<)<<-?\s*(['"]?)([\w.-]+)\1(?!<)/);
18
20
  if (m && !line.includes('<<<')) until = m[2];
19
21
  }
20
- return out.join('\n');
22
+ return { kept: kept.join('\n'), bodies: bodies.join('\n') };
21
23
  }
22
24
 
25
+ /** The command with each heredoc's body taken out: the lines after `<<WORD` up to the line `WORD`. */
26
+ export const withoutHeredocs = (cmd) => heredocsApart(cmd).kept;
27
+
23
28
  /** `text` with every quoted character replaced by `_`, the quotes kept: same length, nothing inside to match. */
24
29
  export function maskQuotes(text) {
25
30
  let out = '';
@@ -113,7 +118,7 @@ const READERS = [
113
118
  /^(?:cd|pwd|cat|head|tail|wc|grep|egrep|fgrep|cut|jq|nl|tr|ls|stat|diff|cmp|echo|printf|true)(?:\s|$)/,
114
119
  // less with no log file of what it shows.
115
120
  /^(?!.*\s(?:-[a-zA-Z]*[oO]|--log-file\b|--LOG-FILE\b))less(?:\s|$)/,
116
- /^(?!.*\s(?:--output\b|-O|--open-files-in-pager\b))git(?:\s+(?:-C\s+\S+|--no-pager|-P))*\s+(?:diff|log|show|blame|grep|status|cat-file|ls-files|shortlog|rev-parse)(?:\s|$)/,
121
+ /^(?!.*\s(?:--output\b|-O|--open-files-in-pager\b))git(?:\s+(?:-C\s+\S+|--no-pager|-P))*\s+(?:diff|log|show|blame|grep|status|cat-file|ls-files|ls-tree|shortlog|rev-parse|rev-list|merge-base|check-ignore|check-attr|describe|name-rev|show-ref|for-each-ref|cherry)(?:\s|$)/,
117
122
  // git branch only listing branches or naming the current one: no name to create, move or delete.
118
123
  /^git(?:\s+(?:-C\s+\S+|--no-pager|-P))*\s+branch(?:\s+(?:--show-current|--list|-l|-a|--all|-r|--remotes|-vv?|--verbose|--no-color|--color|--merged|--no-merged))*\s*$/,
119
124
  // rg with no preprocessor; sort with no output file or compressor.
@@ -129,7 +134,7 @@ const CODE_KIT_READS = new RegExp(
129
134
  );
130
135
 
131
136
  /** A command's words, quotes taken off. */
132
- const wordsOf = (text) =>
137
+ export const wordsOf = (text) =>
133
138
  (text.match(/'[^']*'|"(?:\\.|[^"\\])*"|\S+/g) ?? []).map((w) =>
134
139
  w.replace(/^(['"])(.*)\1$/s, '$2'),
135
140
  );
@@ -281,6 +286,16 @@ const REDEFINES =
281
286
  /(?:^|[;&|\n(]\s*)(?:[\w.-]+\s*\(\s*\)|function\s|alias\s|unalias\s|source\s|\.\s|hash\s|enable\s|builtin\s|set\s|setopt\s|shopt\s|unset\s|export\s|typeset\s|declare\s|local\s|readonly\s)/;
282
287
  const SHELL_READS =
283
288
  /^(?:PATH|path|FPATH|fpath|CDPATH|cdpath|IFS|ENV|BASH_ENV|ZDOTDIR|HOME|LD_\w*|DYLD_\w*|GIT_\w*|XDG_\w*)$/;
289
+ // A function defined in the line: `name() {` or `function name`. One that no reading part calls can't
290
+ // change what that part runs; what its body runs is judged as the line's other commands are.
291
+ const DEFINES_FUNCTION =
292
+ /(?:^|[;&|\n(]\s*)(?:function\s+([\w.-]+)(?:\s*\(\s*\))?|([\w.-]+)\s*\(\s*\))/g;
293
+ function definedFunctions(code) {
294
+ const names = [...code.matchAll(DEFINES_FUNCTION)].map(([, a, b]) => a ?? b);
295
+ // What else the line redefines, a function's body counted, since a call runs it.
296
+ const rest = code.replace(DEFINES_FUNCTION, ';').replace(/[{}]/g, ';');
297
+ return { names, rest };
298
+ }
284
299
  // Any other variable set in the line (`CK=…/code-kit.mjs`) stays in the shell: no command it runs sees
285
300
  // it, unless it was exported already, and what names it is judged on its own.
286
301
  const setsWhatRuns = (code) =>
@@ -290,15 +305,23 @@ const setsWhatRuns = (code) =>
290
305
 
291
306
  /**
292
307
  * The parts of `cmd` that name `pattern`, each a pipeline (`a | b`) of its own, that don't only read
293
- * (readsOnly): what a rule for a file only reads may hold. A line with a heredoc, or one that could
294
- * change what its commands run (REDEFINES), is one part, judged whole.
308
+ * (readsOnly): what a rule for a file only reads may hold. A line with a heredoc whose body names
309
+ * `pattern`, or one that could change what its commands run (REDEFINES), is one part, judged whole; a
310
+ * heredoc that doesn't name it is judged like any other command that doesn't, and so is a function
311
+ * defined, unless a part that names `pattern` calls it.
295
312
  */
296
313
  export function unreadNames(cmd, pattern) {
297
314
  const read = withoutHarmlessRedirects(cmd);
298
315
  const code = codeOf(read);
299
316
  if (!pattern.test(cmd)) return [];
300
- if (/<</.test(cmd) || REDEFINES.test(code) || setsWhatRuns(code))
317
+ const functions = definedFunctions(code);
318
+ if (
319
+ pattern.test(heredocsApart(cmd).bodies) ||
320
+ REDEFINES.test(functions.rest) ||
321
+ setsWhatRuns(code)
322
+ )
301
323
  return readsOnly(cmd) ? [] : [cmd];
324
+ const calls = (p) => commandsOf(p).some(({ text: t }) => functions.names.includes(wordsOf(t)[0]));
302
325
  const text = withoutHeredocs(read);
303
326
  const parts = [];
304
327
  let start = 0;
@@ -319,7 +342,9 @@ export function unreadNames(cmd, pattern) {
319
342
  new RegExp(String.raw`^${GIT}(?:commit|merge|revert|cherry-pick|rebase|am|pull)(?![\w-])`),
320
343
  );
321
344
  return parts.filter(
322
- (p) => pattern.test(p) && !readsOnly(p) && !(restores && restoresFromHead(p, pattern)),
345
+ (p) =>
346
+ pattern.test(p) &&
347
+ (calls(p) || (!readsOnly(p) && !(restores && restoresFromHead(p, pattern)))),
323
348
  );
324
349
  }
325
350
 
@@ -0,0 +1,80 @@
1
+ // The config's streams checked (docs/specs/31-streams-and-platform.md, STRM-1, STRM-4, STRM-5), on their
2
+ // own so the config's loader reads them without the rest of the stream model.
3
+ export const CORE = 'core';
4
+ const isObj = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
5
+
6
+ /** STRM-1, STRM-4, STRM-5: what's wrong with the config's streams, in its words. */
7
+ export function streamProblems(c) {
8
+ if (c.streams === undefined) {
9
+ const tagged = (Array.isArray(c.layers) ? c.layers : []).filter((l) => l?.stream !== undefined);
10
+ return tagged.length
11
+ ? [
12
+ `layers ${tagged.map((l) => `"${l.name}"`).join(', ')} name a stream, but there's no "streams"`,
13
+ ]
14
+ : [];
15
+ }
16
+ if (!isObj(c.streams) || !Object.keys(c.streams).length)
17
+ return ['"streams" must name each stream: { "<name>": { "lanes", "plan" } }'];
18
+ const p = [];
19
+ const lanes = Object.keys(isObj(c.lanes) ? c.lanes : {});
20
+ const owner = new Map();
21
+ const plans = [];
22
+ for (const [name, s] of Object.entries(c.streams)) {
23
+ const at = `streams.${name}`;
24
+ if (!/^[a-z][a-z0-9-]*$/.test(name) || name === CORE) {
25
+ p.push(`${at}: a stream's name is short and lower-case, and isn't "${CORE}"`);
26
+ continue;
27
+ }
28
+ if (!isObj(s)) {
29
+ p.push(`${at} must be an object`);
30
+ continue;
31
+ }
32
+ if (!Array.isArray(s.lanes) || !s.lanes.every((l) => typeof l === 'string'))
33
+ p.push(`${at}.lanes must list the stream's lanes`);
34
+ for (const l of Array.isArray(s.lanes) ? s.lanes : []) {
35
+ if (!lanes.includes(l)) p.push(`${at}.lanes names an unknown lane "${l}"`);
36
+ else if (owner.has(l))
37
+ p.push(
38
+ `the lane "${l}" is in two streams, ${owner.get(l)} and ${name}: a lane is one stream's`,
39
+ );
40
+ else owner.set(l, name);
41
+ }
42
+ if (typeof s.plan !== 'string' || !s.plan)
43
+ p.push(`${at}.plan must be the stream's plan file (or folder)`);
44
+ else {
45
+ const under = c.docs?.plan;
46
+ if (under && !(s.plan === under || s.plan.startsWith(`${under.replace(/\/$/, '')}/`)))
47
+ p.push(`${at}.plan must be inside docs.plan (${under}), where code-kit reads the stories`);
48
+ plans.push([name, s.plan]);
49
+ }
50
+ if (
51
+ s.specs !== undefined &&
52
+ !(Array.isArray(s.specs) && s.specs.every((x) => typeof x === 'string'))
53
+ )
54
+ p.push(`${at}.specs must list the spec files the stream builds`);
55
+ if (s.platform !== undefined && typeof s.platform !== 'boolean')
56
+ p.push(`${at}.platform must be true or false`);
57
+ if (s.label !== undefined && (typeof s.label !== 'string' || s.label.length > 60))
58
+ p.push(`${at}.label must be a short name, at most 60 characters`);
59
+ }
60
+ for (const [a, pa] of plans)
61
+ for (const [b, pb] of plans)
62
+ if (a < b && (pa === pb || pa.startsWith(`${pb}/`) || pb.startsWith(`${pa}/`)))
63
+ p.push(`streams ${a} and ${b} share a plan (${pa}, ${pb}): each stream's plan is its own`);
64
+ const platforms = Object.entries(c.streams).filter(([, s]) => s?.platform === true);
65
+ if (platforms.length > 1)
66
+ p.push(
67
+ `only one stream owns core, but ${platforms.map(([n]) => n).join(' and ')} are platform`,
68
+ );
69
+ if (platforms.length === 1) {
70
+ const loose = lanes.filter((l) => !owner.has(l));
71
+ if (loose.length)
72
+ p.push(
73
+ `${loose.map((l) => `"${l}"`).join(', ')} ${loose.length === 1 ? 'is' : 'are'} in no stream; with a platform stream (${platforms[0][0]}), core's lanes are its: list ${loose.length === 1 ? 'it' : 'them'} under a stream`,
74
+ );
75
+ }
76
+ for (const [i, l] of (Array.isArray(c.layers) ? c.layers : []).entries())
77
+ if (l?.stream !== undefined && !Object.hasOwn(c.streams, l.stream))
78
+ p.push(`layers[${i}].stream names an unknown stream "${l.stream}"`);
79
+ return p;
80
+ }
@@ -0,0 +1,244 @@
1
+ // Streams and the platform (docs/specs/31-streams-and-platform.md, STRM-1 to STRM-8). A stream is a squad
2
+ // and the product line it builds: its own lead session, lanes, plan and specs. The code is one codebase:
3
+ // per technical layer, a core and a module per stream. A layer with `stream` is that stream's module; one
4
+ // without is core. A lane in no stream is a core lane the streams share, taken in turns; a stream with
5
+ // `platform: true` owns core instead. A project without `streams` is one stream holding every lane.
6
+ import { appendFileSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
7
+ import { dirname, join } from 'node:path';
8
+ import { matchesAny } from './glob.mjs';
9
+ import { layerOf } from './layers.mjs';
10
+ import { laneOf, projectWorktrees } from './rules.mjs';
11
+ import { CORE } from './streamconfig.mjs';
12
+
13
+ export { CORE, streamProblems } from './streamconfig.mjs';
14
+
15
+ export const TURNS_FILE = '.claude/state/lane-turns.json';
16
+ export const CORE_REQUESTS_FILE = '.claude/state/core-requests.jsonl';
17
+
18
+ const mainOf = (root) => projectWorktrees(root)[0] ?? root;
19
+ const isObj = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
20
+
21
+ /** STRM-1: the project's streams, in the config's order: [{ name, label, lanes, plan, specs, platform }]. */
22
+ export function streamsOf(config) {
23
+ if (!isObj(config?.streams)) return [];
24
+ return Object.entries(config.streams).map(([name, s]) => ({
25
+ name,
26
+ label: s?.label ?? name,
27
+ lanes: Array.isArray(s?.lanes) ? s.lanes : [],
28
+ plan: s?.plan ?? null,
29
+ specs: Array.isArray(s?.specs) ? s.specs : [],
30
+ platform: s?.platform === true,
31
+ }));
32
+ }
33
+
34
+ /** Whether the project is built as streams: false for one without `streams`, which works as before. */
35
+ export const hasStreams = (config) => streamsOf(config).length > 0;
36
+
37
+ /** STRM-6: the stream that owns core, or null. */
38
+ export const platformOf = (config) => streamsOf(config).find((s) => s.platform) ?? null;
39
+
40
+ /** The stream a lane belongs to, or null: a core lane the streams share, or a project without streams. */
41
+ export const streamOfLane = (config, lane) =>
42
+ streamsOf(config).find((s) => s.lanes.includes(lane))?.name ?? null;
43
+
44
+ /** STRM-6: the lanes the streams share (core's, with no platform stream): every lane in no stream. */
45
+ export function sharedLanes(config) {
46
+ if (!hasStreams(config)) return [];
47
+ return Object.keys(config.lanes ?? {}).filter((lane) => !streamOfLane(config, lane));
48
+ }
49
+
50
+ /** The stream whose plan holds the plan file `file`, or null. */
51
+ export function streamOfPlanFile(config, file) {
52
+ if (!file) return null;
53
+ return (
54
+ streamsOf(config).find(
55
+ (s) => s.plan && (file === s.plan || file.startsWith(`${s.plan.replace(/\/$/, '')}/`)),
56
+ )?.name ?? null
57
+ );
58
+ }
59
+
60
+ /**
61
+ * The stream a story belongs to: its lane's, or, for the lead's own stories, design stories and a shared
62
+ * core lane's, the stream whose plan holds it. Null in a project without streams.
63
+ */
64
+ export const streamOfStory = (config, story) =>
65
+ streamOfLane(config, story?.lane) ?? streamOfPlanFile(config, story?.file);
66
+
67
+ /**
68
+ * STRM-5: whose code a repository path is: a stream's name, `core`, or null outside every layer and lane.
69
+ * A layer says first (a module of a stream, or core); a file in no layer is its lane's stream's, or core's
70
+ * when its lane is shared.
71
+ */
72
+ export function ownerStreamOf(config, rel) {
73
+ if (!hasStreams(config)) return null;
74
+ const layer = layerOf(rel, config.layers ?? []);
75
+ if (layer) return layer.stream ?? CORE;
76
+ const lane = laneOf(rel, config);
77
+ if (!lane) return null;
78
+ return streamOfLane(config, lane) ?? CORE;
79
+ }
80
+
81
+ /** STRM-4: story ids in more than one plan file: [{ id, files }]. */
82
+ export function duplicateStories(stories) {
83
+ const files = new Map();
84
+ for (const s of stories) files.set(s.id, [...(files.get(s.id) ?? []), s.file]);
85
+ return [...files]
86
+ .filter(([, f]) => new Set(f).size > 1)
87
+ .map(([id, f]) => ({ id, files: [...new Set(f)] }));
88
+ }
89
+
90
+ /** STRM-4: the stream whose plan `rel` is, when it isn't `stream`'s own: its name, or null. */
91
+ export function otherStreamsPlan(config, rel, stream) {
92
+ const owner = streamOfPlanFile(config, rel);
93
+ return owner && owner !== stream ? owner : null;
94
+ }
95
+
96
+ /** STRM-4: whether a stream's own lead may write `rel`: the spec files of other streams stay theirs. */
97
+ export function otherStreamsSpec(config, rel, stream) {
98
+ const owner = streamsOf(config).find((s) => s.specs.length && matchesAny(rel, s.specs));
99
+ return owner && owner.name !== stream ? owner.name : null;
100
+ }
101
+
102
+ // STRM-6: whose turn a shared core lane is: the stream it last ran a story for.
103
+ function readTurns(root) {
104
+ try {
105
+ const t = JSON.parse(readFileSync(join(mainOf(root), TURNS_FILE), 'utf8'));
106
+ return isObj(t) ? t : {};
107
+ } catch {
108
+ return {};
109
+ }
110
+ }
111
+
112
+ /** STRM-6: the stream a shared lane last ran a story for, or null. */
113
+ export const lastTurn = (root, lane) => readTurns(root)[lane] ?? null;
114
+
115
+ /** STRM-6: a shared lane started a story for `stream`. */
116
+ export function recordTurn(root, lane, stream) {
117
+ if (!stream) return;
118
+ const file = join(mainOf(root), TURNS_FILE);
119
+ mkdirSync(dirname(file), { recursive: true });
120
+ writeFileSync(file, `${JSON.stringify({ ...readTurns(root), [lane]: stream })}\n`);
121
+ }
122
+
123
+ /**
124
+ * STRM-6: the shared lanes `stream` gives way on: those it ran last, while another stream has a story
125
+ * waiting for them. `waiting` is [{ lane, stream }], every stream's ready and sent-back stories.
126
+ */
127
+ export function lanesToGiveWay(root, config, stream, waiting) {
128
+ if (!stream) return [];
129
+ return sharedLanes(config).filter(
130
+ (lane) =>
131
+ lastTurn(root, lane) === stream &&
132
+ waiting.some((w) => w.lane === lane && w.stream && w.stream !== stream),
133
+ );
134
+ }
135
+
136
+ // STRM-7: what a stream asks of core, with a platform stream: the platform lead decides each.
137
+ function readCoreLog(root) {
138
+ try {
139
+ return readFileSync(join(mainOf(root), CORE_REQUESTS_FILE), 'utf8')
140
+ .split('\n')
141
+ .flatMap((l) => {
142
+ try {
143
+ return l ? [JSON.parse(l)] : [];
144
+ } catch {
145
+ return [];
146
+ }
147
+ });
148
+ } catch {
149
+ return [];
150
+ }
151
+ }
152
+
153
+ function appendCore(root, record) {
154
+ const file = join(mainOf(root), CORE_REQUESTS_FILE);
155
+ mkdirSync(dirname(file), { recursive: true });
156
+ appendFileSync(file, `${JSON.stringify(record)}\n`);
157
+ }
158
+
159
+ /** STRM-7: every change request to core: [{ id, at, stream, session, story, what, why, state, decided }]. */
160
+ export function coreRequests(root) {
161
+ const byId = new Map();
162
+ for (const r of readCoreLog(root)) {
163
+ if (r.kind === 'ask') byId.set(r.id, { ...r, state: 'open', decided: null });
164
+ const had = byId.get(r.id);
165
+ if (r.kind === 'decide' && had)
166
+ byId.set(r.id, {
167
+ ...had,
168
+ state: r.how,
169
+ decided: { at: r.at, by: r.by ?? null, story: r.story ?? null, reason: r.reason ?? null },
170
+ });
171
+ }
172
+ return [...byId.values()];
173
+ }
174
+
175
+ /** STRM-7: a stream's lead asks core for what its story needs. The same open ask is asked once. */
176
+ export function askCore(
177
+ root,
178
+ { stream, session = null, story = null, what, why = null },
179
+ now = Date.now(),
180
+ ) {
181
+ const text = String(what ?? '').trim();
182
+ if (!text) return { ok: false, why: 'Say what the story needs from core.' };
183
+ const open = coreRequests(root).find(
184
+ (r) => r.state === 'open' && r.what === text && (r.story ?? null) === (story ?? null),
185
+ );
186
+ if (open) return { ok: true, request: open, existed: true };
187
+ const id = `C-${readCoreLog(root).filter((r) => r.kind === 'ask').length + 1}`;
188
+ appendCore(root, {
189
+ kind: 'ask',
190
+ id,
191
+ at: new Date(now).toISOString(),
192
+ stream,
193
+ session,
194
+ story,
195
+ what: text,
196
+ why: why?.trim() || null,
197
+ });
198
+ return { ok: true, request: coreRequests(root).find((r) => r.id === id), existed: false };
199
+ }
200
+
201
+ /**
202
+ * STRM-7: the platform lead's decision on a change request: `accepted` with the platform story that
203
+ * builds it (the asking story waits for that story), or `declined` with why.
204
+ */
205
+ export function decideCore(
206
+ root,
207
+ id,
208
+ { how, story = null, reason = null, by = null },
209
+ now = Date.now(),
210
+ ) {
211
+ const r = coreRequests(root).find((x) => x.id === id);
212
+ if (!r)
213
+ return { ok: false, why: `There's no change request ${id} to core. code-kit core lists them.` };
214
+ if (r.state !== 'open') return { ok: false, why: `${id} was ${r.state} already.` };
215
+ if (how === 'accepted' && !/^ST-\d+$/.test(story ?? ''))
216
+ return { ok: false, why: 'Name the platform story that builds it: --story ST-n.' };
217
+ if (how === 'declined' && !reason?.trim())
218
+ return {
219
+ ok: false,
220
+ why: 'Say why it is declined, with --reason, so the asking lead can plan around it.',
221
+ };
222
+ appendCore(root, { kind: 'decide', id, at: new Date(now).toISOString(), how, story, reason, by });
223
+ return { ok: true, request: coreRequests(root).find((x) => x.id === id) };
224
+ }
225
+
226
+ /**
227
+ * STRM-7: the stories a change request to core holds: Map(story → why), each open request's story, and
228
+ * each accepted one's until the platform story that builds it is done.
229
+ */
230
+ export function heldByCore(root, stories) {
231
+ const done = new Set(stories.filter((s) => s.state === 'done').map((s) => s.id));
232
+ const held = new Map();
233
+ for (const r of coreRequests(root)) {
234
+ if (!r.story || done.has(r.story)) continue;
235
+ if (r.state === 'open')
236
+ held.set(r.story, `${r.story} waits on the platform's decision on ${r.id} (${r.what})`);
237
+ else if (r.state === 'accepted' && r.decided?.story && !done.has(r.decided.story))
238
+ held.set(
239
+ r.story,
240
+ `${r.story} waits for ${r.decided.story}, the platform's story for ${r.id} (${r.what})`,
241
+ );
242
+ }
243
+ return held;
244
+ }
@@ -14,6 +14,8 @@ import { evidenceRecords } from './reviews.mjs';
14
14
  import { storyOfBranch } from './teamfacts.mjs';
15
15
  import { literalPath, matchesAny } from './glob.mjs';
16
16
  import { layerProblems } from './layers.mjs';
17
+ import { cloneCandidate, scanForPromotions } from './promote.mjs';
18
+ import { hasStreams } from './streams.mjs';
17
19
  import { STANDARDS_APPROVAL, standardsFile, standardsWeakenings } from './standards.mjs';
18
20
  import { TESTS_APPROVAL, branchWeakenings, fixOf, proveFix } from './regression.mjs';
19
21
  import {
@@ -315,6 +317,18 @@ export function verifyBranch({
315
317
  if (screen) found.design.push(screen.split('\n')[0]);
316
318
  }
317
319
 
320
+ // PROM-4: with promote.coreClones at refuse, module code the branch adds that repeats core is refused.
321
+ if (hasStreams(config) && config.harness.promote.coreClones === 'refuse' && present.length) {
322
+ const { clones } = scanForPromotions(root, config, {
323
+ files: present,
324
+ ref: 'HEAD',
325
+ record: false,
326
+ });
327
+ for (const c of clones.map(cloneCandidate))
328
+ if (c.signal === 'core-clone')
329
+ found.layers.push(`${c.what}: use core's instead of a copy (harness.promote.coreClones).`);
330
+ }
331
+
318
332
  // HAND-2: each register entry the branch adds or changes, and each approved design whose files it
319
333
  // changed, names the approved files with their hashes, every state the spec lists. HAND-11: an entry
320
334
  // the base already holds (where the branch left it, as it is now, or the first protected branch's,
@@ -4,6 +4,7 @@
4
4
 
5
5
  /** The steps the loop hands the lead; the rest (spec-design, init, check) wait for the person. */
6
6
  const LEAD_STEPS = new Set([
7
+ 'promote',
7
8
  'reconcile',
8
9
  'instructions',
9
10
  'decide',
@@ -171,6 +172,11 @@ export function leadPrompt(step, { cli = 'code-kit' } = {}) {
171
172
  return ids.length
172
173
  ? `${step.why ?? 'A lane waits on your decision.'} Run /code-kit:decide ${ids.join(' ')}.`
173
174
  : null;
175
+ // PROM-2: candidates for core, decided by the lead whose they are (the platform's, in a project with one).
176
+ if (step.step === 'promote')
177
+ return ids.length
178
+ ? `${step.why ?? `${ids.join(', ')} are proposed for core.`} Run /code-kit:promote ${ids.join(' ')}.`
179
+ : null;
174
180
  // ONB-3: a companion set up before any coding.
175
181
  if (step.step === 'setup')
176
182
  return ids.length
@@ -214,6 +220,7 @@ export function stepLabel(step) {
214
220
  {
215
221
  reconcile: 'Reconcile',
216
222
  decide: 'Decide requests',
223
+ promote: 'Decide for core',
217
224
  instructions: 'Update the instructions',
218
225
  dispatch: 'Dispatch',
219
226
  review: 'Review',