nomad / scripts /session-start.js
LucioLiu's picture
Initial release - mirrors github.com/LucioLiu/nomad
0110783 verified
Raw
History Blame Contribute Delete
10.6 kB
#!/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,
};