ai_co_discuss 0.6.11 → 0.6.13

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.
@@ -47,7 +47,7 @@ export function applicable_text(state) {
47
47
  }
48
48
 
49
49
  // A room intent nobody acted on lapses after a day; a finished suggestion after a week.
50
- const lapses_at = item => item.application_pending ? Infinity : Date.parse(item.created_at) + (item.stage === 'intent' && (item.status || 'pending') === 'pending' ? DAY : WEEK);
50
+ const lapses_at = item => item.application_pending || item.merge_id ? Infinity : Date.parse(item.created_at) + (item.stage === 'intent' && (item.status || 'pending') === 'pending' ? DAY : WEEK);
51
51
 
52
52
  /** Suggestions still waiting, a stale refinement shown as waiting again. */
53
53
  export function active_suggestions(state) {
@@ -65,13 +65,19 @@ function settle(state, item, status, entry_id = null) {
65
65
  message_id: source.message_id, execution_id: item.execution_id ?? null, entry_id, decided_at: now(),
66
66
  ...(item.summary_message_id ? { summary_message_id: item.summary_message_id, evidence_count: item.evidence_count } : {}),
67
67
  ...(item.room_id ? { room_id: item.room_id } : {}),
68
- ...(item.workflow_action ? { workflow: item.workflow, workflow_action: item.workflow_action } : {}) }].slice(-HISTORY);
68
+ ...(item.merge_id ? { merge_id: item.merge_id } : {}),
69
+ ...(item.workflow_action ? { workflow: item.workflow, workflow_action: item.workflow_action } : {}),
70
+ ...(is_candidate(item) ? { source, sources: source_rows(item), before: item.previous || null,
71
+ after: item.remove ? null : item.text, ...(status === 'expired' ? { candidate: item } : {}) } : {}) }].slice(-HISTORY);
69
72
  state.suggestions = state.suggestions.filter(row => row.id !== item.id);
70
73
  }
71
74
 
72
75
  /** Move lapsed suggestions into the history as expired. */
73
76
  function prune(state) {
74
77
  expire_entries(state);
78
+ migrate_rule_admissions(state);
79
+ const batch = (state.admissions || []).find(job => job.operation === 'merge' && job.status === 'checking');
80
+ if (batch && timed_out(batch)) finish_batch_failure(state, batch, 'failed', { failure: 'timeout' });
75
81
  for (const item of state.suggestions.filter(row => lapses_at(row) <= Date.now())) settle(state, item, 'expired');
76
82
  state.suggestions = active_suggestions(state);
77
83
  }
@@ -199,7 +205,7 @@ function propose(state, input, source, current) {
199
205
  ...(kind === 'workflow' ? { workflow_action: input.workflow_action } : {}),
200
206
  ...(Object.hasOwn(input, 'expires_at') ? { expires_at: input.expires_at } : {}) } : {};
201
207
  const suggestion = { id: previous?.id || randomUUID(), kind, stage, status: 'pending', origin: previous?.origin || (stage === 'intent' ? 'intent' : 'review'), target: id || previous?.target || null, previous: current?.text || previous?.previous || '',
202
- previous_version: current?.updated_at ?? previous?.previous_version, remove: input.remove === true || (input.update != null && Boolean(previous?.remove)), scope: 'global', text: checked_text(input.text),
208
+ selected: previous?.selected ?? false, previous_version: current?.updated_at ?? previous?.previous_version, remove: input.remove === true || (input.update != null && Boolean(previous?.remove)), scope: 'global', text: checked_text(input.text),
203
209
  complete: stage === 'intent' && input.complete === true, workflow: kind !== 'workflow' ? null : typeof input.workflow === 'string' ? input.workflow : previous?.workflow ?? null,
204
210
  source: previous?.source || source, sources: previous ? merged_sources(previous, sources) : sources,
205
211
  execution_id: previous?.execution_id ?? source.execution_id ?? null, review_id: previous?.review_id ?? source.review_id ?? null,
@@ -269,7 +275,7 @@ export function change_experience(state, input, source = null) {
269
275
  }
270
276
 
271
277
  const ADMISSION_TIMEOUT = 10 * 60000;
272
- const CLOSED = new Set(['effective', 'unreviewed', 'dismissed']);
278
+ const CLOSED = new Set(['effective', 'unreviewed', 'dismissed', 'undone']);
273
279
  const SECTIONS = ['requirements', 'delegation', 'progress'];
274
280
  const source_rows = row => row?.sources || (row?.source ? [row.source] : []);
275
281
  const same_source = (left, right) => left.room_id === right.room_id && left.message_id === right.message_id;
@@ -286,12 +292,288 @@ export function admission_view(state, moss_configured = true) {
286
292
  organized: state.organized ? { ...state.organized, stale: state.organized.entries_revision !== revision } : null,
287
293
  admissions: (state.admissions || []).filter(job => CLOSED.has(job.status) || !job.suggestion_id ||
288
294
  active_suggestions(state).some(row => row.id === job.suggestion_id)).map(job => ({
289
- ...job,
295
+ ...Object.fromEntries(Object.entries(job).filter(([key]) => !['rollback', 'staged_entries'].includes(key))),
290
296
  ...(job.status === 'checking' && timed_out(job) ? { status: 'failed', failure: 'timeout' } : {}),
291
297
  can_direct_enable: can_direct_enable(job, revision, moss_configured),
298
+ ...(job.operation === 'merge' ? { can_undo: job.status === 'effective' && !!job.rollback && job.applied_revision === revision } : {}),
292
299
  })) };
293
300
  }
