File size: 10,561 Bytes
0110783
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
#!/usr/bin/env node
/**

 * session-start.js — Nomad SessionStart hook (portable port of production

 * `hooks-core/session-start-core.js`, parameterized per team-skeleton.md §3/§5).

 *

 * Injects up to five sections at session start:

 *   ① a pointer to the team charter (ARCHITECTURE.md / 团队结构宪章.md) if one

 *      exists at the team root — the charter's §9 optional "layer 2" routing

 *   ② top-of-file excerpt of the shared team log (shared_paths.team_log)

 *   ③ a "what's in progress" summary of the shared kanban (shared_paths.kanban)

 *   ④ this agent's own unread-inbox count

 *   ⑤ a cross-session soft-lock warning, if another harness/session appears

 *      to already hold this agent home (see lib/session-lock.js)

 * Any section that can't be built (file missing, path unresolvable, parse

 * miss) is silently skipped — never blocks the session, never throws past main().

 *

 * Design decisions specific to this portable version (see scripts/README.md

 * for the full writeup):

 *   - Team root and agent home are located by directory STRUCTURE (presence of

 *     team-config.json / AGENTS.md), never by a hardcoded folder name — unlike

 *     the production original, which regex-matches a fixed parent-folder name.

 *   - The kanban section tries the production-shaped structured parse first

 *     (## heading containing "In Progress"/"进行中" + ### item title + a

 *     "**Status**:"/"**状态**:" line). If that structural shape isn't found

 *     (kanban.md formats vary team to team — team-skeleton.md doesn't mandate

 *     internal structure), it degrades to a plain head-of-file excerpt instead

 *     of going silent, so a differently-formatted kanban still surfaces

 *     *something* rather than nothing.

 *   - The memory/ directory and inbox filename are resolved by probing both

 *     the Chinese and English naming candidates (`记忆`/`memory`,

 *     `收件箱.md`/`inbox.md`) — team-skeleton.md explicitly allows either

 *     native-language or English directory names (hardcoding point #5), and

 *     team-config.json has no field for this, so probing is the least-assumption

 *     way to support both without adding a new config field this batch wasn't

 *     asked to introduce.

 *

 * Usage: node session-start.js [--platform claude|codex|cursor]

 *   stdin: hook input JSON (at least a `cwd` field). Missing/bad JSON never

 *   crashes this script — it just can't resolve cwd, and section ③ is skipped.

 */

'use strict';
const fs = require('fs');
const path = require('path');
const emit = require('./lib/emit');
const cfg = require('./lib/config');
const sessionLock = require('./lib/session-lock');
const messages = require('./lib/messages');

const TEAMLOG_HEAD_LINES = 55;
const KANBAN_STATUS_MAX_CHARS = 150;
const KANBAN_ITEMS_MAX = 10;
const KANBAN_RAW_FALLBACK_LINES = 20;

const MEMORY_DIR_CANDIDATES = ['记忆', 'memory'];
const INBOX_FILENAME_CANDIDATES = ['收件箱.md', 'inbox.md'];
// Team charter filename candidates — same probe-both-namings pattern as the
// memory/inbox candidates above. The charter's own §9 ("charter routing")
// names SessionStart injection of a charter pointer as its optional layer 2;
// this section is that layer. Both scaffolded layouts are covered: the
// English sample team ships ARCHITECTURE.md, the Chinese one 团队结构宪章.md.
const CHARTER_FILENAME_CANDIDATES = ['ARCHITECTURE.md', '团队结构宪章.md'];

// Bilingual structural markers for the kanban "in progress" heuristic parse.
const IN_PROGRESS_RE = /(进行中|in.?progress)/i;
const STATUS_LINE_RE = /^-\s*\*\*(状态|status)\*\*[::]\s*(.+)$/i;
const UNREAD_SECTION_RE = /(未读|unread)/i;

// ── pure-function layer: string in, string/object out — no filesystem access, unit-testable directly ──

function safeSplitLines(content) {
  return content.split(/\r\n|\r|\n/);
}

function parseTeamlogHead(content, maxLines) {
  return safeSplitLines(content).slice(0, maxLines).join('\n');
}

/**

 * Structured kanban parse: `##` heading containing an "in progress" marker,

 * `###` item title, then a `- **Status**:`/`- **状态**:` line (either

 * language's colon, either language's bold-label wording).

 * @returns {{items:string[], total:number}}

 */
