reasonweave 1.4.9 → 1.4.12

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.
@@ -794,17 +794,26 @@ function resolveTicketId(id) {
794
794
  const clean = String(id).trim().replace(/\.md$/, '').replace(/-resp$/, '');
795
795
  const direct = path.join(H_DIR, `${clean}.md`);
796
796
  if (fs.existsSync(direct)) return clean;
797
- // 支持通过 conversation_id 或 UUID 前缀反查工单 ID
797
+ // 支持通过 conversation_id 或 UUID 前缀反查工单 ID(支持大小写不敏感与跨平台路径)
798
798
  if (fs.existsSync(H_DIR)) {
799
799
  try {
800
800
  const files = fs.readdirSync(H_DIR).filter(f => f.endsWith('.md') && f.toUpperCase() !== 'README.MD');
801
+ const cleanLower = clean.toLowerCase();
802
+ // 1. 优先查文件名(大小写不敏感匹配)
803
+ for (const f of files) {
804
+ if (f.toLowerCase().replace(/\.md$/, '') === cleanLower) {
805
+ return f.replace(/\.md$/, '');
806
+ }
807
+ }
808
+ // 2. 查 frontmatter 中的 conversation_id / handoff_id
801
809
  const matches = [];
802
810
  for (const f of files) {
803
811
  try {
804
- const raw = fs.readFileSync(path.join(H_DIR, f), 'utf8');
812
+ const raw = safeReadFileWithRetry(path.join(H_DIR, f), 'utf8');
805
813
  const fm = readFM(raw);
806
814
  if (fm && fm.conversation_id) {
807
- if (fm.conversation_id === clean || fm.conversation_id.startsWith(clean)) {
815
+ const convLower = String(fm.conversation_id).toLowerCase();
816
+ if (convLower === cleanLower || convLower.startsWith(cleanLower)) {
808
817
  matches.push(fm.handoff_id || f.replace(/\.md$/, ''));
809
818
  }
810
819
  }
@@ -819,6 +828,33 @@ function resolveTicketId(id) {
819
828
  return clean;
820
829
  }
821
830
 
831
+ /** 安全读取文件,针对 Windows/NTFS 独占锁 (EBUSY / EPERM) 实施毫秒级指数退避自愈重试 */
832
+ function safeReadFileWithRetry(filePath, encoding = 'utf8', retries = 3) {
833
+ for (let attempt = 0; attempt <= retries; attempt++) {
834
+ try {
835
+ return fs.readFileSync(filePath, encoding);
836
+ } catch (err) {
837
+ if ((err.code === 'EBUSY' || err.code === 'EPERM') && attempt < retries) {
838
+ const delay = 50 * Math.pow(2, attempt);
839
+ const start = Date.now();
840
+ while (Date.now() - start < delay) {}
841
+ continue;
842
+ }
843
+ throw err;
844
+ }
845
+ }
846
+ }
847
+
848
+ /** 跨平台路径统一归一化(Windows 下统一小写正斜杠,消除盘符与大小写判定分裂) */
849
+ function normalizeFsPath(p) {
850
+ if (!p) return '';
851
+ let norm = path.normalize(path.resolve(p));
852
+ if (process.platform === 'win32') {
853
+ norm = norm.toLowerCase().replaceAll('\\', '/');
854
+ }
855
+ return norm;
856
+ }
857
+
822
858
  function readFM(content) {
823
859
  if (!content) return null;
824
860
  const m = content.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n/);
@@ -845,17 +881,33 @@ function fmtVal(v) {
845
881
  return v;
846
882
  }
847
883
 
848
- /** 原子写入文件(write tmp + rename),防止并发或意外中断写半截 */
884
+ /** 原子写入文件(write tmp + rename),针对 Windows 独占锁实施重试自愈 */
849
885
  function writeAtomic(file, content) {
850
886
  const dir = path.dirname(file);
851
887
  try { if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true }); } catch {}
852
888
  const tmp = path.join(dir, `.${path.basename(file)}.tmp.${process.pid}.${Date.now()}`);
853
889
  fs.writeFileSync(tmp, content, 'utf8');
854
- try {
855
- fs.renameSync(tmp, file);
856
- } catch {
857
- fs.copyFileSync(tmp, file);
858
- try { fs.unlinkSync(tmp); } catch {}
890
+ let renamed = false;
891
+ for (let attempt = 0; attempt <= 3; attempt++) {
892
+ try {
893
+ fs.renameSync(tmp, file);
894
+ renamed = true;
895
+ break;
896
+ } catch (err) {
897
+ if ((err.code === 'EBUSY' || err.code === 'EPERM') && attempt < 3) {
898
+ const delay = 50 * Math.pow(2, attempt);
899
+ const start = Date.now();
900
+ while (Date.now() - start < delay) {}
901
+ continue;
902
+ }
903
+ break;
904
+ }
905
+ }
906
+ if (!renamed) {
907
+ try {
908
+ fs.copyFileSync(tmp, file);
909
+ try { fs.unlinkSync(tmp); } catch {}
910
+ } catch {}
859
911
  }
860
912
  }
861
913
 
@@ -1112,16 +1164,49 @@ function assertNoUnrecognizedSession(op, args = []) {
1112
1164
  process.exit(1);
1113
1165
  }
1114
1166
 
1115
- function getSessionLane() {
1167
+ function getSessionData() {
1116
1168
  try {
1117
1169
  const k = getSessionId();
1170
+ if (!k || k === 'global' || k.startsWith('ppid-')) return {};
1118
1171
  const f = path.join(SESSIONS_DIR, `${k}.json`);
1119
1172
  if (fs.existsSync(f)) {
1120
- const data = JSON.parse(fs.readFileSync(f, 'utf8'));
1121
- if (data && data.lane) return String(data.lane).toLowerCase();
1173
+ return JSON.parse(safeReadFileWithRetry(f, 'utf8')) || {};
1122
1174
  }
1123
1175
  } catch {}
1124
- return '';
1176
+ return {};
1177
+ }
1178
+
1179
+ function setSessionData(patch) {
1180
+ try {
1181
+ const k = getSessionId();
1182
+ if (!k || k === 'global' || k.startsWith('ppid-')) return;
1183
+ if (!fs.existsSync(SESSIONS_DIR)) fs.mkdirSync(SESSIONS_DIR, { recursive: true });
1184
+ const f = path.join(SESSIONS_DIR, `${k}.json`);
1185
+ let current = {};
1186
+ if (fs.existsSync(f)) {
1187
+ try { current = JSON.parse(safeReadFileWithRetry(f, 'utf8')) || {}; } catch {}
1188
+ }
1189
+ const merged = { ...current, ...patch, ppid: process.ppid, ts: new Date().toISOString() };
1190
+ writeAtomic(f, JSON.stringify(merged, null, 2));
1191
+ } catch {}
1192
+ }
1193
+
1194
+ function getSessionLane() {
1195
+ const data = getSessionData();
1196
+ return data.lane ? String(data.lane).toLowerCase() : '';
1197
+ }
1198
+
1199
+ function setSessionLane(lane) {
1200
+ if (!lane) return;
1201
+ setSessionData({ lane: String(lane).toLowerCase() });
1202
+ }
1203
+
1204
+ function clearSessionLane() {
1205
+ try {
1206
+ const k = getSessionId();
1207
+ const f = path.join(SESSIONS_DIR, `${k}.json`);
1208
+ if (fs.existsSync(f)) fs.unlinkSync(f);
1209
+ } catch {}
1125
1210
  }
1126
1211
 
1127
1212
  /** 跨会话操作硬门禁(Anti-Cross-Session Hard Gate · v2.36.0 宪法 T6):
@@ -1144,35 +1229,78 @@ function assertSessionAffinity(fm, op, id, args = []) {
1144
1229
  if (ticketSession && curSession !== ticketSession && !ticketSession.startsWith(curSession) && !curSession.startsWith(ticketSession)) {
1145
1230
  const isZh = detectLang() === 'zh';
1146
1231
  if (isZh) {
1147
- console.error(`\n❌ 跨会话操作拦截 (CROSS_SESSION_MUTATION_BLOCKED):`);
1148
- console.error(` 工单 [${id}] 归属于会话 [${ticketSession}],当前活跃会话为 [${curSession}]。`);
1149
- console.error(` 根据 AEF 最高工程宪法(防串扰与会话隔离铁律),严禁跨会话处理或推进外部工单!`);
1150
- console.error(` 👉 请切换至原发起会话(${ticketSession})执行 ${op},或在终端使用 --force-session 显式覆盖。\n`);
1232
+ console.error(`\n❌ 跨会话操作硬门禁拦截 (CROSS_SESSION_MUTATION_BLOCKED):`);
1233
+ console.error(` 当前工单 [${id}] 归属于会话 [${ticketSession}],但当前活跃会话为 [${curSession}]!`);
1234
+ console.error(` 根据 v2.36.0 宪法 T6 严禁跨会话处理工单律,推进 (forward)、闭环 (accept/close) 与重开 (reopen) 仅限原工单发起会话执行。`);
1235
+ console.error(` 👉 请切换回原发起会话处理,或在新建工单下流转。\n`);
1151
1236
  } else {
1152
1237
  console.error(`\n❌ Cross-Session Mutation Blocked (CROSS_SESSION_MUTATION_BLOCKED):`);
1153
- console.error(` Ticket [${id}] belongs to session [${ticketSession}], but current session is [${curSession}].`);
1154
- console.error(` Cross-session ticket mutation is strictly prohibited (use --force-session to bypass).\n`);
1238
+ console.error(` Ticket [${id}] belongs to session [${ticketSession}], but current active session is [${curSession}]!`);
1239
+ console.error(` Per v2.36.0 constitution T6, forward/accept/reopen are restricted to the origin session.`);
1240
+ console.error(` 👉 Switch back to the origin session or create a new ticket.\n`);
1155
1241
  }
1156
1242
  process.exit(1);
1157
1243
  }
1158
1244
  }
1159
1245
 
1160
- function setSessionLane(lane) {
1161
- if (!lane) return;
1162
- try {
1163
- if (!fs.existsSync(SESSIONS_DIR)) fs.mkdirSync(SESSIONS_DIR, { recursive: true });
1164
- const k = getSessionId();
1165
- const f = path.join(SESSIONS_DIR, `${k}.json`);
1166
- fs.writeFileSync(f, JSON.stringify({ lane: String(lane).toLowerCase(), ppid: process.ppid, ts: new Date().toISOString() }, null, 2), 'utf8');
1167
- } catch {}
1246
+ /**
1247
+ * 校验会话-工单互斥粘性锁(Anti-Cross-Ticket Contamination · ADR-0019 / 借鉴 LangGraph thread_id)
1248
+ * 同一接单 Agent 会话在同一上下文只能处理同一份工单(一单到底),严禁向外部工单提交写操作。
1249
+ */
1250
+ function assertTicketAffinity(ticketId, op, args = []) {
1251
+ if (args.includes('--force-ticket') || process.env.BATON_FORCE_TICKET === '1') {
1252
+ return;
1253
+ }
1254
+ const curSession = getSessionId();
1255
+ if (!curSession || curSession === 'global' || curSession.startsWith('ppid-')) {
1256
+ return;
1257
+ }
1258
+ const sessData = getSessionData();
1259
+ const boundTicket = sessData.bound_ticket;
1260
+ if (!boundTicket) {
1261
+ return;
1262
+ }
1263
+
1264
+ const normBound = String(boundTicket).toLowerCase().trim();
1265
+ const normTarget = String(ticketId).toLowerCase().trim();
1266
+
1267
+ if (normBound !== normTarget) {
1268
+ const isZh = detectLang() === 'zh';
1269
+ if (isZh) {
1270
+ console.error(`\n❌ 跨工单污染拦截 (CROSS_TICKET_CONTAMINATION_BLOCKED):`);
1271
+ console.error(` 当前活跃会话 [${curSession}] 已锁定处理工单 [${boundTicket}](Round ${sessData.bound_round || 1}),`);
1272
+ console.error(` 检测到对不同工单 [${ticketId}] 的越界写操作(baton ${op})!`);
1273
+ console.error(` 根据 ADR-0019 单会话一单到底律,同一上下文只能处理同一份工单,严禁串单操作。`);
1274
+ console.error(` 👉 若需强制操作,请在终端追加 --force-ticket,或开启全新 Agent 会话。\n`);
1275
+ } else {
1276
+ console.error(`\n❌ Cross-Ticket Contamination Blocked (CROSS_TICKET_CONTAMINATION_BLOCKED):`);
1277
+ console.error(` Current session [${curSession}] is locked to ticket [${boundTicket}] (Round ${sessData.bound_round || 1}),`);
1278
+ console.error(` but attempted to perform '${op}' on different ticket [${ticketId}].`);
1279
+ console.error(` Per ADR-0019 single-ticket exclusive invariant, cross-ticket mutations in the same context are prohibited.`);
1280
+ console.error(` 👉 Use --force-ticket to bypass, or open a fresh agent session.\n`);
1281
+ }
1282
+ process.exit(1);
1283
+ }
1168
1284
  }
1169
1285
 
1170
- function clearSessionLane() {
1171
- try {
1172
- const k = getSessionId();
1173
- const f = path.join(SESSIONS_DIR, `${k}.json`);
1174
- if (fs.existsSync(f)) fs.unlinkSync(f);
1175
- } catch {}
1286
+ /** 绑定或自动递增当前会话与工单的亲和锁 */
1287
+ function bindSessionTicket(ticketId, round = 1, force = false) {
1288
+ if (!ticketId) return;
1289
+ const curSession = getSessionId();
1290
+ if (!curSession || curSession === 'global' || curSession.startsWith('ppid-')) {
1291
+ return;
1292
+ }
1293
+ const sessData = getSessionData();
1294
+ const normTarget = String(ticketId).trim();
1295
+ const r = Number(round) || 1;
1296
+ if (force || !sessData.bound_ticket || String(sessData.bound_ticket).toLowerCase() === normTarget.toLowerCase()) {
1297
+ setSessionData({
1298
+ bound_ticket: normTarget,
1299
+ bound_round: (force && String(sessData.bound_ticket).toLowerCase() !== normTarget.toLowerCase())
1300
+ ? r
1301
+ : Math.max(Number(sessData.bound_round) || 1, r)
1302
+ });
1303
+ }
1176
1304
  }
1177
1305
 
1178
1306
  /** 获取或生成审计私钥凭据(.handoffs/.secrets/audit.token 或 BATON_AUDIT_TOKEN) */
@@ -1268,6 +1396,150 @@ function resolveExecutionLane(asInput, ctx = {}) {
1268
1396
  return '';
1269
1397
  }
1270
1398
 
1399
+ /**
1400
+ * Baton 角色-动作法定权能矩阵 (Role-Action Capability Matrix · ADR-0019 / 借鉴 MetaGPT set_actions)
1401
+ * 严格划分各角色(Initiator / Executor / Auditor)在状态机流转中所允许执行的命令白名单。
1402
+ */
1403
+ const ROLE_ACTION_MATRIX = {
1404
+ // 发起角色 (Initiator / from_lane):负责工单生命周期调度、推进与最终验收
1405
+ initiator: new Set([
1406
+ 'new', 'forward', 'wait', 'prompt', 'accept', 'close',
1407
+ 'reopen', 'reject', 'show', 'status', 'check', 'brief', 'drift', 'sync', 'lane'
1408
+ ]),
1409
+
1410
+ // 执行角色 (Executor / to_lane=impl 等):负责根据需求编写代码并提供证据
1411
+ executor: new Set([
1412
+ 'show', 'status', 'receipt', 'deliver', 'check', 'wait', 'lane'
1413
+ ]),
1414
+
1415
+ // 独立审查角色 (Auditor / to_lane=audit):负责独立测试核验与反向裁决(严禁自审关单)
1416
+ audit: new Set([
1417
+ 'show', 'status', 'receipt', 'deliver', 'reject', 'nonce', 'check', 'wait', 'lane'
1418
+ ])
1419
+ };
1420
+
1421
+ /**
1422
+ * 校验当前角色执行该命令的合法性(防角色漂移物理门禁 · ADR-0018 & ADR-0019 / 借鉴 MetaGPT Role-Action 白名单)
1423
+ * 核心原则:用物理能力限制取代提示词礼貌提示。
1424
+ */
1425
+ function assertRoleCommandAllowed(op, lane, ticketFm = null) {
1426
+ if (!lane) return;
1427
+ const l = lane.toLowerCase().trim();
1428
+ const isZh = detectLang() === 'zh';
1429
+
1430
+ const fromLanes = ticketFm?.from_lane ? String(ticketFm.from_lane).toLowerCase().split(/[,/]/).map(s => s.trim()) : [];
1431
+ const toLane = String(ticketFm?.to_lane || ticketFm?.target || '').toLowerCase().trim();
1432
+ const isInitiator = fromLanes.includes(l) || (!toLane && l !== 'audit');
1433
+
1434
+ let roleCategory = 'executor';
1435
+ if (isInitiator) {
1436
+ roleCategory = 'initiator';
1437
+ } else if (l === 'audit') {
1438
+ roleCategory = 'audit';
1439
+ }
1440
+
1441
+ const allowedActions = ROLE_ACTION_MATRIX[roleCategory] || ROLE_ACTION_MATRIX.executor;
1442
+ if (!allowedActions.has(op)) {
1443
+ const roleTitleZh = roleCategory === 'initiator' ? '发起方' : (roleCategory === 'audit' ? '独立审计方' : '执行方');
1444
+ const roleTitleEn = roleCategory === 'initiator' ? 'Initiator' : (roleCategory === 'audit' ? 'Auditor' : 'Executor');
1445
+ if (isZh) {
1446
+ console.error(`❌ [角色权限门禁拦截 (ROLE_ACTION_BLOCKED / ROLE_ACTION_VIOLATION)] 角色 [${l}](${roleTitleZh})法定权能无权执行动作 [baton ${op}]!`);
1447
+ console.error(` 👉 该角色法定可用动作仅限: ${[...allowedActions].map(a => `baton ${a}`).join(', ')}`);
1448
+ if (l === 'audit' && !isInitiator) {
1449
+ console.error(` 👉 audit 角色为独立审查方,其职责为签署回执 (baton receipt --deliver) 或驳回 (baton reject),严禁执行闭环 (baton ${op})!`);
1450
+ } else if ((op === 'accept' || op === 'close') && !isInitiator) {
1451
+ console.error(` 👉 终态验收闭环(accept/close)是发起方的专属特权,执行方禁止自审自闭环(严禁自审自闭环 / ANTI_SELF_CLOSE_BLOCKED)。`);
1452
+ } else if ((op === 'receipt' || op === 'deliver') && isInitiator) {
1453
+ console.error(` 👉 回执与交付(receipt/deliver)是接收方的专属职责,发起方禁止自填回执 (ANTI_SELF_RECEIPT_BLOCKED)。`);
1454
+ }
1455
+ } else {
1456
+ console.error(`❌ [Role Action Blocked (ROLE_ACTION_BLOCKED / ROLE_ACTION_VIOLATION)] Role [${l}] (${roleTitleEn}) is not permitted to execute action [baton ${op}]!`);
1457
+ console.error(` 👉 Allowed actions for this role: ${[...allowedActions].map(a => `baton ${a}`).join(', ')}`);
1458
+ if (l === 'audit' && !isInitiator) {
1459
+ console.error(` 👉 'audit' role is a reviewer: only allowed to submit receipt or reject, strictly prohibited from closing tickets (baton ${op})!`);
1460
+ } else if ((op === 'accept' || op === 'close') && !isInitiator) {
1461
+ console.error(` 👉 Ticket closure (accept/close) is reserved for the initiator; assignees cannot close their own tickets (执行方禁止自审自闭环 / ANTI_SELF_CLOSE_BLOCKED).`);
1462
+ } else if ((op === 'receipt' || op === 'deliver') && isInitiator) {
1463
+ console.error(` 👉 Submitting receipts (receipt/deliver) is reserved for assignees; initiators cannot submit receipts (禁止自填回执 / ANTI_SELF_RECEIPT_BLOCKED).`);
1464
+ }
1465
+ }
1466
+ process.exit(1);
1467
+ }
1468
+
1469
+ // 1. audit 角色的硬性白名单约束:
1470
+ // audit 角色作为接收/审查方时,其职责为签署回执(receipt)或驳回(reject)
1471
+ // 严禁执行 accept/close(不可自审自闭环)、forward(不可替发起方派发)、reopen
1472
+ if (l === 'audit') {
1473
+ if (!isInitiator) {
1474
+ if (op === 'accept' || op === 'close') {
1475
+ console.error(isZh
1476
+ ? `❌ [角色权限门禁拦截 (ROLE_ACTION_BLOCKED)] audit 角色为独立审查方,其职责为签署回执 (baton receipt --deliver) 或驳回 (baton reject),严禁执行闭环 (baton ${op})!\n 👉 终态验收闭环必须由发起方 (from_lane) 独立实测后执行。`
1477
+ : `❌ [Role Action Blocked (ROLE_ACTION_BLOCKED)] 'audit' role is a reviewer: only allowed to submit receipt or reject, strictly prohibited from closing tickets (baton ${op})!\n 👉 Final acceptance must be verified and closed by the initiator (from_lane).`);
1478
+ process.exit(1);
1479
+ }
1480
+ if (op === 'forward') {
1481
+ console.error(isZh
1482
+ ? `❌ [角色权限门禁拦截 (ROLE_ACTION_BLOCKED)] audit 角色为入站审查方,严禁重新 forward 本工单!\n 👉 交付请使用: baton receipt <id> --deliver,退回请使用: baton reject <id>`
1483
+ : `❌ [Role Action Blocked (ROLE_ACTION_BLOCKED)] 'audit' role is an inbound reviewer: prohibited from forwarding tickets!\n 👉 To deliver use: baton receipt <id> --deliver; to return use: baton reject <id>`);
1484
+ process.exit(1);
1485
+ }
1486
+ if (op === 'reopen') {
1487
+ console.error(isZh
1488
+ ? `❌ [角色权限门禁拦截 (ROLE_ACTION_BLOCKED)] audit 角色严禁执行 reopen。工单重开仅限发起方执行。`
1489
+ : `❌ [Role Action Blocked (ROLE_ACTION_BLOCKED)] 'audit' role is prohibited from reopening tickets.`);
1490
+ process.exit(1);
1491
+ }
1492
+ }
1493
+ }
1494
+
1495
+ // 2. 如果工单信息已知:校验当前角色是否与工单角色存在逆向错位
1496
+ if (ticketFm) {
1497
+ // 针对本工单的目标接收方(to_lane),无论其 lane 名称为何(audit / impl / pm / qa):
1498
+ // 一律禁止对自己接收执行的工单执行 accept/close!
1499
+ if (toLane && l === toLane) {
1500
+ if (op === 'accept' || op === 'close') {
1501
+ console.error(isZh
1502
+ ? `❌ [角色漂移与自审自闭环拦截 (ANTI_SELF_CLOSE_BLOCKED)] 当前执行身份 lane=${l} 是本工单的目标执行/审查方 (to_lane=${toLane})。\n 👉 终态验收闭环(accept/close)是发起方的专属特权,必须由发起方 (from_lane=${fromLanes.join('/')}) 独立实测执行,执行方禁止自审自闭环!`
1503
+ : `❌ [Anti-Self-Close Blocked (ANTI_SELF_CLOSE_BLOCKED)] Role lane=${l} is the assignee (to_lane=${toLane}) of this ticket.\n 👉 Ticket closure (accept/close) is reserved for the initiator (from_lane=${fromLanes.join('/')}); assignees cannot close their own tickets (执行方禁止自审自闭环)!`);
1504
+ process.exit(1);
1505
+ }
1506
+ }
1507
+ }
1508
+ }
1509
+
1510
+ /** 动态角色权能横幅输出(Context Re-anchoring · ADR-0019 / 借鉴 MetaGPT Prefix 与 RoleFix) */
1511
+ function printRoleCapabilityBanner(lane, boundTicket = null, boundRound = 1) {
1512
+ if (!lane) return;
1513
+ const l = lane.toLowerCase().trim();
1514
+ const isZh = detectLang() === 'zh';
1515
+ const roleTitle = resolveLaneRole(l) || l;
1516
+ const isAudit = l === 'audit';
1517
+ const isInitiator = ['coordinator', 'arch', 'lead', 'product'].includes(l);
1518
+ const ticketStr = boundTicket ? (isZh ? ` | 绑定工单: ${boundTicket} (Round ${boundRound || 1})` : ` | Bound Ticket: ${boundTicket} (Round ${boundRound || 1})`) : '';
1519
+
1520
+ if (isZh) {
1521
+ const allowed = isInitiator
1522
+ ? 'baton new / forward / wait / prompt / accept / close / reopen / status'
1523
+ : (isAudit ? 'baton receipt (--deliver) / reject / nonce / status' : 'baton receipt (--deliver) / status / check');
1524
+ const prohibited = isInitiator
1525
+ ? '无(发起方主管全生命周期调度)'
1526
+ : (isAudit ? 'baton accept / close (禁止自审自结) / forward / prompt' : 'baton accept / close (禁止越权关单) / forward / prompt');
1527
+ console.log(`[Baton 角色锚定] 当前身份: 【${roleTitle} (${l})】${ticketStr}`);
1528
+ console.log(` - 法定可用: ${allowed}`);
1529
+ console.log(` - 物理禁止: ${prohibited}\n`);
1530
+ } else {
1531
+ const allowed = isInitiator
1532
+ ? 'baton new / forward / wait / prompt / accept / close / reopen / status'
1533
+ : (isAudit ? 'baton receipt (--deliver) / reject / nonce / status' : 'baton receipt (--deliver) / status / check');
1534
+ const prohibited = isInitiator
1535
+ ? 'None (Initiator manages lifecycle)'
1536
+ : (isAudit ? 'baton accept / close (No self-closing) / forward / prompt' : 'baton accept / close (Assignee cannot close) / forward / prompt');
1537
+ console.log(`[Role Anchor] Role: [${roleTitle} (${l})]${ticketStr}`);
1538
+ console.log(` - Allowed: ${allowed}`);
1539
+ console.log(` - Prohibited: ${prohibited}\n`);
1540
+ }
1541
+ }
1542
+
1271
1543
  /** 会话身份锁 CLI 管理命令(ADR-0010) */
1272
1544
  function cmdLane(args) {
1273
1545
  const isZh = detectLang() === 'zh';
@@ -1288,10 +1560,12 @@ function cmdLane(args) {
1288
1560
  if (targetLane) {
1289
1561
  const laneNorm = targetLane.toLowerCase().trim();
1290
1562
  setSessionLane(laneNorm);
1563
+ const sessData = getSessionData();
1291
1564
  if (isJson) {
1292
1565
  console.log(JSON.stringify({ ok: true, session_id: getSessionId(), lane: laneNorm }));
1293
1566
  } else {
1294
1567
  console.log(isZh ? `✅ 当前会话身份已锁定为: ${laneNorm}` : `✅ Current session lane bound to: ${laneNorm}`);
1568
+ printRoleCapabilityBanner(laneNorm, sessData.bound_ticket, sessData.bound_round || 1);
1295
1569
  }
1296
1570
  return;
1297
1571
  }
@@ -1312,6 +1586,9 @@ function cmdLane(args) {
1312
1586
  return;
1313
1587
  }
1314
1588
 
1589
+ const sessData = getSessionData();
1590
+ printRoleCapabilityBanner(effectiveLane, sessData.bound_ticket, sessData.bound_round || 1);
1591
+
1315
1592
  if (isZh) {
1316
1593
  console.log(`🔐 Agent Baton 会话身份状态:`);
1317
1594
  console.log(` Session ID: ${sessionId}`);
@@ -1635,6 +1912,14 @@ function cmdNewIntra(args) {
1635
1912
  }
1636
1913
 
1637
1914
  function cmdStatus(args) {
1915
+ const isJson = args.includes('--json');
1916
+ if (!isJson) {
1917
+ const curLane = (flagValue(args, '--as') || flagValue(args, '--by') || getSessionLane() || process.env.HANDOFF_LANE || '').toLowerCase().trim();
1918
+ if (curLane) {
1919
+ const sessData = getSessionData();
1920
+ printRoleCapabilityBanner(curLane, sessData.bound_ticket, sessData.bound_round || 1);
1921
+ }
1922
+ }
1638
1923
  // 把解析到的根与模式显式传给 handoff-status.mjs,使其成为确定性入口(仓内根 ≠ 脚本目录)
1639
1924
  const filtered = args.filter(a => a !== '--root' && a !== '--mode' && !a.startsWith('--root=') && !a.startsWith('--mode='));
1640
1925
  try {
@@ -1718,15 +2003,48 @@ function cmdAccept(args) {
1718
2003
  return withTicketLock(id, () => {
1719
2004
  const content = fs.readFileSync(file, 'utf8');
1720
2005
  const fm = readFM(content);
2006
+
2007
+ const rFile = path.join(R_DIR, `${id}-resp.md`);
2008
+ let rFm = {};
2009
+ if (fs.existsSync(rFile)) {
2010
+ try { rFm = readFM(fs.readFileSync(rFile, 'utf8')) || {}; } catch {}
2011
+ }
2012
+ const currentSess = getSessionId();
2013
+ const deliveredByLane = String(fm?.delivered_by_lane || rFm?.delivered_by_lane || '').toLowerCase().trim();
2014
+ const deliveredBySession = fm?.delivered_by_session || rFm?.delivered_by_session;
2015
+
2016
+ // 1. 会话级自审自闭环拦截(单会话防人格分裂与冒充 · ADR-0018):
2017
+ // 若当前会话是完成该工单交付的会话(且与原发起会话不同),严禁自审自结
2018
+ if (deliveredBySession && currentSess && deliveredBySession === currentSess && fm?.conversation_id !== currentSess) {
2019
+ console.error(detectLang() === 'zh'
2020
+ ? `❌ [单会话角色漂移拦截 (SESSION_SELF_CLOSE_BLOCKED)] 当前会话 (session=${currentSess}) 是该工单的交付执行方!\n 👉 终态验收闭环(accept/close)必须由发起方独立实测后执行,严禁在执行方会话内自审自闭环!`
2021
+ : `❌ [Session Self-Close Blocked (SESSION_SELF_CLOSE_BLOCKED)] Current session (${currentSess}) delivered this ticket. Acceptance must be performed by initiator!`);
2022
+ process.exit(1);
2023
+ }
2024
+
2025
+ // 身份门禁(P0-3 修复 / ADR-0008 Phase 2 / ADR-0018 防角色漂移):
2026
+ // 角色命令物理白名单与单会话自审拦截优先级高于会话亲和性
2027
+ const callerLaneEarly = resolveExecutionLane(asLane, { fromLane: fm?.from_lane, toLane: fm?.to_lane, op: 'accept', ticketId: id });
2028
+ assertRoleCommandAllowed('accept', callerLaneEarly, fm);
2029
+
1721
2030
  assertSessionAffinity(fm, 'accept', id, args);
1722
2031
  const st = fm?.status;
1723
2032
 
1724
- // 身份门禁(P0-3 修复 / ADR-0008 Phase 2 显式声明):闭环(accept)是发起方的特权,执行方禁止自审自闭环
1725
2033
  if (MODE === 'intra-repo') {
1726
2034
  const fromLaneRaw = String(fm?.from_lane || '').toLowerCase();
1727
2035
  const fromLanes = fromLaneRaw.split(/[,/]/).map(s => s.trim()).filter(Boolean);
1728
- let cur = resolveExecutionLane(asLane, { fromLane: fm?.from_lane, toLane: fm?.to_lane, op: 'accept', ticketId: id });
2036
+ const toLane = String(fm?.to_lane || '').toLowerCase().trim();
2037
+ const sessionLane = getSessionLane();
2038
+
2039
+ let cur = callerLaneEarly;
1729
2040
  if (!cur) {
2041
+ // 如果当前会话曾作为交付方或被锁定为 to_lane,严禁静默推导为发起方
2042
+ if ((sessionLane && sessionLane === toLane) || (deliveredByLane && sessionLane === deliveredByLane)) {
2043
+ console.error(detectLang() === 'zh'
2044
+ ? `❌ [自审自闭环拦截 (ANTI_SELF_CLOSE_BLOCKED)] 当前会话已锁定为执行/审查方 (lane=${sessionLane})。终态验收闭环是发起方的专属特权,执行方严禁自审自闭环!`
2045
+ : `❌ [Anti-Self-Close Blocked (ANTI_SELF_CLOSE_BLOCKED)] Current session is locked as receiver lane=${sessionLane}.`);
2046
+ process.exit(1);
2047
+ }
1730
2048
  if (fromLanes.length === 1) {
1731
2049
  cur = fromLanes[0];
1732
2050
  const isZh = detectLang() === 'zh';
@@ -1741,6 +2059,9 @@ function cmdAccept(args) {
1741
2059
  process.exit(1);
1742
2060
  }
1743
2061
  }
2062
+
2063
+ // 角色物理白名单与单向流转校验
2064
+ assertRoleCommandAllowed('accept', cur, fm);
1744
2065
  if (!fromLanes.includes(cur)) {
1745
2066
  console.error(`❌ 越界闭环:当前执行身份 lane=${cur} 不是发起方 from_lane=${fromLaneRaw}。执行方禁止自审自闭环。`);
1746
2067
  process.exit(1);
@@ -1758,10 +2079,9 @@ function cmdAccept(args) {
1758
2079
  }
1759
2080
 
1760
2081
  // P0-a:闭环前置内容门禁——delivered/received 必有回执,且该回执须过「锚节 + 转递提示词 + evidence」,否则拒绝闭环。
1761
- const rFile = path.join(R_DIR, `${id}-resp.md`);
1762
2082
  if (!fs.existsSync(rFile)) { console.error(`❌ 找不到回执: ${rFile}(delivered/received 状态应已有回执)`); process.exit(1); }
1763
2083
  const rRaw = fs.readFileSync(rFile, 'utf8');
1764
- const rFm = readFM(rRaw) || {};
2084
+ rFm = readFM(rRaw) || {};
1765
2085
 
1766
2086
  // 终态交付硬门禁(v2.18 · 防抢跑闭环):缺 delivered_at 拒绝闭环(杜绝执行方会话未结束即被抢先闭环)
1767
2087
  const deliveredAt = fm.delivered_at || rFm.delivered_at;
@@ -1846,6 +2166,12 @@ function cmdAccept(args) {
1846
2166
  logStateJournal(id, 'accept', { from_status: st, to_status: 'closed', accepted_at: now, note });
1847
2167
  console.log(`✅ 已审计闭环: ${id}(验收记录已写入交接文档)`);
1848
2168
 
2169
+ // 清空会话锁定的工单(ADR-0019 会话闭环解绑)
2170
+ const sessData = getSessionData();
2171
+ if (sessData.bound_ticket && String(sessData.bound_ticket).toLowerCase() === String(id).toLowerCase()) {
2172
+ setSessionData({ bound_ticket: '', bound_round: 1 });
2173
+ }
2174
+
1849
2175
  // 清理注册表避免孤儿文件 (D2)
1850
2176
  const watchFile = path.join(ROOT, '.watch', `${id}.json`);
1851
2177
  try { if (fs.existsSync(watchFile)) fs.unlinkSync(watchFile); } catch {}
@@ -1870,7 +2196,14 @@ function cmdAccept(args) {
1870
2196
  function cmdReject(args) {
1871
2197
  const noteIdx = args.indexOf('-n');
1872
2198
  const rawNote = noteIdx !== -1 ? args[noteIdx + 1]?.trim() : undefined;
1873
- const note = rawNote !== undefined ? rawNote.replace(/\\r\\n/g, '\n').replace(/\\n/g, '\n') : undefined;
2199
+ let note = rawNote !== undefined ? rawNote.replace(/\\r\\n/g, '\n').replace(/\\n/g, '\n') : undefined;
2200
+ if (note && /(?:##\s*(?:Baton Pass Prompt|交接提示词)|Please\s+\[.*\]\s+take\s+handoff|请\s*\[.*\]\s*接单)/i.test(note)) {
2201
+ const isZh = detectLang() === 'zh';
2202
+ console.warn(isZh
2203
+ ? `⚠️ [反向交接卡片清洗] 检测到回执正文包含出站交接提示词卡片(这是发起方的专有行为,接收方严禁反向输出)。已自动清除该片段,防止双向乒乓混淆。`
2204
+ : `⚠️ [Anti-Reverse Prompt] Stripped outbound handoff prompt card from receipt body.`);
2205
+ note = note.replace(/(?:##\s*(?:Baton Pass Prompt|交接提示词)[\s\S]*?(?:```[\s\S]*?```|$)|```text\s*请\s*\[.*\]\s*接单[\s\S]*?```|```text\s*Please\s*\[.*\]\s*take\s*handoff[\s\S]*?```)/gi, '').trim();
2206
+ }
1874
2207
  const byIdx = args.indexOf('--by');
1875
2208
  const asIdx = args.indexOf('--as');
1876
2209
  const byArg = byIdx !== -1 ? args[byIdx + 1]?.trim() : undefined;
@@ -1894,6 +2227,7 @@ function cmdReject(args) {
1894
2227
  const rawH = fs.readFileSync(file, 'utf8');
1895
2228
  const hFm = readFM(rawH);
1896
2229
  const st = hFm?.status;
2230
+ assertTicketAffinity(id, 'reject', args);
1897
2231
 
1898
2232
  // 身份门禁:允许发起方驳回执行方交付,亦允许审计方(to_lane=audit)对被审工单给出驳回裁决
1899
2233
  let cur = resolveExecutionLane(asArg || byArg, { fromLane: hFm?.from_lane, toLane: hFm?.to_lane, op: 'reject', ticketId: id });
@@ -1939,6 +2273,8 @@ function cmdReject(args) {
1939
2273
  isFromLane = true;
1940
2274
  }
1941
2275
 
2276
+ assertRoleCommandAllowed('reject', cur, hFm);
2277
+
1942
2278
  if (st === 'draft' && !isAuditor && !isFromLane) {
1943
2279
  console.error(`❌ 交接 ${id} 当前为 draft,尚无登记回执或交付,不能驳回${fs.existsSync(path.join(R_DIR, `${id}-resp.md`)) ? `;检测到回执文件,请先 baton deliver ${id} 交付后再核验驳回` : ''}。`);
1944
2280
  process.exit(1);
@@ -1968,6 +2304,7 @@ function cmdReject(args) {
1968
2304
  const rFile = path.join(R_DIR, `${id}-resp.md`);
1969
2305
  let rHash = '';
1970
2306
  const nextRound = (Number(hFm?.round) || 1) + 1;
2307
+ bindSessionTicket(id, nextRound);
1971
2308
  const rejEntry = `- 日期:${todayISO()}\n- 理由:${note}\n`;
1972
2309
  const rejTicketEntry = `- 轮次:Round ${nextRound}(驳回方: ${cur})\n- 日期:${todayISO()}\n- 理由:${note}\n`;
1973
2310
  const updatedTicket = insertRejectionEntry(rawH, rejTicketEntry);
@@ -2042,19 +2379,23 @@ function cmdReject(args) {
2042
2379
  const rejectorRole = resolveLaneRole(cur) || (isZh ? '驳回方' : 'Rejector');
2043
2380
  const targetLane = (isAuditor || !isFromLane) ? (hFm?.from_lane || 'impl') : (hFm?.to_lane || 'impl');
2044
2381
  const targetRole = resolveLaneRole(targetLane) || (isZh ? '实现方' : 'Implementer');
2382
+ const rDisplay = path.join(H_DIR, `../receipts/${id}-resp.md`);
2383
+ const rCleanDisplay = rDisplay.startsWith(os.homedir()) ? '~' + rDisplay.slice(os.homedir().length) : rDisplay;
2384
+ const cleanNote = (note || '').split('\n')[0].trim().slice(0, 40);
2385
+ const noteSuffix = cleanNote ? ` · ${cleanNote}` : '';
2045
2386
  let verdictLine;
2046
2387
  if (cur === 'audit') {
2047
2388
  verdictLine = isZh
2048
- ? `审计完成,裁决 NO-GO(工单已退回${targetRole}进入 Round ${nextRound})`
2049
- : `Audit complete, verdict NO-GO (Ticket returned to ${targetRole} entering Round ${nextRound})`;
2389
+ ? `请 [${targetLane}] 按驳回记录修订并重新交付 [${id}]:${rCleanDisplay}(Round ${nextRound} · NO-GO${noteSuffix})\n(审计完成,裁决 NO-GO(工单已退回${targetRole}进入 Round ${nextRound}))`
2390
+ : `Please [${targetLane}] revise per rejection record and re-deliver [${id}]: ${rCleanDisplay} (Round ${nextRound} · NO-GO${noteSuffix})\n(Audit complete, verdict NO-GO (Ticket returned to ${targetRole} entering Round ${nextRound}))`;
2050
2391
  } else if (isFromLane) {
2051
2392
  verdictLine = isZh
2052
- ? `${rejectorRole}验收未通过,裁决 NO-GO(工单已退回${targetRole}进入 Round ${nextRound})`
2053
- : `${rejectorRole} verification failed, verdict NO-GO (Ticket returned to ${targetRole} entering Round ${nextRound})`;
2393
+ ? `请 [${targetLane}] 按驳回记录修订并重新交付 [${id}]:${rCleanDisplay}(Round ${nextRound} · NO-GO${noteSuffix})\n(${rejectorRole}验收未通过,裁决 NO-GO(工单已退回${targetRole}进入 Round ${nextRound}))`
2394
+ : `Please [${targetLane}] revise per rejection record and re-deliver [${id}]: ${rCleanDisplay} (Round ${nextRound} · NO-GO${noteSuffix})\n(${rejectorRole} verification failed, verdict NO-GO (Ticket returned to ${targetRole} entering Round ${nextRound}))`;
2054
2395
  } else {
2055
2396
  verdictLine = isZh
2056
- ? `${rejectorRole}驳回退回,裁决 NO-GO(工单已退回${targetRole}进入 Round ${nextRound})`
2057
- : `${rejectorRole} rejected, verdict NO-GO (Ticket returned to ${targetRole} entering Round ${nextRound})`;
2397
+ ? `请 [${targetLane}] 按驳回记录修订并重新交付 [${id}]:${rCleanDisplay}(Round ${nextRound} · NO-GO${noteSuffix})\n(${rejectorRole}驳回退回,裁决 NO-GO(工单已退回${targetRole}进入 Round ${nextRound}))`
2398
+ : `Please [${targetLane}] revise per rejection record and re-deliver [${id}]: ${rCleanDisplay} (Round ${nextRound} · NO-GO${noteSuffix})\n(${rejectorRole} rejected, verdict NO-GO (Ticket returned to ${targetRole} entering Round ${nextRound}))`;
2058
2399
  }
2059
2400
  if (isZh) {
2060
2401
  console.log(`\nℹ️ 裁决收尾(接收方回复末尾仅单行纯文本,无需标题与代码块):`);
@@ -2094,6 +2435,8 @@ function cmdReopen(args) {
2094
2435
  const fm = readFM(content);
2095
2436
  if (!fm) { console.error('工单损坏: ' + file); process.exit(1); }
2096
2437
  assertSessionAffinity(fm, 'reopen', id, args);
2438
+ const curReopen = (asLane || getSessionLane() || process.env.HANDOFF_LANE || '').toLowerCase();
2439
+ assertRoleCommandAllowed('reopen', curReopen, fm);
2097
2440
  if (fm.status !== 'closed') {
2098
2441
  console.error(`❌ 工单 ${id} 当前状态为 ${fm.status},仅 closed 状态允许重开。`);
2099
2442
  process.exit(1);
@@ -2189,18 +2532,18 @@ function extractConclusion(raw) {
2189
2532
  * **仓内(v2.13 修复):严禁 detectRepo 拼仓库名**,改读回执 frontmatter 的 from_lane/to_lane,
2190
2533
  * 用 resolveLaneRole 拼自然角色(杜绝「请收 Tappy 回执」式把项目名当沟通角色的事故)。 */
2191
2534
  function printReceiptDeliveryLine(rFile, needsChange, isDelivered = false) {
2192
- let lines = 0, bytes = 0, fromLane = '', toLane = '', rawText = '', ticketId = '';
2535
+ let lines = 0, bytes = 0, fromLane = '', toLane = '', rawText = '', ticketId = '', rFm = {};
2193
2536
  try {
2194
2537
  const buf = fs.readFileSync(rFile);
2195
2538
  bytes = buf.length;
2196
2539
  const text = buf.toString('utf8');
2197
2540
  rawText = text;
2198
2541
  lines = text.split('\n').length - (text.endsWith('\n') ? 1 : 0);
2199
- const fm = readFM(text) || {};
2200
- fromLane = fm.from_lane || '';
2201
- toLane = fm.to_lane || '';
2202
- ticketId = fm.handoff_id || path.basename(rFile).replace(/-resp\.md$/, '');
2203
- if (fm.delivered_at) isDelivered = true;
2542
+ rFm = readFM(text) || {};
2543
+ fromLane = rFm.from_lane || '';
2544
+ toLane = rFm.to_lane || '';
2545
+ ticketId = rFm.handoff_id || path.basename(rFile).replace(/-resp\.md$/, '');
2546
+ if (rFm.delivered_at) isDelivered = true;
2204
2547
  } catch { /* 读不到不阻断主流程 */ }
2205
2548
  const flag = needsChange ? '是' : '否';
2206
2549
  const display = rFile.startsWith(os.homedir()) ? '~' + rFile.slice(os.homedir().length) : rFile;
@@ -2210,16 +2553,29 @@ function printReceiptDeliveryLine(rFile, needsChange, isDelivered = false) {
2210
2553
  const fromRole = resolveLaneRole(fromLane) || fromLane || (isZh ? '本方' : 'Executor');
2211
2554
  if (isDelivered) {
2212
2555
  console.log(`\n✅ 仓内终态交付已生效 [${ticketId}](状态推进为 delivered,后台监听已自动感知平息并唤醒发起方 [${toRole}] 进行独立验收闭环)。`);
2556
+ const rRaw = rawText ? stripFM(rawText) : '';
2557
+ const rConcl = extractConclusion(rRaw) || (needsChange ? '需整改' : 'PASS');
2558
+ const rBodyClean = rRaw.replace(/^#+.*$/gm, '').replace(/[-*]\s+/g, '').replace(/\s+/g, ' ').trim();
2559
+ const rSummary = rBodyClean ? ` · ${rBodyClean.slice(0, 35)}` : '';
2560
+ let roundNum = rFm.round || 1;
2561
+ try {
2562
+ const hFmCheck = readFM(fs.readFileSync(path.join(H_DIR, `${ticketId}.md`), 'utf8')) || {};
2563
+ if (hFmCheck.round) roundNum = hFmCheck.round;
2564
+ } catch {}
2213
2565
  const verdictLine = fromLane === 'audit'
2214
- ? (isZh ? `审计完成,裁决 GO` : `Audit complete, verdict GO`)
2215
- : (isZh ? `交付完成,回执已就绪 [${ticketId}]:${display}` : `Delivery complete, receipt ready [${ticketId}]: ${display}`);
2566
+ ? (isZh
2567
+ ? `请 [${toLane || 'initiator'}] 查收审计回执并闭环工单 [${ticketId}]:${display}(Round ${roundNum} · GO · ${rConcl}${rSummary})\n(审计完成,裁决 GO)`
2568
+ : `Please [${toLane || 'initiator'}] review audit receipt and close ticket [${ticketId}]: ${display} (Round ${roundNum} · GO · ${rConcl}${rSummary})\n(Audit complete, verdict GO)`)
2569
+ : (isZh
2570
+ ? `请 [${toLane || 'initiator'}] 查收交付回执并独立实测 [${ticketId}]:${display}(Round ${roundNum} · DELIVERED · ${rConcl}${rSummary})\n(交付完成,回执已就绪 [${ticketId}]:${display})`
2571
+ : `Please [${toLane || 'initiator'}] review delivery receipt and verify tests [${ticketId}]: ${display} (Round ${roundNum} · DELIVERED · ${rConcl}${rSummary})\n(Delivery complete, receipt ready [${ticketId}]: ${display})`);
2216
2572
  if (isZh) {
2217
- console.log(`\nℹ️ 交付收尾(接收方回复末尾仅单行纯文本,无需标题与代码块):`);
2218
- console.log(verdictLine + '\n');
2573
+ console.log(`\nℹ️ 交付收尾(接收方回复末尾单行纯文本,建议格式):`);
2574
+ console.log(verdictLine.split('\n')[0] + '\n');
2219
2575
  console.log(`💡 [接收方纪律] 本端职责已完成,闭环(accept/close)归发起方所有,严禁接收方越权闭环;严禁反向输出交接卡片。\n`);
2220
2576
  } else {
2221
- console.log(`\nℹ️ Delivery Epilogue (Receiver outputs single plain-text line at the end, no headers or code blocks):`);
2222
- console.log(verdictLine + '\n');
2577
+ console.log(`\nℹ️ Delivery Epilogue (Receiver outputs single line at the end, recommended format):`);
2578
+ console.log(verdictLine.split('\n')[0] + '\n');
2223
2579
  console.log(`💡 [Receiver Rule] This lane task is complete. Ticket closure (accept/close) is reserved for the initiator.\n`);
2224
2580
  }
2225
2581
  } else {
@@ -2247,7 +2603,14 @@ function cmdReceipt(args) {
2247
2603
  const asInput = flagValue(args, '--as') || flagValue(args, '--by');
2248
2604
  const noteIdx = args.indexOf('-n');
2249
2605
  const rawNote = noteIdx !== -1 ? args[noteIdx + 1]?.trim() : undefined;
2250
- const note = rawNote !== undefined ? rawNote.replace(/\\r\\n/g, '\n').replace(/\\n/g, '\n') : undefined;
2606
+ let note = rawNote !== undefined ? rawNote.replace(/\\r\\n/g, '\n').replace(/\\n/g, '\n') : undefined;
2607
+ if (note && /(?:##\s*(?:Baton Pass Prompt|交接提示词)|Please\s+\[.*\]\s+take\s+handoff|请\s*\[.*\]\s*接单)/i.test(note)) {
2608
+ const isZh = detectLang() === 'zh';
2609
+ console.warn(isZh
2610
+ ? `⚠️ [反向交接卡片清洗] 检测到回执正文包含出站交接提示词卡片(这是发起方的专有行为,接收方严禁反向输出)。已自动清除该片段,防止双向乒乓混淆。`
2611
+ : `⚠️ [Anti-Reverse Prompt] Stripped outbound handoff prompt card from receipt body.`);
2612
+ note = note.replace(/(?:##\s*(?:Baton Pass Prompt|交接提示词)[\s\S]*?(?:```[\s\S]*?```|$)|```text\s*请\s*\[.*\]\s*接单[\s\S]*?```|```text\s*Please\s*\[.*\]\s*take\s*handoff[\s\S]*?```)/gi, '').trim();
2613
+ }
2251
2614
  // evidence flags(P0-c):CLI 传入可核验证据,落进 frontmatter 供门禁/check 校验
2252
2615
  const evidenceFlags = {
2253
2616
  commits: flagValue(args, '--evidence-commits'),
@@ -2269,8 +2632,10 @@ function cmdReceipt(args) {
2269
2632
  return withTicketLock(id, () => {
2270
2633
  const hFm = readFM(fs.readFileSync(hFile, 'utf8'));
2271
2634
  const st = hFm?.status;
2635
+ assertTicketAffinity(id, explicitDeliver ? 'deliver' : 'receipt', args);
2272
2636
  // 防提前闭环(v2.13 / v2.25 P0-3 强化 / ADR-0008 Phase 2 显式声明):发起方禁止自填回执,且仓内模式强制校验执行身份
2273
2637
  const cur = resolveExecutionLane(asInput, { fromLane: hFm?.from_lane, toLane: hFm?.to_lane, op: explicitDeliver ? 'deliver' : 'receipt', ticketId: id });
2638
+ assertRoleCommandAllowed(explicitDeliver ? 'deliver' : 'receipt', cur, hFm);
2274
2639
  if (MODE === 'intra-repo') {
2275
2640
  const toLane = String(hFm?.to_lane || '').toLowerCase();
2276
2641
  const fromLane = String(hFm?.from_lane || '').toLowerCase();
@@ -2288,6 +2653,7 @@ function cmdReceipt(args) {
2288
2653
  process.exit(1);
2289
2654
  }
2290
2655
  }
2656
+ bindSessionTicket(id, hFm?.round || 1, args.includes('--force-ticket') || process.env.BATON_FORCE_TICKET === '1');
2291
2657
  // 状态转换合法性内联(v2.6;v2.12.5 放开 draft):draft/forwarded → received。
2292
2658
  if (st === 'draft') {
2293
2659
  console.log(`ℹ️ ${id} 仍为 draft(发起方未跑可选标记 forward)→ 直接登记回执(draft → received)。`);
@@ -2447,7 +2813,11 @@ function cmdReceipt(args) {
2447
2813
  writeReceiptFile(rFile, rFm, note, receiptStubIntra(id, hFm.from_lane || ''));
2448
2814
  setFM(hFile, { status: 'received', needs_change: needsChange });
2449
2815
  if (shouldDeliver) {
2450
- cmdDeliver([id, '--as', cur]);
2816
+ const deliverArgs = [id, '--as', cur];
2817
+ if (args.includes('--force-ticket')) deliverArgs.push('--force-ticket');
2818
+ if (args.includes('--force-session')) deliverArgs.push('--force-session');
2819
+ if (args.includes('--auto-nonce')) deliverArgs.push('--auto-nonce');
2820
+ cmdDeliver(deliverArgs);
2451
2821
  return;
2452
2822
  }
2453
2823
  logStateJournal(id, 'receipt', {
@@ -2475,7 +2845,10 @@ function cmdReceipt(args) {
2475
2845
  const authorLabel = `${TARGET_LABELS[hTarget] || hTarget} 侧回执`;
2476
2846
  writeReceiptFile(rFile, rFm, note, receiptStub(id, authorLabel));
2477
2847
  if (shouldDeliver) {
2478
- cmdDeliver([id]);
2848
+ const deliverArgs = [id];
2849
+ if (args.includes('--force-ticket')) deliverArgs.push('--force-ticket');
2850
+ if (args.includes('--force-session')) deliverArgs.push('--force-session');
2851
+ cmdDeliver(deliverArgs);
2479
2852
  return;
2480
2853
  }
2481
2854
  setFM(hFile, { status: 'received', needs_change: needsChange, needs_iggle_change: needsChange });
@@ -2496,7 +2869,14 @@ function cmdReceipt(args) {
2496
2869
  function cmdDeliver(args) {
2497
2870
  const noteIdx = args.indexOf('-n');
2498
2871
  const rawNote = noteIdx !== -1 ? args[noteIdx + 1]?.trim() : undefined;
2499
- const note = rawNote !== undefined ? rawNote.replace(/\\r\\n/g, '\n').replace(/\\n/g, '\n') : undefined;
2872
+ let note = rawNote !== undefined ? rawNote.replace(/\\r\\n/g, '\n').replace(/\\n/g, '\n') : undefined;
2873
+ if (note && /(?:##\s*(?:Baton Pass Prompt|交接提示词)|Please\s+\[.*\]\s+take\s+handoff|请\s*\[.*\]\s*接单)/i.test(note)) {
2874
+ const isZh = detectLang() === 'zh';
2875
+ console.warn(isZh
2876
+ ? `⚠️ [反向交接卡片清洗] 检测到回执正文包含出站交接提示词卡片(这是发起方的专有行为,接收方严禁反向输出)。已自动清除该片段,防止双向乒乓混淆。`
2877
+ : `⚠️ [Anti-Reverse Prompt] Stripped outbound handoff prompt card from receipt body.`);
2878
+ note = note.replace(/(?:##\s*(?:Baton Pass Prompt|交接提示词)[\s\S]*?(?:```[\s\S]*?```|$)|```text\s*请\s*\[.*\]\s*接单[\s\S]*?```|```text\s*Please\s*\[.*\]\s*take\s*handoff[\s\S]*?```)/gi, '').trim();
2879
+ }
2500
2880
  const asInput = flagValue(args, '--as') || flagValue(args, '--by');
2501
2881
  const valFlags = ['-n', '--evidence-commits', '--evidence-paths', '--evidence-repo', '--evidence-note', '--as', '--by'];
2502
2882
  const valueIdx = new Set();
@@ -2516,6 +2896,7 @@ function cmdDeliver(args) {
2516
2896
  const hRaw = fs.readFileSync(hFile, 'utf8');
2517
2897
  const hFm = readFM(hRaw) || {};
2518
2898
  const st = hFm?.status;
2899
+ assertTicketAffinity(id, 'deliver', args);
2519
2900
  if (st === 'closed') {
2520
2901
  console.log(`↩️ ${id} 已闭环,跳过交付。`);
2521
2902
  return;
@@ -2530,6 +2911,8 @@ function cmdDeliver(args) {
2530
2911
 
2531
2912
  // 防提前闭环与越界交付(P0-3 修复 / ADR-0008 Phase 2 显式声明)
2532
2913
  const cur = resolveExecutionLane(asInput, { fromLane: hFm?.from_lane, toLane: hFm?.to_lane, op: 'deliver', ticketId: id });
2914
+ assertRoleCommandAllowed('deliver', cur, hFm);
2915
+ bindSessionTicket(id, hFm?.round || 1, args.includes('--force-ticket') || process.env.BATON_FORCE_TICKET === '1');
2533
2916
  if (MODE === 'intra-repo') {
2534
2917
  const toLane = String(hFm?.to_lane || '').toLowerCase();
2535
2918
  const fromLane = String(hFm?.from_lane || '').toLowerCase();
@@ -2647,9 +3030,11 @@ function cmdDeliver(args) {
2647
3030
  }
2648
3031
 
2649
3032
  const nowISO = new Date().toISOString();
3033
+ const currentSess = getSessionId();
2650
3034
  // 写入回执 frontmatter
2651
3035
  const updatedRFm = { ...rFm, delivered_at: nowISO, needs_change: false };
2652
3036
  if (cur) updatedRFm.delivered_by_lane = cur;
3037
+ if (currentSess) updatedRFm.delivered_by_session = currentSess;
2653
3038
  writeReceiptFile(rFile, updatedRFm, undefined, rBody);
2654
3039
 
2655
3040
  // 写入交接 frontmatter(保留 rejected_at 供历史追溯与校验)
@@ -2658,6 +3043,8 @@ function cmdDeliver(args) {
2658
3043
  delivered_at: nowISO,
2659
3044
  needs_change: false
2660
3045
  };
3046
+ if (cur) updateHFm.delivered_by_lane = cur;
3047
+ if (currentSess) updateHFm.delivered_by_session = currentSess;
2661
3048
  if (note) updateHFm.delivery_note = note;
2662
3049
  setFM(hFile, updateHFm);
2663
3050
  logStateJournal(id, 'deliver', { from_status: st, to_status: 'delivered', delivered_at: nowISO, note });
@@ -2931,6 +3318,11 @@ async function cmdForward(args) {
2931
3318
  assertSessionAffinity(fm, 'forward', id, args);
2932
3319
  const toLane = String(fm?.to_lane || fm?.target || '').toLowerCase();
2933
3320
  const ticketFrom = String(fm?.from_lane || '').toLowerCase();
3321
+ const asLane = flagValue(args, '--as') || flagValue(args, '--by');
3322
+ if (asLane) {
3323
+ const curLane = resolveExecutionLane(asLane, { fromLane: ticketFrom, toLane, op: 'forward', ticketId: id });
3324
+ assertRoleCommandAllowed('forward', curLane, fm);
3325
+ }
2934
3326
  if (!getSessionLane() && ticketFrom) {
2935
3327
  setSessionLane(ticketFrom);
2936
3328
  }
@@ -3023,7 +3415,7 @@ async function cmdForward(args) {
3023
3415
  }
3024
3416
 
3025
3417
  // 无论跨仓还是仓内(含 same / separate),一律输出标准交接提示词供一键复制
3026
- cmdPrompt([id]);
3418
+ cmdPrompt([id, '--internal-forward']);
3027
3419
  }
3028
3420
 
3029
3421
  if (isDaemon || shouldWait) {
@@ -3147,6 +3539,12 @@ function cmdShow(args) {
3147
3539
  console.log(fm.audit_nonce);
3148
3540
  return;
3149
3541
  }
3542
+ bindSessionTicket(id, fm?.round || 1);
3543
+ const asLane = flagValue(args, '--as') || flagValue(args, '--by');
3544
+ const curLane = resolveExecutionLane(asLane, { fromLane: fm?.from_lane, toLane: fm?.to_lane, op: 'show', ticketId: id });
3545
+ if (curLane && !args.includes('--json')) {
3546
+ printRoleCapabilityBanner(curLane, id, fm?.round || 1);
3547
+ }
3150
3548
  const body = stripFM(raw);
3151
3549
  console.log(`# ${id}`);
3152
3550
  const keys = isResp
@@ -3241,7 +3639,7 @@ const STUB_BODY_ZH = `### Agent Baton (Handoff) 接入桩(轻量韧性版 ·
3241
3639
 
3242
3640
  **核心守卫与身份(强制)**
3243
3641
  - **物理工作区边界**:会话严格绑定当前宿主工作区,严禁跨仓 cd 操作外部代码;跨仓请输出交接提示词引导人类在目标仓 Agent 会话中派发。
3244
- - **一单到底与会话ID统一(强制 · v2.36.0)**:工单物理 ID 即为会话 ID(全局唯一统一),严禁物理 ID 与会话 ID 分裂。所有轮次(Round 1..N)在原单同一 ID 下流转闭环,严禁轮次变异;任务主题全生命周期保持一致。
3642
+ - **一单到底与互斥粘性锁(强制 · v2.44.0)**:工单物理 ID 即为会话 ID(全局唯一统一),严禁物理 ID 与会话 ID 分裂。同一接单会话严格绑定单一工单(一单到底),严禁跨工单越界写操作(CROSS_TICKET_CONTAMINATION_BLOCKED);所有轮次(Round 1..N)在原单同一 ID 下流转闭环,严禁轮次变异;任务主题全生命周期保持一致。
3245
3643
  - **严禁跨会话处理工单(最高宪法级隔离)**:工单全程严格绑定发起会话;严禁跨会话处理/推进/闭环外部工单(\`forward\`/\`accept\`/\`reopen\` 仅限原发起会话执行;接收方接单必须显式带工单编号,严禁从全局待办中盲目抢单)。
3246
3644
  - **命令形态与显式身份**:一律 \`baton <op>\` 或 \`handoff <op>\`。全面支持 \`--as <lane>\` 显式声明身份,同一会话无缝切换多工单。
3247
3645
  - **会话身份锁与凭证防伪**:支持 \`baton lane <lane>\` 锁定会话身份;环境绑定优先级 \`HANDOFF_LANE\` > \`baton lane\` > \`--as <lane>\`;审计交付必须持有 \`audit.token\` 密码学签章,禁止发起方跨角色自我闭环。
@@ -3250,28 +3648,29 @@ const STUB_BODY_ZH = `### Agent Baton (Handoff) 接入桩(轻量韧性版 ·
3250
3648
  **入站工作流(接单 · 交付 · 退回)**
3251
3649
  1. **查待办**:运行 \`baton status --as <本方 lane|target> --current\`(或全局 \`baton status --current\`)。
3252
3650
  2. **读工单**:运行 \`baton show <id>\`,根据验收判据改动本 lane 范围代码并实测。
3253
- 3. **交付或退回(实测为唯一准绳)**:
3254
- - **实测通过**:照抄 \`$(lab path handoffs)/RESPONSE-TEMPLATE.md\` 骨架 → 运行 \`baton receipt <id> -n "<正文>" --deliver --as <本方 lane> --evidence-paths "<路径>"\`(审计工单附 \`--audit-nonce "<nonce>"\` 或同工作区授权下使用 \`--auto-nonce\` 自动绑定最新令牌;红队用例严格遵循 NO_DISPATCH / NO_COMPLETE / COMPLETE 三态标准)。
3651
+ 3. **交付或退回(实测为唯一准绳 · 必须调用 CLI 推进状态 · 必须写成 Markdown)**:
3652
+ - **格式铁律**:无论是开单还是回执,必须严格使用标准 Markdown 格式(.md),严禁写成无结构的纯文本(.txt)!
3653
+ - **实测通过**:严格遵循 \`$(lab path handoffs)/RESPONSE-TEMPLATE.md\` 骨架撰写回执(包含状态/结论锚节与明确结论)→ 运行 \`baton receipt <id> -n "<正文>" --deliver --as <本方 lane> --evidence-paths "<路径>"\`(审计工单附 \`--audit-nonce "<nonce>"\` 或同工作区授权下使用 \`--auto-nonce\` 自动绑定最新令牌;红队用例严格遵循 NO_DISPATCH / NO_COMPLETE / COMPLETE 三态标准;**严禁只写 Markdown 文件不翻状态**,必须通过 CLI 推进工单状态至 delivered!)。
3255
3654
  - **实测未过(NO-GO/受阻)**:审计方享有安全下车通道,运行 \`baton reject <id> -n "<理由/差异在哪>" --as audit\` 退回整改;普通执行方若受阻/缺失条件,登记受阻回执 \`baton receipt <id> -n "<缺失条件/受阻理由>" --evidence-note "<说明>" --as <本方 lane>\` 由发起方核实并处理。
3256
3655
  4. **收尾自检**:运行 \`baton check [id]\`(若有数据漂移可加 \`--fix\` 自动修复)。
3257
- 5. **入站回复收尾(简洁单行裁决 · 严禁角色漂移)**:接收方必须严格保持本方执行/审计角色,严禁切换为发起方角色;**严禁反向输出 \`## 交接提示词\` 卡片或调用 \`baton close\` 越权闭环**;最终回复人类的最末尾仅输出单行纯文本(无需标题,无需代码块,严禁多行出站卡片):
3258
- - 审计驳回:\`审计完成,裁决 NO-GO(工单已退回<发起方角色>进入 Round <N>)\`
3259
- - 审计通过:\`审计完成,裁决 GO\`
3260
- - 普通交付:\`交付完成,回执已就绪\`
3261
- 后续 Round 轮次由发起方在出站重新转递时统筹计算并派发。
3656
+ 5. **入站回复收尾(简洁单行裁决 · 严禁角色漂移 · 方案 A 权威标准)**:接收方受 CLI 物理权限白名单锁定,硬拦截 close/forward/prompt;接收方必须严格保持本方执行/审计角色,严禁切换为发起方角色;**严禁反向输出 \`## Baton Pass Prompt\` 卡片或调用 \`baton close\` 越权闭环**;最终回复人类的最末尾仅输出单行纯文本(无需标题,无需代码块,严禁多行出站卡片):
3657
+ - 审计驳回:\`请 [<目标角色>] 按驳回记录修订并重新交付 [<工单编号>]:<回执路径>(Round <轮次> · NO-GO · <一句话驳回原因>)\`
3658
+ - 审计通过:\`请 [<发起角色>] 查收审计回执并闭环工单 [<工单编号>]:<回执路径>(Round <轮次> · GO · <一句话通过总结>)\`
3659
+ - 普通交付:\`请 [<审查角色>] 查收交付回执并独立实测 [<工单编号>]:<回执路径>(Round <轮次> · DELIVERED · <一句话完成摘要>)\`
3660
+ (兼容极简格式:\`审计完成,裁决 NO-GO / GO / 交付完成,回执已就绪\`;后续 Round 轮次由发起方在出站重新转递时统筹计算并派发)。
3262
3661
 
3263
3662
  **出站工作流(派发 · 监听 · 严禁漏开监听)**
3264
- 1. **建单与转递(单工单原子闭环 · 99%场景)**:\`baton new <target|lane> <type> "<标题>"\`,填写正文后直接作为宿主后台任务(如 \`WaitMsBeforeAsync: 500\`)运行 \`baton forward <id> --wait\`(双盲审计附加 \`--blind\` 脱敏思考自辩;单工单严禁使用 \`--async\` 拆分两步!)。
3663
+ 1. **建单与转递(单工单原子闭环 · 99%场景)**:\`baton new <target|lane> <type> "<标题>"\`,填写正文后直接作为宿主后台任务(如 \`WaitMsBeforeAsync: 500\`)运行 \`baton forward <id> --wait\`(双盲审计附加 \`--blind\` 脱敏思考自辩;单工单严禁使用 \`--async\` 拆分两步!**派发后必须挂起监听,严禁漏开监听**)。
3265
3664
  2. **多单并发派发(仅限一次性派发多单)**:\`baton forward <id1> <id2> ... --async\`,派发后必须立即作为后台任务运行 \`baton wait <id1> <id2> ... --all\` 聚合监听平账(严禁将多单提示词混杂在同一个代码块内)。
3266
3665
  3. **宿主任务与降级监听纪律(强制 · v2.42.0)**:
3267
3666
  - **严禁将普通 shell \`session_id\` 当作自动唤醒保证**:\`exec_command\` 返回的 \`session_id\` 仅为普通终端会话,宿主无反应式自主唤醒机制;仅在确认宿主具备真正的任务完成事件驱动唤醒能力(如 Antigravity \`run_command\` 的 \`WaitMsBeforeAsync\`)时,才可宣称监听已自动接管。
3268
3667
  - **非反应式宿主降级协议**:在不支持后台任务完成自主唤醒的宿主中,必须在提示词前向人类明示「降级监听:只监听、不自动续办」,说明执行方交付后人类只需发送任意消息/按回车唤起本会话;
3269
3668
  - **会话恢复自动续办纪律**:任何会话恢复交互时,必须先运行 \`baton status --current\`,识别到 \`delivered\` 状态后自动进入 \`show → 独立实测复核 → close/reject\`,严禁要求用户重述已交付事实或粘贴回执!
3270
3669
  4. **出站回复收尾(交接提示词规范)**:出站由发起方统一计算与推进 Round 轮次;回复最末块必须固定为独立代码块,方便人类一键复制给接收方 Agent(其后无任何正文):
3271
- ## 交接提示词
3670
+ ## Baton Pass Prompt
3272
3671
  \`\`\`text
3273
- 请 [<目标角色>] 接单:
3274
- [发起角色] [<发起角色>]
3672
+ 请 [<to_lane>] 接单:
3673
+ [发起角色] [<from_lane>]
3275
3674
  [任务主题] <主题>
3276
3675
  [任务轮次] Round <round>(第 <round> 轮复审)
3277
3676
  [工单编号] [<conversation_id>]
@@ -3287,7 +3686,7 @@ const STUB_BODY_EN = `### Agent Baton (Handoff) Guard Stub (Resilient & Slim ·
3287
3686
 
3288
3687
  **Core Guards & Identity (Mandatory)**
3289
3688
  - **Workspace Boundary**: Agent session is strictly pinned to active workspace. Never cross boundaries via cd to mutate external code; output a Baton Pass Prompt for cross-repo tasks.
3290
- - **Single Ticket Lifecycle & Unified Session ID (Mandatory · v2.36.0)**: Ticket physical ID is conversation ID (unified), immutable across all rounds (Round 1..N); task topic remains constant.
3689
+ - **Single Ticket Lifecycle & Affinity Lock (Mandatory · v2.44.0)**: Ticket physical ID is conversation ID (unified), immutable across all rounds (Round 1..N); agent session strictly locked to single ticket per context (anti-cross-ticket contamination); task topic remains constant.
3291
3690
  - **Anti-Cross-Session Hard Gate (Constitutional Isolation)**: Tickets strictly bind to initiator conversation; cross-session mutation/closure (\`forward\`/\`accept\`/\`reopen\`) is prohibited. Receivers take tickets with explicit IDs.
3292
3691
  - **CLI Form & Explicit Identity**: Always use \`baton <op>\` or \`handoff <op>\`. Full support for \`--as <lane>\` explicit identity override, enabling multi-ticket processing within the same session.
3293
3692
  - **Session Lane Lock & Cryptographic Signatures**: Lock identity via \`baton lane <lane>\`; precedence is \`HANDOFF_LANE\` > \`baton lane\` > \`--as <lane>\`; audit delivery requires \`audit.token\` signatures.
@@ -3296,18 +3695,19 @@ const STUB_BODY_EN = `### Agent Baton (Handoff) Guard Stub (Resilient & Slim ·
3296
3695
  **Inbound Workflow (Receive · Deliver · Reject)**
3297
3696
  1. **Check Pending**: Run \`baton status --as <my lane|target> --current\` (or global \`baton status --current\`).
3298
3697
  2. **Inspect Ticket**: Run \`baton show <id>\`, implement scoped changes, and independently run tests.
3299
- 3. **Deliver or Reject (Empirical Tests are the Sole Authority)**:
3300
- - **All Tests Pass**: Follow \`$(lab path handoffs)/RESPONSE-TEMPLATE.md\` → run \`baton receipt <id> -n "<Body>" --deliver --as <my lane> --evidence-paths "<files>"\` (audit tickets require \`--audit-nonce "<nonce>"\` or \`--auto-nonce\`; red-team probes must follow three-state standard: NO_DISPATCH / NO_COMPLETE / COMPLETE).
3698
+ 3. **Deliver or Reject (Empirical Tests are the Sole Authority · Must Update State via CLI · Must be Markdown)**:
3699
+ - **Markdown Format Invariant**: Both ticket creation and receipt submission MUST be authored in standard Markdown (.md). Never use plain text (.txt)!
3700
+ - **All Tests Pass**: Strictly follow \`$(lab path handoffs)/RESPONSE-TEMPLATE.md\` skeleton (must include verdict section & clear verdict line) → run \`baton receipt <id> -n "<Body>" --deliver --as <my lane> --evidence-paths "<files>"\` (audit tickets require \`--audit-nonce "<nonce>"\` or \`--auto-nonce\`; red-team probes must follow three-state standard: NO_DISPATCH / NO_COMPLETE / COMPLETE; **prohibited from only creating Markdown without state transition**, must advance ticket state via CLI!).
3301
3701
  - **Tests Fail / Blocked (NO-GO)**: Use unconditional egress channel, run \`baton reject <id> -n "<reason/missing condition>" --as <my lane>\` to send back for revision (draft receipts can be logged without blocker).
3302
3702
  4. **Wrap-up Check**: Run \`baton check [id]\` (supports \`--fix\` for auto-repair).
3303
- 5. **Inbound Reply Epilogue (Concise One-Line Verdict · Anti-Role-Drift)**: Receiver must strictly maintain own execution/audit role without role drift; strictly prohibited from generating reverse \`## Baton Pass Prompt\` cards or calling \`baton close\`; output only a single plain-text line at the very end of your response to the user (no markdown headers, no code blocks, strictly no multi-line outbound cards):
3304
- - Audit Rejection: \`Audit complete, verdict NO-GO (Ticket returned to <initiator role> entering Round <N>)\`
3305
- - Audit Pass: \`Audit complete, verdict GO\`
3306
- - General Delivery: \`Delivery complete, receipt ready\`
3307
- Next Round calculation and outbound dispatch cards are exclusively managed by the initiator when re-forwarding.
3703
+ 5. **Inbound Reply Epilogue (Concise One-Line Verdict · Anti-Role-Drift · Scheme A Standard)**: Receiver is physically locked by role-command whitelist; CLI hard-blocks close/forward/prompt; receiver must strictly maintain own execution/audit role without role drift; strictly prohibited from generating reverse \`## Baton Pass Prompt\` cards or calling \`baton close\`; output only a single plain-text line at the very end of your response to the user (no markdown headers, no code blocks, strictly no multi-line outbound cards):
3704
+ - Rejection (NO-GO): \`Please [<target_lane>] revise per rejection record and re-deliver [<ticket_id>]: <receipt_path> (Round <N> · NO-GO · <one-line reason>)\`
3705
+ - Pass (GO): \`Please [<initiator_lane>] review audit receipt and close ticket [<ticket_id>]: <receipt_path> (Round <N> · GO · <one-line summary>)\`
3706
+ - General Delivery: \`Please [<reviewer_lane>] review delivery receipt and verify tests [<ticket_id>]: <receipt_path> (Round <N> · DELIVERED · <one-line summary>)\`
3707
+ (Compatible with legacy concise form: \`Audit complete, verdict NO-GO/GO / Delivery complete, receipt ready\`).
3308
3708
 
3309
3709
  **Outbound Workflow (Dispatch · Listen · Mandatory Listener)**
3310
- 1. **Create & Forward (Single Ticket Atomic · 99% cases)**: \`baton new <target|lane> <type> "<Title>"\`, fill body, then run \`baton forward <id> --wait\` as a host background task (add \`--blind\` for double-blind audit; single-ticket \`--async\` split is strictly prohibited!).
3710
+ 1. **Create & Forward (Single Ticket Atomic · 99% cases)**: \`baton new <target|lane> <type> "<Title>"\`, fill body, then run \`baton forward <id> --wait\` as a host background task (add \`--blind\` for double-blind audit; single-ticket \`--async\` split is strictly prohibited; **listener must be running, never forget listener**).
3311
3711
  2. **Concurrent Batch Dispatch (Multiple tickets only)**: \`baton forward <id1> <id2> ... --async\`, then immediately run \`baton wait <id1> <id2> ... --all\` as a host background task to clear debt (never bundle multiple tickets into one prompt card).
3312
3712
  3. **Host Task & Downgrade Protocol (Mandatory · v2.42.0)**:
3313
3713
  - **Prohibit treating shell \`session_id\` as auto-wakeup guarantee**: Shell \`session_id\` from \`exec_command\` represents an interactive shell session without reactive wakeup; only claim auto-managed listener when the host confirms an event-driven task completion hook (e.g. Antigravity \`run_command\` \`WaitMsBeforeAsync\`).
@@ -3316,8 +3716,8 @@ const STUB_BODY_EN = `### Agent Baton (Handoff) Guard Stub (Resilient & Slim ·
3316
3716
  4. **Outbound Reply Closing (Baton Pass Prompt)**: Initiator calculates and advances Round count; end outbound replies with an isolated code block for one-click human copying (no text after):
3317
3717
  ## Baton Pass Prompt
3318
3718
  \`\`\`text
3319
- Please [<Target Role>] take handoff:
3320
- [Initiator] [<Initiator Role>]
3719
+ Please [<to_lane>] take handoff:
3720
+ [Initiator] [<from_lane>]
3321
3721
  [Task Topic] <Title>
3322
3722
  [Task Round] Round <round> (Review Round <round>)
3323
3723
  [Ticket ID] [<conversation_id>]
@@ -3474,6 +3874,22 @@ function cmdCheckCross(args = []) {
3474
3874
  if (fm.status === 'closed' && !/^## (验收记录|Audit Record|Acceptance Record)/im.test(raw))
3475
3875
  problems.push(`[交接] status=closed 但缺「验收记录」节(须经 handoff accept <id> -n "<结论>" 闭环): ${f}`);
3476
3876
 
3877
+ // 状态流转硬门禁:防止回执方只写回执 Markdown 文件却漏跑 baton receipt / baton deliver 推进状态
3878
+ const rPathCross = path.join(R_DIR, `${id}-resp.md`);
3879
+ if ((fm.status === 'draft' || fm.status === 'forwarded') && fs.existsSync(rPathCross)) {
3880
+ try {
3881
+ const rRaw = fs.readFileSync(rPathCross, 'utf8');
3882
+ const rBody = stripFM(rRaw);
3883
+ const rFm = readFM(rRaw) || {};
3884
+ const concl = extractConclusion(rBody);
3885
+ const hasSubstance = Boolean(concl || (rBody && rBody.length > 50) || rFm.evidence_paths);
3886
+ const isLegacy = fm.created && fm.created < '2026-11-15';
3887
+ if (!isLegacy && hasSubstance) {
3888
+ problems.push(`[状态流转违例] 检测到回执 receipts/${id}-resp.md 已存在且有实质内容,但工单状态仍停留在 ${fm.status}。回执方严禁只写 Markdown 文件不翻状态,必须调用 CLI (baton receipt ${id} --deliver 或 baton deliver ${id}) 推进工单状态!`);
3889
+ }
3890
+ } catch {}
3891
+ }
3892
+
3477
3893
  // 状态机语义不变量校验(v2.25 · P1-1 修复)
3478
3894
  if (fm.status === 'closed') {
3479
3895
  if (fm.rejected_at) {
@@ -3584,8 +4000,25 @@ function cmdCheckIntra(args = []) {
3584
4000
  if (fm.status === 'closed' && !/^## (验收记录|Audit Record|Acceptance Record)/im.test(raw))
3585
4001
  problems.push(`[交接] status=closed 但缺「验收记录」节(须经 handoff accept <id> -n "<结论>" 闭环): ${f}`);
3586
4002
 
3587
- // needs_change 一致性校验与安全修复
4003
+ // 状态流转硬门禁:防止回执方只写回执 Markdown 文件却漏跑 baton receipt / baton deliver 推进状态
4004
+ // 注意:若工单处于驳回待整改状态(rejected_at 存在且 needs_change=true),回执记录的是驳回意见而非待交付成果,豁免此项检测。
3588
4005
  const rPath = path.join(R_DIR, `${id}-resp.md`);
4006
+ const isUnderRejection = Boolean(fm.rejected_at && (fm.needs_change === true || fm.needs_change === 'true'));
4007
+ if (!isUnderRejection && (fm.status === 'draft' || fm.status === 'forwarded') && fs.existsSync(rPath)) {
4008
+ try {
4009
+ const rRaw = fs.readFileSync(rPath, 'utf8');
4010
+ const rBody = stripFM(rRaw);
4011
+ const rFm = readFM(rRaw) || {};
4012
+ const concl = extractConclusion(rBody);
4013
+ const hasSubstance = Boolean(concl || (rBody && rBody.length > 50) || rFm.evidence_paths);
4014
+ const isLegacy = fm.created && fm.created < '2026-11-15';
4015
+ if (!isLegacy && hasSubstance) {
4016
+ problems.push(`[状态流转违例] 检测到回执 receipts/${id}-resp.md 已存在且有实质内容,但工单状态仍停留在 ${fm.status}。回执方严禁只写 Markdown 文件不翻状态,必须调用 CLI (baton receipt ${id} --deliver 或 baton deliver ${id}) 推进工单状态!`);
4017
+ }
4018
+ } catch {}
4019
+ }
4020
+
4021
+ // needs_change 一致性校验与安全修复
3589
4022
  if (fs.existsSync(rPath)) {
3590
4023
  const rRaw = fs.readFileSync(rPath, 'utf8');
3591
4024
  const rFm = readFM(rRaw) || {};
@@ -3987,8 +4420,24 @@ function cmdPrompt(args) {
3987
4420
  const ws = fm.workspace || 'same';
3988
4421
  const toLane = String(fm.to_lane || '').toLowerCase();
3989
4422
  const fromLane = String(fm.from_lane || 'impl').toLowerCase();
3990
- const toRole = resolveLaneRole(toLane) || toLane || (isZh ? '执行方' : 'Executor');
3991
- const fromRole = resolveLaneRole(fromLane) || fromLane || (isZh ? '发起方' : 'Initiator');
4423
+
4424
+ // 防反向交接提示词卡片拦截(ADR-0018 · 仿 LangGraph 阻断乒乓死循环):
4425
+ // 接收/审查方(to_lane)严禁直接生成面向发起方的出站交接提示词卡片
4426
+ const asLane = flagValue(args, '--as') || flagValue(args, '--by');
4427
+ const callerLane = resolveExecutionLane(asLane, { fromLane, toLane, op: 'prompt', ticketId: id });
4428
+ const isDirectPrompt = !args.includes('--internal-forward');
4429
+ const isExplicitToLane = Boolean(asLane && asLane.toLowerCase().trim() === toLane);
4430
+ const currentSess = getSessionId();
4431
+ const isInitiatorSession = Boolean(currentSess && fm?.conversation_id && currentSess === fm.conversation_id);
4432
+
4433
+ if (isDirectPrompt && (isExplicitToLane || (!isInitiatorSession && callerLane && callerLane === toLane))) {
4434
+ console.error(isZh
4435
+ ? `❌ [反向提示词拦截 (REVERSE_PROMPT_BLOCKED)] 当前会话身份为接收/审查方 (lane=${callerLane || asLane})。\n 👉 接收方职责为交付回执或驳回,交接提示词卡片专属发起方派单时使用,接收方严禁反向生成出站交接卡!`
4436
+ : `❌ [Reverse Prompt Blocked (REVERSE_PROMPT_BLOCKED)] Current role is the ticket's receiver (lane=${callerLane || asLane}). Outbound prompt cards are reserved for the initiator!`);
4437
+ process.exit(1);
4438
+ }
4439
+ const toRole = toLane || (isZh ? '执行方' : 'Executor');
4440
+ const fromRole = fromLane || (isZh ? '发起方' : 'Initiator');
3992
4441
  const cleanTitle = sanitizeTaskTopic(title);
3993
4442
  const round = Number(fm.round || 1);
3994
4443
  const roundLineZh = round > 1 ? `[任务轮次] Round ${round}(第 ${round} 轮复审)\n` : '';
@@ -3997,8 +4446,8 @@ function cmdPrompt(args) {
3997
4446
  const profileLineEn = fm.tool_profile === 'readonly' ? `[Tool Profile] tool_profile=readonly (Read-only: Prohibited from modifying production code)\n` : '';
3998
4447
  const convId = fm.conversation_id || getSessionId();
3999
4448
  const promptId = convId || id;
4000
- const initiatorLineZh = `[发起角色] [${fromRole}](${fromLane})\n`;
4001
- const initiatorLineEn = `[Initiator] [${fromRole}] (${fromLane})\n`;
4449
+ const initiatorLineZh = `[发起角色] [${fromRole}]\n`;
4450
+ const initiatorLineEn = `[Initiator] [${fromRole}]\n`;
4002
4451
  const isAuditLane = (toLane === 'audit');
4003
4452
  const roleAnchorZh = isAuditLane ? `[角色锚定] 本会话即为独立审计沙箱,请直接作为审计执行员进行独立测试与核验(切勿触发派单逻辑)\n` : '';
4004
4453
  const roleAnchorEn = isAuditLane ? `[Role Anchor] This session is an isolated audit sandbox. Act directly as the audit verifier to execute and verify tests (do not trigger dispatch/forwarding logic).\n` : '';
@@ -4027,7 +4476,7 @@ function cmdPrompt(args) {
4027
4476
  if (isZh) {
4028
4477
  console.log(`📋 仓内交接 (${id}) · workspace=${ws}:`);
4029
4478
  console.log(` 主题: ${cleanTitle}`);
4030
- console.log(`\n## 交接提示词\n`);
4479
+ console.log(`\n## Baton Pass Prompt\n`);
4031
4480
  console.log(`> 直接复制下方提示词,发送给接收方 Agent 接单:\n`);
4032
4481
  console.log(`\`\`\`text`);
4033
4482
  console.log(chosenPromptText);
@@ -4109,7 +4558,7 @@ function cmdPrompt(args) {
4109
4558
  process.exit(3);
4110
4559
  }
4111
4560
 
4112
- const targetLabel = pTarget ? (TARGET_LABELS[pTarget] || pTarget) : (isZh ? '依赖方' : 'dependency');
4561
+ const targetLabel = pTarget || (isZh ? 'dependency' : 'dependency');
4113
4562
  const cleanTitle = sanitizeTaskTopic(title);
4114
4563
  const round = Number(readFM(content)?.round || 1);
4115
4564
  const roundLineZh = round > 1 ? `[任务轮次] Round ${round}(第 ${round} 轮复审)\n` : '';
@@ -4129,7 +4578,7 @@ function cmdPrompt(args) {
4129
4578
  if (isZh) {
4130
4579
  console.log(`📋 跨仓交接 (${id}) · target=${pTarget || 'unknown'}:`);
4131
4580
  console.log(` 主题: ${cleanTitle}`);
4132
- console.log(`\n## 交接提示词\n`);
4581
+ console.log(`\n## Baton Pass Prompt\n`);
4133
4582
  console.log(`> 直接复制下方提示词,发送给接收方 Agent 接单:\n`);
4134
4583
  console.log(`\`\`\`text`);
4135
4584
  console.log(chosenPromptText);