294
301
 
302
+ const is_candidate = row => row && (row.kind || 'rule') === 'rule' && row.stage !== 'intent';
303
+ const legacy_open_rule = job => !CLOSED.has(job.status) && !['merge', 'room_strategy', 'workflow'].includes(job.operation);
304
+ export const needs_experience_maintenance = state => (state.admissions || []).some(job =>
305
+ legacy_open_rule(job) || job.operation === 'merge' && job.status === 'checking' && timed_out(job));
306
+
307
+ function migrate_rule_admissions(state) {
308
+ if (!state.admissions?.some(legacy_open_rule)) return;
309
+ for (const job of state.admissions.filter(legacy_open_rule)) {
310
+ const row = state.suggestions.find(item => item.id === job.suggestion_id);
311
+ if (row) { delete row.admission_id; continue; }
312
+ const target = state.entries.find(item => item.id === job.target);
313
+ const source = { kind: 'user' };
314
+ state.suggestions.push({ id: job.id, kind: 'rule', stage: 'product', status: 'pending',
315
+ operation: job.operation, target: job.target, previous: target?.text || '', revoke_source: job.revoke_source,
316
+ text: job.text, remove: job.operation === 'remove', source, sources: [source], selected: true, created_at: job.created_at });
317
+ }
318
+ state.admissions = state.admissions.filter(job => !legacy_open_rule(job));
319
+ }
320
+
321
+ /** Project the proposer wording separately from the current target and the saved original. */
322
+ export function experience_suggestions(state) {
323
+ return active_suggestions(state).map(row => {
324
+ if (!is_candidate(row)) return row;
325
+ const target = state.entries.find(item => item.id === row.target);
326
+ return { ...row, selected: row.selected === true, operation: candidate_operation(row),
327
+ before: target?.text ?? (row.previous || null), after: row.remove ? null : row.text,
328
+ target_missing: Boolean(row.target && !target), candidate_expires_at: new Date(Date.parse(row.created_at) + WEEK).toISOString() };
329
+ });
330
+ }
331
+
332
+ function candidate_operation(row) {
333
+ return row.operation || (row.remove ? 'remove' : row.target ? 'edit' : 'add');
334
+ }
335
+
336
+ function candidate_job(row) {
337
+ return { id: row.id, operation: candidate_operation(row), target: row.target,
338
+ entry_id: row.target || row.id, origin: row.source?.kind === 'user' ? 'owner' : 'ai',
339
+ sources: source_rows(row), revoke_source: row.revoke_source, summary_message_id: row.summary_message_id,
340
+ ...(Object.hasOwn(row, 'expires_at') ? { expires_at: row.expires_at } : {}) };
341
+ }
342
+
343
+ function selected_candidates(state, input, pending = false) {
344
+ const ids = input.ids ?? (input.id ? [input.id] : []);
345
+ if (!Array.isArray(ids) || !ids.length || new Set(ids).size !== ids.length || ids.length > PENDING)
346
+ throw new Error(t('请选择有效的经验候选。'));
347
+ const rows = ids.map(id => state.suggestions.find(row => row.id === id));
348
+ if (rows.some(row => !is_candidate(row) || row.merge_id || (pending && row.status !== 'pending')))
349
+ throw new Error(t('请选择有效的经验候选。'));
350
+ return rows;
351
+ }
352
+
353
+ function owner_candidate(state, input) {
354
+ const { id, text, remove } = input;
355
+ const target = state.entries.find(row => row.id === id);
356
+ if ((id && !target) || (!id && remove)) throw new Error(t('经验编号不存在。'));
357
+ if (state.suggestions.filter(row => row.stage !== 'intent').length >= PENDING)
358
+ throw new Error(t('最多保留 10 条待确认建议。'));
359
+ const source = { kind: 'user' };
360
+ state.suggestions.push({ id: randomUUID(), kind: 'rule', stage: 'product', status: 'pending',
361
+ source, sources: [source], selected: true, created_at: now(), target: target?.id ?? null,
362
+ remove: remove === true, text: checked_text(text ?? (remove ? target.text : null)), previous: target?.text || '' });
363
+ }
364
+
365
+ function direct_rule_change(state, input) {
366
+ const target = input.action === 'add' ? null : state.entries.find(row => row.id === input.id);
367
+ if (input.action !== 'add' && !target) throw new Error(t('经验编号不存在。'));
368
+ const revoke_source = input.action === 'revoke-source' ? { room_id: input.room_id, message_id: Number(input.message_id) } : null;
369
+ if (revoke_source && !source_rows(target).some(source => same_source(source, revoke_source)))
370
+ throw new Error(t('未找到要撤销的经验出处。'));
371
+ const text = input.action === 'add' || input.action === 'edit' ? checked_text(input.text) : target.text;
372
+ const job = { entry_id: target?.id || randomUUID(), target: target?.id, origin: 'owner', operation: input.action,
373
+ sources: [], revoke_source };
374
+ state.entries = candidate_entries(state, job, { text });
375
+ const current = state.entries.find(row => row.id === job.entry_id);
376
+ state.history = [...(state.history || []), { id: randomUUID(), kind: 'rule', status: 'direct_edit', operation: input.action,
377
+ actor: 'owner', entry_id: job.entry_id, before: target?.text ?? null, after: current?.text ?? null,
378
+ text: text, decided_at: now() }].slice(-HISTORY);
379
+ return current;
380
+ }
381
+
382
+ function checked_revision(state, revision) {
383
+ if (revision && revision === experience_entries_revision(state)) return;
384
+ throw Object.assign(new Error(t('经验账本已变更,请重新读取。')), {
385
+ code: revision ? 'stale_experience_ledger' : 'experience_ledger_required', http_status: revision ? 409 : 400,
386
+ });
387
+ }
388
+
389
+ function finish_batch_failure(state, job, status, detail) {
390
+ for (const row of state.suggestions.filter(item => item.merge_id === job.id)) {
391
+ delete row.merge_id;
392
+ row.selected = false;
393
+ }
394
+ delete job.staged_entries;
395
+ return Object.assign(job, { status, ...detail, finished_at: now() });
396
+ }
397
+
398
+ function apply_batch(state, job, entries, sections) {
399
+ if (entries.filter(row => row.enabled).length > Math.max(LIMIT, state.entries.filter(row => row.enabled).length))
400
+ throw new Error(t('最多启用 20 条经验。'));
401
+ const organized_text = sections ? sections_text(entries, sections) : null;
402
+ const before = sections ? applicable_text(state) : null;
403
+ job.rollback = { entries: structuredClone(state.entries), organized: state.organized,
404
+ candidates: state.suggestions.filter(row => row.merge_id === job.id).map(({ merge_id, ...row }) => row) };
405
+ state.entries = entries;
406
+ job.applied_revision = experience_entries_revision(state);
407
+ if (sections) state.organized = { text: organized_text, sections, entries_revision: job.applied_revision,
408
+ version: (state.organized?.version || 0) + 1, updated_at: now() };
409
+ for (const row of job.rollback.candidates) settle(state, { ...row, merge_id: job.id }, job.dismiss_ids?.includes(row.id) ? 'dismissed' : 'accepted');
410
+ delete job.staged_entries;
411
+ return Object.assign(job, { status: 'effective', before, after: organized_text, applied_at: now() });
412
+ }
413
+
414
+ const CONFLICT_SENTENCE_LIMIT = 160;
415
+
416
+ function conflict_sentence(value) {
417
+ const text = checked_text(value);
418
+ if ([...text].length > CONFLICT_SENTENCE_LIMIT || /[\r\n]|[。!?!?]\s*\S|\.\s+\S/u.test(text))
419
+ throw new Error(t('冲突原因和场景须各为一句,不超过 {limit} 字。', { limit: CONFLICT_SENTENCE_LIMIT }));
420
+ return text;
421
+ }
422
+
423
+ function batch_conflicts(state, job, conflicts) {
424
+ const rows = new Map(job.staged_entries.map(row => [row.id, row.text]));
425
+ const candidates = new Map(state.suggestions.filter(row => row.merge_id === job.id && !job.dismiss_ids?.includes(row.id))
426
+ .map(row => [row.target || row.id, row]));
427
+ if (!Array.isArray(conflicts) || !conflicts.length || conflicts.length > PENDING)
428
+ throw new Error(t('经验检查结果无效。'));
429
+ return conflicts.map(({ left_id, right_id, scenario }) => {
430
+ if (left_id === right_id || !rows.has(left_id) || !rows.has(right_id)) throw new Error(t('经验检查结果无效。'));
431
+ const left = candidates.get(left_id), right = candidates.get(right_id);
432
+ return { left_id, right_id, left_text: rows.get(left_id), right_text: rows.get(right_id),
433
+ left_candidate_id: left?.id ?? null, right_candidate_id: right?.id ?? null,
434
+ left_source: left?.source ?? null, right_source: right?.source ?? null, scenario: conflict_sentence(scenario) };
435
+ });
436
+ }
437
+
438
+ function merged_batch_entries(job, rules) {
439
+ const untouched = job.staged_entries.filter(row => !row.enabled);
440
+ const pool = new Map(job.staged_entries.filter(row => row.enabled).map(row => [row.id, row]));
441
+ if (!Array.isArray(rules)) throw new Error(t('经验检查结果无效。'));
442
+ const merged = rules.map(rule => {
443
+ const ids = [rule.id, ...(rule.merge_ids || [])];
444
+ const rows = ids.map(id => pool.get(id));
445
+ if (new Set(ids).size !== ids.length || rows.some(row => !row) || new Set(rows.map(row => row.expires_at ?? null)).size !== 1)
446
+ throw new Error(t('经验检查结果无效。'));
447
+ for (const id of ids) pool.delete(id);
448
+ const [main, ...others] = rows;
449
+ const text = checked_text(rule.text);
450
+ const sources = next_sources(main, { sources: others.flatMap(source_rows) });
451
+ return { ...main, text, sources, ...(main.evidence_count === undefined ? {} : { evidence_count: sources.length }),
452
+ ...(text === main.text && !others.length ? {} : { updated_at: now() }) };
453
+ });
454
+ if (pool.size) throw new Error(t('经验检查结果无效。'));
455
+ return [...untouched, ...merged];
456
+ }
457
+
458
+ function finish_batch(state, job, input) {
459
+ if (job.status !== 'checking' || job.attempt !== input.attempt || job.entries_revision !== input.entries_revision || timed_out(job))
460
+ throw new Error(t('这次经验检查已失效,请重新读取。'));
461
+ if (job.entries_revision !== experience_entries_revision(state) || has_expired_entries({ entries: job.staged_entries }))
462
+ return finish_batch_failure(state, job, 'failed', { failure: 'stale' });
463
+ if (input.outcome === 'failed') return finish_batch_failure(state, job, 'failed', { failure: 'moss' });
464
+ if (input.outcome === 'conflict') {
465
+ const conflicts = batch_conflicts(state, job, input.conflicts);
466
+ const reason = conflict_sentence(input.reason ?? conflicts[0].scenario);
467
+ return finish_batch_failure(state, job, 'conflict', { conflicts, reason });
468
+ }
469
+ if (input.outcome !== 'pass' || !input.sections) throw new Error(t('经验检查结果无效。'));
470
+ return apply_batch(state, job, merged_batch_entries(job, input.rules), input.sections);
471
+ }
472
+
473
+ function conflict_choices(job, choices) {
474
+ const conflicts = job.conflicts;
475
+ if (!Array.isArray(choices) || choices.length !== conflicts.length) throw new Error(t('请为每处冲突选择保留哪一条。'));
476
+ const keep = new Set(), drop = new Set(), dismiss = new Set(job.dismiss_ids || []), remove = new Set(job.remove_ids || []);
477
+ for (const conflict of conflicts) {
478
+ const choice = choices.find(row => row?.left_id === conflict.left_id && row?.right_id === conflict.right_id);
479
+ if (!choice || ![conflict.left_id, conflict.right_id].includes(choice.keep_id))
480
+ throw new Error(t('请为每处冲突选择保留哪一条。'));
481
+ const left_wins = choice.keep_id === conflict.left_id;
482
+ const loser = left_wins ? conflict.right_id : conflict.left_id;
483
+ const candidate = left_wins ? conflict.right_candidate_id : conflict.left_candidate_id;
484
+ keep.add(choice.keep_id);
485
+ drop.add(loser);
486
+ if (candidate) dismiss.add(candidate);
487
+ else remove.add(loser);
488
+ }
489
+ if ([...keep].some(id => drop.has(id))) throw new Error(t('同一条经验不能同时保留和移除。'));
490
+ return { dismiss_ids: [...dismiss], remove_ids: [...remove] };
491
+ }
492
+
493
+ function conflict_edits(state, job, edits) {
494
+ const ids = new Set(job.conflicts.flatMap(row => [row.left_candidate_id, row.right_candidate_id]).filter(Boolean));
495
+ if (!Array.isArray(edits) || !edits.length || edits.length > ids.size || new Set(edits.map(row => row?.id)).size !== edits.length)
496
+ throw new Error(t('只能修改这一批中出现冲突的候选正文。'));
497
+ const additions = edits.map(row => {
498
+ const candidate = state.suggestions.find(candidate => candidate.id === row?.id);
499
+ if (!ids.has(row?.id) || !candidate || candidate.remove) throw new Error(t('只能修改这一批中出现冲突的候选正文。'));
500
+ return [row.id, checked_text(row.text)];
501
+ });
502
+ return Object.assign({}, job.candidate_edits, Object.fromEntries(additions));
503
+ }
504
+
505
+ function retry_batch(state, input, moss_configured, authorization = null) {
506
+ const previous = state.admissions?.find(row => row.id === input.id && row.operation === 'merge');
507
+ if (authorization && previous?.status !== 'conflict')
508
+ throw Object.assign(new Error(t('这批经验已不在冲突状态。')), { http_status: 409, code: 'experience_conflict_closed' });
509
+ if (!previous || !['conflict', 'failed'].includes(previous.status)) throw new Error(t('当前状态不能执行此经验操作。'));
510
+ checked_revision(state, input.entries_revision);
511
+ if (previous.status === 'conflict') checked_revision(state, previous.entries_revision);
512
+ if (authorization && (input.choices === undefined) === (input.edits === undefined))
513
+ throw new Error(t('请提交冲突取舍或候选改文,二选一。'));
514
+ const matching = previous.entries_revision === input.entries_revision;
515
+ const resolution = matching ? { dismiss_ids: previous.dismiss_ids, remove_ids: previous.remove_ids,
516
+ candidate_edits: previous.candidate_edits, authorization: previous.authorization } : {};
517
+ if (previous.status === 'conflict') {
518
+ if (authorization && input.edits !== undefined) resolution.candidate_edits = conflict_edits(state, previous, input.edits);
519
+ else Object.assign(resolution, conflict_choices(previous, input.choices));
520
+ }
521
+ if (authorization) Object.assign(resolution, { authorization, retry_of: previous.id });
522
+ const result = submit_batch(state, { ids: previous.candidate_ids, entries_revision: input.entries_revision }, moss_configured, resolution, previous);
523
+ previous.status = 'dismissed';
524
+ return result;
525
+ }
526
+
527
+ function restore_candidate(state, id) {
528
+ const row = state.history?.find(item => item.id === id && item.status === 'expired' && is_candidate(item.candidate));
529
+ if (!row) throw new Error(t('建议已处理或过期。'));
530
+ if (state.suggestions.filter(item => item.stage !== 'intent').length >= PENDING)
531
+ throw new Error(t('最多保留 10 条待确认建议。'));
532
+ state.history = state.history.filter(item => item.id !== id);
533
+ state.suggestions.push({ ...row.candidate, selected: false, status: 'pending', created_at: now() });
534
+ }
535
+
536
+ function submit_batch(state, input, moss_configured, resolution = {}, previous = null) {
537
+ checked_revision(state, input.entries_revision);
538
+ if ((state.admissions || []).some(job => job !== previous && job.operation === 'merge' && ['checking', 'conflict'].includes(job.status)))
539
+ throw Object.assign(new Error(t('还有一批经验正在合并。')), { http_status: 409, code: 'experience_merge_busy' });
540
+ const candidates = selected_candidates(state, input, true);
541
+ const applying = candidates.filter(row => !resolution.dismiss_ids?.includes(row.id));
542
+ const targets = applying.filter(row => row.target).map(row => row.target);
543
+ if (new Set(targets).size !== targets.length) throw new Error(t('一批中不能同时修改同一条经验。'));
544
+ let entries = state.entries.filter(row => !resolution.remove_ids?.includes(row.id));
545
+ for (const row of applying) {
546
+ if (row.expires_at && expired_entry(row) && !row.remove) throw new Error(t('短期经验已到期。'));
547
+ entries = candidate_entries({ entries }, candidate_job(row), { text: resolution.candidate_edits?.[row.id] ?? row.text }, true, true);
548
+ }
549
+ const job = { id: randomUUID(), operation: 'merge', candidate_ids: candidates.map(row => row.id),
550
+ created_at: now(), staged_entries: entries, ...resolution };
551
+ for (const row of candidates) row.merge_id = job.id;
552
+ const jobs = state.admissions || [];
553
+ state.admissions = [...jobs.filter(row => row.operation !== 'merge'), ...jobs.filter(row => row.operation === 'merge').slice(-(HISTORY - 1)), job];
554
+ if (!moss_configured) return apply_batch(state, job, entries, null);
555
+ start_check(state, job);
556
+ job.deadline = new Date(Date.now() + ADMISSION_TIMEOUT).toISOString();
557
+ return job;
558
+ }
559
+
560
+ function undo_batch(state, id) {
561
+ const job = (state.admissions || []).find(row => row.id === id && row.operation === 'merge' && row.status === 'effective');
562
+ if (!job?.rollback) throw new Error(t('找不到可撤销的经验合并。'));
563
+ checked_revision(state, job.applied_revision);
564
+ const { entries, organized, candidates } = job.rollback;
565
+ state.entries = entries;
566
+ state.organized = organized;
567
+ state.suggestions.push(...candidates.map(row => ({ ...row, selected: true })));
568
+ state.history = [...(state.history || []).filter(row => !job.candidate_ids.includes(row.id)), {
569
+ id: randomUUID(), kind: 'rule', status: 'merge_undone', actor: 'owner', merge_id: id, decided_at: now(),
570
+ text: t('房主撤销了这一批经验合并。'),
571
+ }].slice(-HISTORY);
572
+ expire_entries(state);
573
+ delete job.rollback;
574
+ return Object.assign(job, { status: 'undone', undone_at: now() });
575
+ }
576
+
295
577
  function start_check(state, job) {
296
578
  const revision = experience_entries_revision(state);
297
579
  const review_again = Boolean(job.entries_revision && job.entries_revision !== revision) || Boolean(job.review_again);
@@ -300,31 +582,6 @@ function start_check(state, job) {
300
582
  return job;
301
583
  }
302
584
 
303
- function enqueue_admission(state, input, suggestion = null) {
304
- const operation = input.action;
305
- const target = suggestion ? suggestion.target : operation === 'add' ? null : input.id;
306
- const row = state.entries.find(item => item.id === target);
307
- if (!['add', 'room_strategy', 'workflow'].includes(operation) && !row) throw new Error(t('经验编号不存在。'));
308
- const revoke_source = operation === 'revoke-source' ? { room_id: input.room_id, message_id: Number(input.message_id) } : null;
309
- if (revoke_source && (!revoke_source.room_id || !Number.isSafeInteger(revoke_source.message_id) ||
310
- !source_rows(row).some(source => same_source(source, revoke_source)))) throw new Error(t('未找到要撤销的经验出处。'));
311
- const job = { id: suggestion?.id || randomUUID(), entry_id: target || randomUUID(), target, operation,
312
- origin: suggestion ? 'ai' : 'owner', suggestion_id: suggestion?.id ?? null,
313
- text: checked_text(input.text ?? suggestion?.text ?? row?.text),
314
- sources: suggestion ? source_rows(suggestion) : [], revoke_source, created_at: now(),
315
- ...(suggestion?.summary_message_id ? { summary_message_id: suggestion.summary_message_id,
316
- evidence_count: suggestion.evidence_count, room_id: suggestion.source.room_id } : {}),
317
- ...(suggestion?.workflow_action ? { workflow: suggestion.workflow, workflow_action: suggestion.workflow_action } : {}),
318
- ...(suggestion && Object.hasOwn(suggestion, 'expires_at') ? { expires_at: suggestion.expires_at } : {}) };
319
- const rest = (state.admissions || []).filter(row => row.id !== job.id);
320
- const waiting = rest.filter(row => !row.suggestion_id && !CLOSED.has(row.status)).length;
321
- const suggestions = state.suggestions.filter(row => row.stage !== 'intent' && row.id !== suggestion?.id).length;
322
- if (waiting + suggestions >= PENDING) throw new Error(t('最多保留 10 条待确认建议。'));
323
- state.admissions = [...rest.filter(row => !CLOSED.has(row.status)), ...rest.filter(row => CLOSED.has(row.status)).slice(-HISTORY), job];
324
- if (suggestion) Object.assign(suggestion, { admission_id: job.id, stage: 'product', complete: false, status: 'pending' });
325
- return start_check(state, job);
326
- }
327
-
328
585
  function sections_text(entries, sections) {
329
586
  if (!sections || Object.keys(sections).length !== SECTIONS.length || SECTIONS.some(key => !Array.isArray(sections[key])))
330
587
  throw new Error(t('整理稿须包含三个规定章节。'));
@@ -347,7 +604,7 @@ function next_sources(row, job) {
347
604
 
348
605
  const separate_product = job => ['room_strategy', 'workflow'].includes(job.operation);
349
606
 
350
- function candidate_entries(state, job, { text, merge_into = null }, reviewed = true) {
607
+ function candidate_entries(state, job, { text, merge_into = null }, reviewed = true, allow_overflow = false) {
351
608
  if (separate_product(job)) {
352
609
  if (merge_into || job.resolution?.choice === 'replace') throw new Error(t('此建议不能合并或替换全局经验。'));
353
610
  return state.entries;
@@ -371,7 +628,7 @@ function candidate_entries(state, job, { text, merge_into = null }, reviewed = t
371
628
  user_modified: job.origin === 'owner' || Boolean(row?.user_modified) };
372
629
  if (row) next[next.findIndex(item => item.id === id)] = replacement;
373
630
  else next.push(replacement);
374
- if (next.filter(item => item.enabled).length > Math.max(LIMIT, state.entries.filter(item => item.enabled).length))
631
+ if (!allow_overflow && next.filter(item => item.enabled).length > Math.max(LIMIT, state.entries.filter(item => item.enabled).length))
375
632
  throw new Error(t('最多启用 20 条经验。'));
376
633
  return next;
377
634
  }
@@ -471,8 +728,15 @@ function manage_admission(state, job, input, internal, moss_configured) {
471
728
  if (suggestion) settle(state, suggestion, 'accepted');
472
729
  return Object.assign(job, { status: 'effective', applied_at: now(), application_pending: false });
473
730
  }
731
+ if (job.application_pending && action === 'confirm' && !job.attempt) return job;
474
732
  if (job.application_pending && action !== 'confirm') throw new Error(t('当前状态不能执行此经验操作。'));
475
- if (action === 'admission-result' && internal) return finish_check(state, job, input);
733
+ if (job.operation === 'merge') {
734
+ if (action === 'admission-result' && internal) return finish_batch(state, job, input);
735
+ if (action === 'admission-refresh' && internal && job.status === 'checking' && job.attempt === input.attempt &&
736
+ job.entries_revision !== experience_entries_revision(state))
737
+ return finish_batch_failure(state, job, 'failed', { failure: 'stale' });
738
+ if (action !== 'admission-delivery' || !internal) throw new Error(t('当前状态不能执行此经验操作。'));
739
+ } else if (action === 'admission-result' && internal) return finish_check(state, job, input);
476
740
  if (action === 'admission-refresh' && internal) {
477
741
  if (job.status === 'checking' && job.attempt === input.attempt && job.entries_revision !== experience_entries_revision(state))
478
742
  return start_check(state, job);
@@ -480,7 +744,9 @@ function manage_admission(state, job, input, internal, moss_configured) {
480
744
  }
481
745
  if (action === 'admission-delivery' && internal) {
482
746
  if (job.status !== 'checking' || job.attempt !== input.attempt) return job;
483
- if (input.failure) return Object.assign(job, { status: 'failed', failure: input.failure });
747
+ if (input.failure) return job.operation === 'merge'
748
+ ? finish_batch_failure(state, job, 'failed', { failure: input.failure })
749
+ : Object.assign(job, { status: 'failed', failure: input.failure });
484
750
  if (!job.deadline) job.deadline = new Date(Date.now() + ADMISSION_TIMEOUT).toISOString();
485
751
  if (!input.begin && !job.submitted_at) job.submitted_at = now();
486
752
  return job;
@@ -500,7 +766,25 @@ export function change_managed_experience(state, input, source, internal = false
500
766
  prune(state);
501
767
  if (state.admissions) state.admissions = state.admissions.filter(row => CLOSED.has(row.status) ||
502
768
  !row.suggestion_id || state.suggestions.some(item => item.id === row.suggestion_id));
503
- if (action === 'expiry' && !source) return update_entry_expiry(state, id, input.expires_at);
769
+ if (!source && action === 'expiry') return update_entry_expiry(state, id, input.expires_at);
770
+ if (!source && action === 'suggest') return owner_candidate(state, input);
771
+ if (!source && action === 'merge') return submit_batch(state, input, moss_configured);
772
+ if (!source && action === 'undo-merge') return undo_batch(state, id);
773
+ if (!source && action === 'retry-merge') return retry_batch(state, input, moss_configured);
774
+ if (internal && action === 'conflict-retry' && input.authorization)
775
+ return retry_batch(state, input, moss_configured, input.authorization);
776
+ if (!source && action === 'restore-candidate') return restore_candidate(state, id);
777
+ if (!source && action === 'release-merge') {
778
+ const job = state.admissions?.find(row => row.id === id && row.operation === 'merge');
779
+ if (!job || !['conflict', 'failed'].includes(job.status)) throw new Error(t('当前状态不能执行此经验操作。'));
780
+ job.status = 'dismissed';
781
+ return job;
782
+ }
783
+ if (!source && action === 'select') {
784
+ if (typeof input.selected !== 'boolean') throw new Error(t('请选择有效的经验候选。'));
785
+ for (const row of selected_candidates(state, input)) row.selected = input.selected;
786
+ return;
787
+ }
504
788
  if (action === 'room-summary' && source?.kind === 'host' && source.summary_message_id) {
505
789
  const previous = (state.reviews || []).find(row => row.source.room_id === source.room_id &&
506
790
  row.source.summary_message_id === source.summary_message_id);
@@ -518,13 +802,22 @@ export function change_managed_experience(state, input, source, internal = false
518
802
  const suggestion = state.suggestions.find(item => item.id === id);
519
803
  if (job && ['admission-result', 'admission-delivery', 'admission-refresh', 'strategy-applied', 'confirm', 'resolve', 'direct-enable', 'retry', 'reject', 'dismiss', 'accept'].includes(action))
520
804
  return manage_admission(state, job, { ...input, action: action === 'dismiss' ? 'reject' : action === 'accept' ? 'confirm' : action }, internal, moss_configured);
521
- if (job && ['refine', 'unrefine'].includes(action)) throw new Error(t('当前状态不能执行此经验操作。'));
522
- if (['add', 'edit', 'enable', 'disable', 'remove', 'revoke-source', 'distill'].includes(action))
523
- return enqueue_admission(state, input);
524
- if ((action === 'go' || action === 'accept') && suggestion && suggestion.kind !== 'workflow') {
525
- if ((action === 'go' && suggestion.stage !== 'intent') || suggestion.status === 'refining')
526
- throw new Error(t('找不到要完成的意图。'));
527
- return queue_rule(state, suggestion, suggestion.stage === 'intent' ? undefined : input.text);
805
+ if ((job && ['refine', 'unrefine'].includes(action)) || suggestion?.merge_id ||
806
+ (input.update && state.suggestions.some(row => row.id === input.update && row.merge_id)))
807
+ throw new Error(t('当前状态不能执行此经验操作。'));
808
+ if (!source && ['add', 'edit', 'enable', 'disable', 'remove', 'revoke-source', 'distill'].includes(action))
809
+ return direct_rule_change(state, input);
810
+ if (!source && action === 'accept' && is_candidate(suggestion)) {
811
+ suggestion.selected = true;
812
+ return suggestion;
813
+ }
814
+ if (!source && action === 'accept' && suggestion?.kind === 'room_strategy')
815
+ return queue_room_strategy(state, suggestion);
816
+ if (action === 'go' && suggestion?.kind === 'rule') {
817
+ if (suggestion.stage !== 'intent') throw new Error(t('找不到要完成的意图。'));
818
+ Object.assign(suggestion, { stage: 'product', status: 'pending', created_at: now(),
819
+ text: checked_text(suggestion.source?.full_text || suggestion.source?.excerpt || suggestion.text) });
820
+ return suggestion;
528
821
  }
529
822
  if (Array.isArray(input.ids) && ['accept', 'reject', 'dismiss', 'refine', 'unrefine'].includes(action)) {
530
823
  for (const item of input.ids) change_managed_experience(state, { ...input, ids: undefined, id: item }, source);
@@ -532,27 +825,23 @@ export function change_managed_experience(state, input, source, internal = false
532
825
  }
533
826
  if (action === 'propose' && input.intent && state.suggestions.find(item => item.id === input.intent)?.kind !== 'workflow')
534
827
  throw new Error(t('经验意图由 MOSS 整理。'));
535
- const result = change_experience(state, input, source);
536
- if (action === 'propose') {
537
- const added = input.update ? state.suggestions.find(item => item.id === input.update) : state.suggestions.at(-1);
538
- if (added?.summary_message_id && added.kind !== 'rule')
539
- return enqueue_admission(state, { action: added.kind }, added);
540
- if (added?.stage === 'product' && added.kind === 'rule') return queue_rule(state, added);
541
- }
542
- return result;
828
+ return change_experience(state, input, source);
543
829
  }
544
830
 
545
- function queue_rule(state, suggestion, text) {
546
- const operation = suggestion.remove ? 'remove' : suggestion.target ? 'edit' : 'add';
547
- const original = suggestion.stage === 'intent' ? suggestion.source?.full_text || suggestion.source?.excerpt : null;
548
- return enqueue_admission(state, { action: operation, text: text ?? (original || suggestion.text) }, suggestion);
831
+ function queue_room_strategy(state, suggestion) {
832
+ const job = { id: suggestion.id, operation: 'room_strategy', suggestion_id: suggestion.id, status: 'awaiting_confirmation',
833
+ application_pending: true, target: null, room_id: suggestion.source.room_id, sources: source_rows(suggestion),
834
+ proposal: { text: suggestion.text }, created_at: now() };
835
+ state.admissions = [...(state.admissions || []), job];
836
+ Object.assign(suggestion, { admission_id: job.id, application_pending: true });
837
+ return job;
549
838
  }
550
839
 
551
- /** Keep the legacy CLI write path under the same admission gate while preserving its known entry ID. */
552
- export function queue_legacy_experience(state, text) {
840
+ /** Apply the account owner's compatibility prompt directly while preserving its known entry ID. */
841
+ export function set_legacy_experience(state, text) {
842
+ prune(state);
553
843
  const current = state.entries.find(row => row.id === LEGACY);
554
- if (!text && !current) return;
555
- const job = enqueue_admission(state, { action: !text ? 'remove' : current ? 'edit' : 'add', id: current?.id, text: text || current?.text });
556
- job.entry_id = LEGACY;
557
- return job;
844
+ if (!text) { state.entries = state.entries.filter(row => row !== current); return; }
845
+ if (!current) return replace_entry(state, null, entry(LEGACY, checked_text(text), { kind: 'user' }));
846
+ return direct_rule_change(state, { action: 'edit', id: LEGACY, text });
558
847
  }
@@ -7,6 +7,21 @@ export default {
7
7
  "房主主动总结:先核实来源,JSON 填 summary_message_id 和 suggestions。": "For an owner-requested summary, verify the sources first, then provide summary_message_id and suggestions in JSON.",
8
8
  "建议须引用本房间的用户消息或派活记录。房主主动总结时,先核实来源,再提交发起消息编号与建议列表。": "Cite user messages or dispatch records from this room. For an owner-requested summary, verify the sources first, then submit the trigger message ID and suggestions.",
9
9
  "房间总结的建议类型或目标无效。": "Invalid suggestion type or target for this room summary.",
10
+ "先用 experience list 读取账本版本;merge 的 JSON 填 ids 与 entries_revision。": "Read the ledger revision with experience list first, then pass ids and entries_revision in the merge JSON.",
11
+ "请选择有效的经验候选。": "Select valid experience candidates.",
12
+ "经验账本已变更,请重新读取。": "Read the latest experience ledger before continuing.",
13
+ "还有一批经验正在合并。": "An experience batch is already being merged.",
14
+ "一批中不能同时修改同一条经验。": "A batch cannot change the same rule more than once.",
15
+ "冲突原因和场景须各为一句,不超过 {limit} 字。": "The reason and scenario must each be one sentence, at most {limit} characters.",
16
+ "这批经验已不在冲突状态。": "This experience batch is no longer in conflict.",
17
+ "请提交冲突取舍或候选改文,二选一。": "Provide either conflict choices or revised candidate wording.",
18
+ "只能修改这一批中出现冲突的候选正文。": "You can revise only conflicting candidates from this batch.",
19
+ "重新合并须引用主理人主窗口本次收到的房主确认消息。": "Retrying a merge requires the owner’s confirmation message received in this execution in the main MOSS window.",
20
+ "处理冲突先读 conflict-read,再用 conflict-retry 带房主确认消息编号和账本版本提交。": "Use conflict-read first, then pass the owner confirmation message ID and ledger revision to conflict-retry.",
21
+ "请为每处冲突选择保留哪一条。": "Choose which rule to keep for every conflict.",
22
+ "同一条经验不能同时保留和移除。": "The same rule cannot be kept and removed.",
23
+ "找不到可撤销的经验合并。": "No undoable experience merge was found.",
24
+ "房主撤销了这一批经验合并。": "The owner undid this experience merge.",
10
25
  "只修改期限,不重新启用已停用的经验。": "Change the deadline without re-enabling a disabled rule.",
11
26
  "请指定 --id,并在 --at ISO 与 --clear 中二选一。": "Specify --id and exactly one of --at ISO or --clear.",
12
27
  "长期": "no deadline",
@@ -88,7 +103,7 @@ export default {
88
103
  "Grok 没有确认预期的会话 ID": "Grok did not confirm the expected session ID",
89
104
  "Grok 执行失败": "Grok execution failed",
90
105
  "Grok 回合未正常结束({reason})": "The Grok turn did not complete successfully ({reason})",
91
- "请只检查本次待入库经验,不跑每日排查。": "Check only this experience admission. Do not run the daily review.",
106
+ "请只处理本次经验入库任务,按任务上下文合并或检查,不跑每日排查。": "Handle only this experience task: merge or check as the task context says. Do not run the daily review.",
92
107
  "未找到要撤销的经验出处。": "The experience source could not be found.",
93
108
  "整理稿须包含三个规定章节。": "The organized draft must include the three required sections.",
94
109
  "整理稿必须恰好引用每条启用经验一次。": "The organized draft must reference every enabled rule exactly once.",
@@ -330,7 +330,7 @@ export function steward_message(skill, context, lang, confirmed = false) {
330
330
  const empty = context == null || context === '' || (typeof context === 'object' && !Object.keys(context).length);
331
331
  const words = typeof context === 'string' && !empty;
332
332
  const [request, consent] = (skill === 'dispatch-analysis' && context?.mode === 'admission'
333
- ? [t('请只检查本次待入库经验,不跑每日排查。', {}, locale), ''] : SKILL_REQUESTS[skill]?.(locale))
333
+ ? [t('请只处理本次经验入库任务,按任务上下文合并或检查,不跑每日排查。', {}, locale), ''] : SKILL_REQUESTS[skill]?.(locale))
334
334
  || [words ? context : t('请用这个技能处理,结果在这里回复我。', {}, locale), ''];
335
335
  // A sentence from the caller is shown as written; structured data from scripts keeps its labelled JSON block.
336
336
  const detail = empty || request === context ? '' : words ? context