@warren-dean/code-kit 0.35.0 → 0.36.1

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
+ }
@@ -134,7 +134,7 @@ const CODE_KIT_READS = new RegExp(
134
134
  );
135
135
 
136
136
  /** A command's words, quotes taken off. */
137
- const wordsOf = (text) =>
137
+ export const wordsOf = (text) =>
138
138
  (text.match(/'[^']*'|"(?:\\.|[^"\\])*"|\S+/g) ?? []).map((w) =>
139
139
  w.replace(/^(['"])(.*)\1$/s, '$2'),
140
140
  );
@@ -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',
package/hooks/session.mjs CHANGED
@@ -11,6 +11,7 @@ import { loadConfig } from './lib/config.mjs';
11
11
  import { releaseSession } from './lib/laneclaims.mjs';
12
12
  import { modelOf } from './lib/hook.mjs';
13
13
  import { endSession, startSession } from './lib/sessions.mjs';
14
+ import { hasStreams } from './lib/streams.mjs';
14
15
  import { projectDir } from './lib/rules.mjs';
15
16
 
16
17
  let input = {};
@@ -33,6 +34,13 @@ if (config && session && process.argv[2] === 'start') {
33
34
  detached: true,
34
35
  stdio: 'ignore',
35
36
  }).unref();
37
+ // PROM-1: in a project built as streams, module code that belongs in core is looked for, in the background.
38
+ if (hasStreams(config))
39
+ spawn(process.execPath, [cli, 'promote', 'scan', '--quiet'], {
40
+ cwd: project,
41
+ detached: true,
42
+ stdio: 'ignore',
43
+ }).unref();
36
44
  // DUR-4: what an agent left open when the last session stopped is checked against git, in the background.
37
45
  spawn(process.execPath, [cli, 'reconcile'], {
38
46
  cwd: project,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@warren-dean/code-kit",
3
- "version": "0.35.0",
3
+ "version": "0.36.1",
4
4
  "description": "Keeps AI coding agents inside your project's rules: lanes, layer rules, protected paths and proof before finish, enforced by Claude Code hooks and in CI",
5
5
  "license": "MIT",
6
6
  "author": "Warren Langeveldt",
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: decide
3
- description: The lead decides what a lane asked for and couldn't do itself (a new package, a migration, a protected file, a UX question) against the story's requirements, the spec, the principles and the architecture. Approves it, answers the lane with something that fits better, or takes it to the person only when it crosses a guardrail. Use when code-kit's loop or `code-kit next` says a lane waits on your decision, when a lane hands back a change request, or when the person runs /code-kit:decide [request numbers].
3
+ description: The lead decides what a lane asked for and couldn't do itself (a new package, a migration, a protected file, a UX question), and, as a platform's lead, what a stream asks of core, against the story's requirements, the spec, the principles and the architecture. Approves it, answers the lane with something that fits better, or takes it to the person only when it crosses a guardrail. Use when code-kit's loop or `code-kit next` says a lane waits on your decision, when a lane hands back a change request, or when the person runs /code-kit:decide [request numbers].
4
4
  ---
5
5
 
6
6
  # Decide a lane's request
@@ -57,6 +57,13 @@ For each, read the lane's change request (its report, in `.claude/state/reports/
57
57
 
58
58
  A request `by: "person"` is a guardrail the lane hit: a spec, a contract, a design, CI, a weakened test, or the running budget. A `cost` request (a commit over the budget, spec 29) is the person's under vibe too, and never goes to them bare: first look for what fits the budget (a smaller size, a cheaper tier or provider, one environment instead of two, a service the story can do without at launch), and send the lane back with it if one does. If none fits, ask them with each option that comes closest, what it gives up and what it saves a month, and the over-budget one with its cost (`code-kit ask … --option …`; under vibe, `--needs payment`). Check the lane really needs it first: often the story can be done inside the guardrail, and you tell the lane how and drop the request. If it does need it, the request is already waiting for the person, in their band and the pane's Needs you. Add your recommendation with `ask` when the choice isn't obvious from the request alone.
59
59
 
60
- ## 5. Report
60
+ ## 5. Change requests to core
61
+
62
+ In a project built as streams with a platform stream (spec 31), a stream that needs core changed asks the platform (`code-kit core ask`), and its story waits. As the platform's lead, `core --json` lists them; ids are `C-n`. Judge each as you would a lane's request: the asking story's requirements need it, core doesn't already do it, and core can own it without knowing the stream (no stream's types, data or rules). Then:
63
+
64
+ - **Accept it** with the platform story that builds it, written in the platform's plan: `code-kit core accept C-n --story ST-n`. The asking story waits for that story to merge.
65
+ - **Decline it** with why, and what the stream can do instead: `code-kit core decline C-n --reason "…"`. The asking story no longer waits.
66
+
67
+ ## 6. Report
61
68
 
62
69
  One line per request: what was asked, what you decided, and why. "ST-138: pillow approved for api (MED-5 needs HEIC decoding; nothing installed reads HEIC)." Then carry on with the build.
@@ -61,6 +61,12 @@ Write `.claude/code-kit.draft.json`. Follow `${CLAUDE_PLUGIN_ROOT}/README.md`
61
61
  - `agent`: a kebab-case agent name, for example `api-engineer`;
62
62
  - `paths` and `exclude`: every path must have exactly one owner.
63
63
  - `label` (optional): what the lane delivers, in a few words ("Screens", "Tests"), when its name doesn't say it.
64
+ - **`streams` (spec 31), only when the product has separate product lines:** when the architecture lays out a core and a module per line, draft them. When the brief, the specs or the plan name more than one product line or offering (for different users, on a shared platform), or there are no specs, ask once: "Do separate teams, or sessions, build separate product lines of this product?", naming the lines you found. If not, leave `streams` out: one lead runs every lane, as before. If so:
65
+ - `docs.plan` is a folder (`docs/plan/`) and each stream has its own plan file in it;
66
+ - `"streams": { "<line>": { "label", "lanes", "plan", "specs" } }`, each lane in exactly one stream: a line's lanes own its modules (`api-<line>`, `web-<line>`);
67
+ - each module's layer gets `"stream": "<line>"`; core's layers have none. The import check then refuses a module importing another line's module, and core importing a module;
68
+ - core's lanes go in a stream with `"platform": true` when the person wants a team to own core (its lead decides what goes into core, and the other streams ask it with `code-kit core ask`); otherwise they're in no stream, and the streams take them in turns;
69
+ - each stream's lead runs in its own session: `/code-kit:lead <stream>`; the first one leads from the main checkout, the others from a worktree each.
64
70
  - **A QA lane:** when lanes own screens, or the plan's journeys cross lanes, a `qa` lane with a `test-engineer` agent owning the end-to-end suites (the plan's work split names them; brownfield: the folders the existing end-to-end tests live in), even if the docs forgot it. Its agent's proving command runs the suites. Add a `checks` entry for them scoped by `files` to the suites, so verify runs them when they change. Unit tests stay with each lane.
65
71
  - **`setup`:** `3`, the version of this setup, so `code-kit next` can tell an older project what re-running init adds.
66
72
  - **`lead.paths`:** contracts, specs, design, root config, and anything the docs reserve for the lead.
@@ -185,6 +191,7 @@ Re-run whenever the build has moved on: new apps or packages, folders that moved
185
191
  - the security reviewer (`.claude/agents/security-reviewer.md`), unless the product handles no sign-in, personal data, payments, outside input or secrets; and, as a proposal for the person, a threat model and security requirements for each spec that lacks them (spec-design's section 4);
186
192
  - `"adapters": { "<name>": true }` for a companion that's installed but not set up, which is then set up before any code.
187
193
  - project standards, when the project has no `docs/standards.md`: suggest them as section 2's Standards describes, moving the engineering rules out of `docs/principles.md`, and protect the file.
194
+ - streams, when the config has no `streams` (whatever its `setup`) and the brief, the specs or the plan name more than one product line: ask the question section 2 gives, naming the lines, and on a yes draft them as section 4 describes.
188
195
  - a running budget, when the config has no `cost` (whatever its `setup`): ask the person for it as section 2 describes. Then cost what's already defined in the infrastructure files, or deployed, into `docs/costs.md`, a row per paid thing at its real size, and run `code-kit cost`. When it's over the budget, bring the person options that fit (spec-design's architecture step lists the kinds), each with what it gives up and what it saves a month, and record their choice in the brief's decision log; the stories that bring it within budget go in the plan.
189
196
  3. **Show the difference:**
190
197
 
@@ -195,7 +202,8 @@ Re-run whenever the build has moved on: new apps or packages, folders that moved
195
202
 
196
203
  `diff` lists lanes, layers, checks and rules that were added (`+`), removed (`-`) or changed (`~`), and how many files change owner, route by route. Explain each change in a sentence, with where it came from: the doc section, or the folder in the repository.
197
204
 
198
- 4. **Also propose:**
205
+ 4. **Adding streams to a project that started as one (spec 31):** when the person says they now build separate product lines, or answers yes to the question above, draft `streams` as in section 2, splitting each technical lane into a core lane and a lane per line, and each layer into core and a module per line. Where the code isn't split into those folders yet, don't move it in the update: write the move as stories (in the platform's plan, or the lead's own), lower layers first, a few files each, every story switching the code that imports what it moved, and say so in the diff. Until a story moves a file, the file stays with the lane that owns it today.
206
+ 5. **Also propose:**
199
207
  - agent files for new lanes, and updates to agents whose paths changed, and to the security reviewer when the specs' threat models changed;
200
208
  - **project skills**, by reading the recipes in the docs again and comparing them with `.claude/skills/`:
201
209
  - a new skill for each recipe the docs now describe that has none;
@@ -204,7 +212,7 @@ Re-run whenever the build has moved on: new apps or packages, folders that moved
204
212
  - the matching **Skills to use** changes on every lane agent whose paths each recipe touches;
205
213
  - skills the person wrote themselves, with no recipe behind them, stay as they are;
206
214
  - a smaller baseline when `baseline` shows violations were fixed. It only ever shrinks.
207
- 5. **On approval:**
215
+ 6. **On approval:**
208
216
  1. Replace `.claude/code-kit.json` with the draft and delete the draft.
209
217
  2. Write or update the agents, and write, update or remove the project skills as approved, together.
210
218
  3. Run `baseline --write` if it shrank.