function parseKanbanHot(content, maxChars) {
  const lines = safeSplitLines(content);
  let inHot = false;
  let title = '';
  const items = [];
  for (const ln of lines) {
    if (/^##\s/.test(ln)) {
      inHot = IN_PROGRESS_RE.test(ln);
      continue;
    }
    if (!inHot) continue;
    const titleMatch = ln.match(/^###\s+(.+)$/);
    if (titleMatch) {
      title = titleMatch[1].trim();
      continue;
    }
    if (title) {
      const stMatch = ln.match(STATUS_LINE_RE);
      if (stMatch) {
        let st = stMatch[2].trim();
        if (st.length > maxChars) st = st.slice(0, maxChars) + '...';
        items.push('- ' + title + ' -- ' + st);
        title = '';
      }
    }
  }
  return { items, total: items.length };
}

function parseInboxUnreadCount(content) {
  const lines = safeSplitLines(content);
  let inUnread = false;
  let unread = 0;
  for (const ln of lines) {
    if (/^##\s/.test(ln)) {
      inUnread = UNREAD_SECTION_RE.test(ln);
      continue;
    }
    if (inUnread && /^-\s/.test(ln)) unread++;
  }
  return unread;
}

function extractCwd(raw) {
  try {
    if (!raw || !raw.trim()) return '';
    const j = JSON.parse(raw);
    return typeof j.cwd === 'string' ? j.cwd : '';
  } catch (e) {
    return '';
  }
}

// ── I/O layer: read files + call pure functions + format text; any exception returns '' (skip that section), never throws ──

function buildTeamlogSection(teamRoot, config, msg) {
  try {
    const p = cfg.resolveSharedPath(teamRoot, config, 'team_log');
    if (!p || !fs.existsSync(p)) return '';
    const content = cfg.readTextFileStripBOM(p);
    const head = parseTeamlogHead(content, TEAMLOG_HEAD_LINES);
    return msg.teamlogHeader(TEAMLOG_HEAD_LINES) + head + msg.teamlogFooter;
  } catch (e) {
    return '';
  }
}

function buildKanbanSection(teamRoot, config, msg) {
  try {
    const p = cfg.resolveSharedPath(teamRoot, config, 'kanban');
    if (!p || !fs.existsSync(p)) return '';
    const content = cfg.readTextFileStripBOM(p);
    const { items, total } = parseKanbanHot(content, KANBAN_STATUS_MAX_CHARS);
    if (total > 0) {
      const shown = items.slice(0, KANBAN_ITEMS_MAX);
      let section = msg.kanbanHeaderStructured(total) + shown.join('\n');
      if (total > KANBAN_ITEMS_MAX) section += msg.kanbanTruncatedNote(KANBAN_ITEMS_MAX);
      section += msg.kanbanFooter;
      return section;
    }
    // Structural shape didn't match this team's kanban.md — degrade to a raw head excerpt
    // instead of going silent (see file header "design decisions" note).
    const rawHead = parseTeamlogHead(content, KANBAN_RAW_FALLBACK_LINES).trim();
    if (!rawHead) return '';
    return msg.kanbanHeaderRaw(KANBAN_RAW_FALLBACK_LINES) + rawHead + '\n';
  } catch (e) {
    return '';
  }
}

function buildCharterSection(teamRoot, msg) {
  try {
    if (!teamRoot) return '';
    const charterPath = cfg.firstExisting(teamRoot, CHARTER_FILENAME_CANDIDATES);
    if (!charterPath) return '';
    return msg.charterPointer(path.basename(charterPath));
  } catch (e) {
    return '';
  }
}

function buildInboxSection(cwd, msg) {
  try {
    if (!cwd) return '';
    const agentHome = cfg.resolveAgentHome(cwd);
    if (!agentHome) return '';
    const memDir = cfg.firstExisting(agentHome, MEMORY_DIR_CANDIDATES);
    if (!memDir) return '';
    const inboxPath = cfg.firstExisting(memDir, INBOX_FILENAME_CANDIDATES);
    if (!inboxPath) return '';
    const content = cfg.readTextFileStripBOM(inboxPath);
    const unread = parseInboxUnreadCount(content);
    if (unread > 0) return msg.inboxUnread(unread);
    return '';
  } catch (e) {
    return '';
  }
}

function buildSessionLockSection(cwd, platform, msg) {
  try {
    if (!cwd) return '';
    const agentHome = cfg.resolveAgentHome(cwd);
    if (!agentHome) return '';
    const result = sessionLock.acquire(agentHome, platform || 'unknown');
    if (result && result.warned && result.priorHolder) {
      return msg.sessionLockWarning(result.priorHolder.harness, result.priorHolder.pid, result.priorHolder.acquiredAt);
    }
    return '';
  } catch (e) {
    return '';
  }
}

async function main() {
  const platform = emit.getPlatform();
  try {
    const raw = await emit.readStdin();
    const cwd = emit.resolveCwd(raw, platform);

    const sid = emit.extractSessionId(raw);
    if (sid && emit.isDuplicateInvocation('SessionStart', sid)) {
      process.exit(0);
      return;
    }

    const teamRoot = cfg.resolveTeamRoot(cwd || process.cwd());
    const config = cfg.loadTeamConfig(teamRoot);
    const lang = cfg.resolveLanguage(config);
    const msg = messages.get(lang);

    let ctx = msg.openingCheck + '\n';
    ctx += buildCharterSection(teamRoot, msg);
    ctx += buildTeamlogSection(teamRoot, config, msg);
    ctx += buildKanbanSection(teamRoot, config, msg);
    ctx += buildInboxSection(cwd, msg);
    ctx += buildSessionLockSection(cwd, platform, msg);

    emit.writeJson(emit.buildSessionStartPayload(ctx, platform));
  } catch (e) {
    // Never block the session: emit nothing on stdout, so the host treats it as
    // "no injection". But surface the error on stderr rather than swallowing it
    // silently — an unexpected exception vanishing without a trace is exactly
    // the silent-failure mode we don't want. stderr is not part of the injected
    // context, so this stays fully compatible with the "never block the session"
    // contract (append-log.js writes to stderr the same way without affecting flow).
    process.stderr.write('[session-start] non-fatal error, no context injected (session not blocked): ' + ((e && e.stack) || e) + '\n');
  }
  process.exit(0);
}

if (require.main === module) {
  main();
}

module.exports = {
  buildTeamlogSection,
  buildKanbanSection,
  buildInboxSection,
  buildSessionLockSection,
  buildCharterSection,
  extractCwd,
  parseTeamlogHead,
  parseKanbanHot,
  parseInboxUnreadCount,
  MEMORY_DIR_CANDIDATES,
  INBOX_FILENAME_CANDIDATES,
  CHARTER_FILENAME_CANDIDATES,
};