dsh-workplan 1.6.0 → 1.7.0
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.
- package/CHANGELOG.md +57 -0
- package/README.en.md +19 -5
- package/README.md +19 -7
- package/client.js +91 -6
- package/lib/host.js +78 -6
- package/lib/plan.js +474 -11
- package/lib/runtime.js +495 -76
- package/package.json +1 -1
- package/src/client.ts +90 -8
- package/src/host.ts +81 -5
- package/src/plan.ts +476 -11
- package/src/runtime.ts +490 -73
package/lib/plan.js
CHANGED
|
@@ -18,6 +18,27 @@ export const RESULT_MARKER_BEGIN = '<!-- DSH-WORKPLAN-RESULT:BEGIN -->';
|
|
|
18
18
|
export const RESULT_MARKER_END = '<!-- DSH-WORKPLAN-RESULT:END -->';
|
|
19
19
|
export const CANCEL_MARKER_BEGIN = '<!-- DSH-WORKPLAN-CANCEL:BEGIN -->';
|
|
20
20
|
export const CANCEL_MARKER_END = '<!-- DSH-WORKPLAN-CANCEL:END -->';
|
|
21
|
+
/*
|
|
22
|
+
* [1.7.0] Two new durable message kinds.
|
|
23
|
+
*
|
|
24
|
+
* The child's structured result travels inside its own reply (not the session
|
|
25
|
+
* log), while a manual re-adjudication by the main Agent must survive a page
|
|
26
|
+
* refresh — before this it existed only in memory and vanished on reload.
|
|
27
|
+
*/
|
|
28
|
+
export const EVIDENCE_MARKER_BEGIN = '<!-- WORKPLAN_EVIDENCE:START -->';
|
|
29
|
+
export const EVIDENCE_MARKER_END = '<!-- WORKPLAN_EVIDENCE:END -->';
|
|
30
|
+
export const UPDATE_MARKER_BEGIN = '<!-- DSH-WORKPLAN-UPDATE:BEGIN -->';
|
|
31
|
+
export const UPDATE_MARKER_END = '<!-- DSH-WORKPLAN-UPDATE:END -->';
|
|
32
|
+
/** Upper bound for the run-time conversation window (single truncation point). */
|
|
33
|
+
export const MAX_CONVERSATION_CHARS = 7000;
|
|
34
|
+
/** Upper bound for one child evidence block; longer blocks are truncated. */
|
|
35
|
+
export const MAX_EVIDENCE_BLOCK_CHARS = 8000;
|
|
36
|
+
export const MAX_EVIDENCE_ACCEPTANCE = 20;
|
|
37
|
+
export const MAX_EVIDENCE_ARTIFACTS = 20;
|
|
38
|
+
export const MAX_EVIDENCE_NEEDS = 10;
|
|
39
|
+
export const VERIFICATIONS = Object.freeze(['structured', 'legacy', 'unverified', 'failed', 'unparsable']);
|
|
40
|
+
export const EVIDENCE_STATUSES = Object.freeze(['done', 'blocked', 'partial']);
|
|
41
|
+
export const ACCEPTANCE_RESULTS = Object.freeze(['pass', 'fail', 'unverified']);
|
|
21
42
|
export const STATUSES = Object.freeze(['pending', 'in_progress', 'done', 'blocked']);
|
|
22
43
|
export const LIKELIHOODS = Object.freeze(['low', 'medium', 'high']);
|
|
23
44
|
export const DEPARTMENTS = Object.freeze({
|
|
@@ -400,6 +421,14 @@ function readSubtasks(value, stageIndex, errors) {
|
|
|
400
421
|
dependsOn: readStringArray(source.dependsOn, `${base}.dependsOn`, { min: 0, max: 12, itemMax: 16 }, errors),
|
|
401
422
|
acceptance: readStringArray(source.acceptance, `${base}.acceptance`, { min: 1, max: 8, itemMax: 800 }, errors),
|
|
402
423
|
risk: readString(source.risk, `${base}.risk`, 1, 1000, errors),
|
|
424
|
+
/*
|
|
425
|
+
* [1.7.0] Optional time estimate, advisory only. Validation never fails on
|
|
426
|
+
* a missing or out-of-range value: a plan that cannot be dispatched is
|
|
427
|
+
* worse than one carrying a rough estimate.
|
|
428
|
+
*/
|
|
429
|
+
...(Number.isFinite(Number(source.estimateMinutes))
|
|
430
|
+
? { estimateMinutes: Math.min(15, Math.max(1, Math.round(Number(source.estimateMinutes)))) }
|
|
431
|
+
: {}),
|
|
403
432
|
};
|
|
404
433
|
});
|
|
405
434
|
}
|
|
@@ -631,10 +660,14 @@ export function departmentLabel(id, language = 'zh') {
|
|
|
631
660
|
return id;
|
|
632
661
|
return language === 'en' ? entry.en : entry.zh;
|
|
633
662
|
}
|
|
634
|
-
export function buildPlannerPrompt(taskText, cwd, conversationContext = '') {
|
|
663
|
+
export function buildPlannerPrompt(taskText, cwd, conversationContext = '', budget = {}) {
|
|
635
664
|
const departments = DEPARTMENT_IDS
|
|
636
665
|
.map((id) => { const d = DEPARTMENTS[id]; return `- ${id}(${d.zh} / ${d.en})`; })
|
|
637
666
|
.join('\n');
|
|
667
|
+
const totalMinutes = Math.max(1, Math.round(Number(budget?.totalMinutes) || 20));
|
|
668
|
+
const childMinutes = Math.max(1, Math.round(Number(budget?.childMinutes) || 15));
|
|
669
|
+
const concurrency = Math.max(1, Number(budget?.concurrency) || MAX_CONCURRENT);
|
|
670
|
+
const resumes = Number.isFinite(Number(budget?.maxResumes)) ? Number(budget.maxResumes) : MAX_PLAN_RESUMES;
|
|
638
671
|
const task = truncate(taskText, 16000);
|
|
639
672
|
const directory = typeof cwd === 'string' && cwd ? cwd : '(未知)';
|
|
640
673
|
const context = truncate(conversationContext, 7000);
|
|
@@ -663,6 +696,12 @@ export function buildPlannerPrompt(taskText, cwd, conversationContext = '') {
|
|
|
663
696
|
'- 单个子任务应能在 10 分钟内完成;动手重的任务要拆成多个小步,避免整条计划被一个慢子任务拖住。',
|
|
664
697
|
'- 不要输出 Markdown 代码围栏、解释或前后缀;只输出一个 JSON 对象。',
|
|
665
698
|
'',
|
|
699
|
+
'本轮时间预算(硬事实,请据此规划规模):',
|
|
700
|
+
`- 一轮总预算约 ${totalMinutes} 分钟;单个子任务上限 ${childMinutes} 分钟;同时最多 ${concurrency} 个子任务并行。`,
|
|
701
|
+
`- 受阻后自动续跑额度 ${resumes} 次;总工作量超过一轮预算时,计划会被暂停并在下一轮继续。`,
|
|
702
|
+
'- 每个子任务必须写 estimateMinutes(整数 1-15):你预估它需要多少分钟。宁可估高,不要估低。',
|
|
703
|
+
'- 规模大就如实拆成多轮,不要为了塞进一轮而把多个交付物压进一个子任务。',
|
|
704
|
+
'',
|
|
666
705
|
'可用部门:',
|
|
667
706
|
departments,
|
|
668
707
|
'',
|
|
@@ -715,7 +754,8 @@ export function buildPlannerPrompt(taskText, cwd, conversationContext = '') {
|
|
|
715
754
|
' "outputs": ["输出/交付物"],',
|
|
716
755
|
' "dependsOn": [],',
|
|
717
756
|
' "acceptance": ["可测试的验收标准"],',
|
|
718
|
-
' "risk": "主要风险"',
|
|
757
|
+
' "risk": "主要风险",',
|
|
758
|
+
' "estimateMinutes": 5',
|
|
719
759
|
' }',
|
|
720
760
|
' ]',
|
|
721
761
|
' }',
|
|
@@ -754,7 +794,43 @@ export function buildPlanSummary(plan) {
|
|
|
754
794
|
const primary = plan.contradictions.primary.statement;
|
|
755
795
|
return truncate(`【任务分解】${plan.title}|${plan.stages.length} 个阶段 / ${total} 个子任务|主要矛盾:${primary}`, 300);
|
|
756
796
|
}
|
|
757
|
-
|
|
797
|
+
/**
|
|
798
|
+
* Conservative lower bound for how long this plan needs, in minutes.
|
|
799
|
+
*
|
|
800
|
+
* The estimate is deliberately a lower bound: `ceil(total / concurrency)` and
|
|
801
|
+
* the largest single estimate, whichever is larger. It only drives an advisory
|
|
802
|
+
* line in the plan message; it never blocks dispatch, because a legal plan that
|
|
803
|
+
* cannot start is a worse failure than one that is merely too big for one round.
|
|
804
|
+
*/
|
|
805
|
+
export function estimatePlanMinutes(plan, fallbackMinutes = 15, concurrency = MAX_CONCURRENT) {
|
|
806
|
+
const subtasks = flattenSubtasks(plan).map((entry) => entry.subtask);
|
|
807
|
+
const total = subtasks.length;
|
|
808
|
+
if (total === 0)
|
|
809
|
+
return 0;
|
|
810
|
+
const estimates = subtasks.map((subtask) => {
|
|
811
|
+
const value = Number(subtask?.estimateMinutes);
|
|
812
|
+
return Number.isFinite(value) && value > 0 ? value : fallbackMinutes;
|
|
813
|
+
});
|
|
814
|
+
const maxEstimate = Math.max(...estimates);
|
|
815
|
+
const waves = Math.ceil(total / Math.max(1, concurrency));
|
|
816
|
+
const totalEstimate = estimates.reduce((sum, value) => sum + value, 0);
|
|
817
|
+
return Math.max(waves * maxEstimate, Math.ceil(totalEstimate / Math.max(1, concurrency)));
|
|
818
|
+
}
|
|
819
|
+
export function buildBudgetWarning(plan, totalBudgetMinutes = 20, maxResumes = MAX_PLAN_RESUMES) {
|
|
820
|
+
const minutes = estimatePlanMinutes(plan);
|
|
821
|
+
const budget = Math.max(1, Math.round(Number(totalBudgetMinutes) || 20));
|
|
822
|
+
if (minutes <= budget)
|
|
823
|
+
return '';
|
|
824
|
+
const rounds = Math.max(1, Math.ceil(minutes / budget));
|
|
825
|
+
const missing = flattenSubtasks(plan).some((entry) => !Number.isFinite(Number(entry.subtask?.estimateMinutes)));
|
|
826
|
+
return [
|
|
827
|
+
`⚠ 预算提示:本计划 ${flattenSubtasks(plan).length} 项,按其估计约需 ${minutes} 分钟 > 本轮 ${budget} 分钟,`
|
|
828
|
+
+ `预计需要约 ${rounds} 轮(续跑额度 ${maxResumes} 次)。`,
|
|
829
|
+
'建议:拆成多轮,或减少同时进行的子任务。',
|
|
830
|
+
...(missing ? ['(部分子任务缺少 estimateMinutes,已按 15 分钟上限估算。)'] : []),
|
|
831
|
+
].join('\n');
|
|
832
|
+
}
|
|
833
|
+
export function buildPlanMessage(plan, options = {}) {
|
|
758
834
|
const summary = buildPlanSummary(plan);
|
|
759
835
|
const payload = {
|
|
760
836
|
kind: 'workplan',
|
|
@@ -765,7 +841,15 @@ export function buildPlanMessage(plan) {
|
|
|
765
841
|
createdAt: plan.createdAt,
|
|
766
842
|
plan,
|
|
767
843
|
};
|
|
768
|
-
const
|
|
844
|
+
const warning = buildBudgetWarning(plan, options.totalBudgetMinutes ?? 20, options.maxResumes ?? MAX_PLAN_RESUMES);
|
|
845
|
+
const text = [
|
|
846
|
+
summary,
|
|
847
|
+
...(warning ? ['', warning] : []),
|
|
848
|
+
'',
|
|
849
|
+
PLAN_MARKER_BEGIN,
|
|
850
|
+
JSON.stringify(payload),
|
|
851
|
+
PLAN_MARKER_END,
|
|
852
|
+
].join('\n');
|
|
769
853
|
return makeUserMessage(text, { kind: 'workplan', form: 'notice', summary });
|
|
770
854
|
}
|
|
771
855
|
export function buildDegradedMessage(options) {
|
|
@@ -832,6 +916,34 @@ export function buildResultMessage(result) {
|
|
|
832
916
|
};
|
|
833
917
|
const blocked = Number(result.stats?.blocked ?? 0);
|
|
834
918
|
const paused = Number(result.stats?.pending ?? 0) > 0 && result.phase === 'paused';
|
|
919
|
+
/*
|
|
920
|
+
* [1.7.0] Evidence review block.
|
|
921
|
+
*
|
|
922
|
+
* A done row is no longer self-certifying: the main Agent is told exactly how
|
|
923
|
+
* many claims are unverified, which self-checks failed, which declared files
|
|
924
|
+
* are missing, and what a sibling department asked for. Keeping this out of
|
|
925
|
+
* the payload (it is derived) keeps the durable message small.
|
|
926
|
+
*/
|
|
927
|
+
const statuses = Array.isArray(result.statuses) ? result.statuses : [];
|
|
928
|
+
const unverified = statuses.filter((item) => item?.verification === 'unverified');
|
|
929
|
+
const failed = statuses.filter((item) => item?.verification === 'failed');
|
|
930
|
+
const legacy = statuses.filter((item) => item?.status === 'done' && item?.verification === 'legacy');
|
|
931
|
+
const missingArtifacts = statuses.flatMap((item) => (Array.isArray(item?.missingArtifacts) ? item.missingArtifacts : [])
|
|
932
|
+
.map((ref) => `${item.subtaskId}:${ref}`));
|
|
933
|
+
const needs = statuses.flatMap((item) => (Array.isArray(item?.needs) ? item.needs : []).map((need) => `${item.subtaskId}:${need}`));
|
|
934
|
+
const review = [];
|
|
935
|
+
if (unverified.length > 0) {
|
|
936
|
+
review.push(`- 未验证 ${unverified.length} 条:${unverified.map((item) => item.subtaskId).join('、')}(完成但证据不足,需主 Agent 核对)`);
|
|
937
|
+
}
|
|
938
|
+
if (failed.length > 0) {
|
|
939
|
+
review.push(`- 自检失败 ${failed.length} 条:${failed.map((item) => item.subtaskId).join('、')}(已按受阻处理,禁止当完成)`);
|
|
940
|
+
}
|
|
941
|
+
if (legacy.length > 0) {
|
|
942
|
+
review.push(`- 未提供结构化证据 ${legacy.length} 条:${legacy.map((item) => item.subtaskId).join('、')}(旧格式回传,按“未验证”对待)`);
|
|
943
|
+
}
|
|
944
|
+
if (missingArtifacts.length > 0) {
|
|
945
|
+
review.push(`- 声明产物缺失:${missingArtifacts.slice(0, 10).join(';')}`);
|
|
946
|
+
}
|
|
835
947
|
const lines = [
|
|
836
948
|
summary,
|
|
837
949
|
'',
|
|
@@ -839,6 +951,10 @@ export function buildResultMessage(result) {
|
|
|
839
951
|
'1. 核对每个完成项的证据与验收标准;',
|
|
840
952
|
'2. 处理受阻项,必要时向用户确认;',
|
|
841
953
|
'3. 给出最终答复,不要声称未验证的完成。',
|
|
954
|
+
...(review.length > 0 ? ['', '验收核对:', ...review] : []),
|
|
955
|
+
...(needs.length > 0
|
|
956
|
+
? ['', '跨部门待转达(子 Agent 提出的需求,请逐条处理):', ...needs.slice(0, 10).map((line) => `- ${line}`)]
|
|
957
|
+
: []),
|
|
842
958
|
// A blocked plan used to look identical to a finished one. State the exact
|
|
843
959
|
// recovery move so the model retries the failed work instead of rebuilding
|
|
844
960
|
// the whole plan or stopping to ask the user for a repeated request.
|
|
@@ -937,6 +1053,230 @@ export function parseCancelMessage(message) {
|
|
|
937
1053
|
return null;
|
|
938
1054
|
}
|
|
939
1055
|
}
|
|
1056
|
+
function readEvidenceAcceptance(value) {
|
|
1057
|
+
if (!Array.isArray(value))
|
|
1058
|
+
return [];
|
|
1059
|
+
return value.slice(0, MAX_EVIDENCE_ACCEPTANCE).map((item) => {
|
|
1060
|
+
const source = isRecord(item) ? item : {};
|
|
1061
|
+
const result = ACCEPTANCE_RESULTS.includes(source.result) ? source.result : 'unverified';
|
|
1062
|
+
return {
|
|
1063
|
+
criterion: truncate(String(source.criterion ?? ''), 500),
|
|
1064
|
+
result,
|
|
1065
|
+
evidence: truncate(String(source.evidence ?? ''), 300),
|
|
1066
|
+
};
|
|
1067
|
+
}).filter((item) => item.criterion !== '');
|
|
1068
|
+
}
|
|
1069
|
+
function readEvidenceArtifacts(value) {
|
|
1070
|
+
if (!Array.isArray(value))
|
|
1071
|
+
return [];
|
|
1072
|
+
return value.slice(0, MAX_EVIDENCE_ARTIFACTS).map((item) => {
|
|
1073
|
+
const source = isRecord(item) ? item : {};
|
|
1074
|
+
const kind = ['file', 'url', 'note'].includes(source.kind) ? source.kind : 'note';
|
|
1075
|
+
const artifact = { kind, ref: truncate(String(source.ref ?? ''), 500) };
|
|
1076
|
+
if (typeof source.exists === 'boolean')
|
|
1077
|
+
artifact.exists = source.exists;
|
|
1078
|
+
return artifact;
|
|
1079
|
+
}).filter((item) => item.ref !== '');
|
|
1080
|
+
}
|
|
1081
|
+
function readEvidenceNeeds(value) {
|
|
1082
|
+
if (!Array.isArray(value))
|
|
1083
|
+
return [];
|
|
1084
|
+
return value.slice(0, MAX_EVIDENCE_NEEDS)
|
|
1085
|
+
.map((item) => truncate(typeof item === 'string' ? item : String(item ?? ''), 300))
|
|
1086
|
+
.filter(Boolean);
|
|
1087
|
+
}
|
|
1088
|
+
/**
|
|
1089
|
+
* Parse the child's structured evidence block.
|
|
1090
|
+
*
|
|
1091
|
+
* Only the last block is read: a child may quote the template from its prompt
|
|
1092
|
+
* before filling in the real one, and the filled-in copy is the last one.
|
|
1093
|
+
* A malformed block is reported as such instead of being silently ignored —
|
|
1094
|
+
* "cannot tell" must never default to "done".
|
|
1095
|
+
*/
|
|
1096
|
+
export function parseEvidenceBlock(output) {
|
|
1097
|
+
const text = typeof output === 'string' ? output : '';
|
|
1098
|
+
const begin = text.lastIndexOf(EVIDENCE_MARKER_BEGIN);
|
|
1099
|
+
if (begin < 0)
|
|
1100
|
+
return { found: false, malformed: false, truncated: false, payload: null, raw: '' };
|
|
1101
|
+
const end = text.indexOf(EVIDENCE_MARKER_END, begin + EVIDENCE_MARKER_BEGIN.length);
|
|
1102
|
+
if (end < 0)
|
|
1103
|
+
return { found: true, malformed: true, truncated: false, payload: null, raw: '' };
|
|
1104
|
+
const raw = text.slice(begin + EVIDENCE_MARKER_BEGIN.length, end).trim();
|
|
1105
|
+
const truncated = raw.length > MAX_EVIDENCE_BLOCK_CHARS;
|
|
1106
|
+
try {
|
|
1107
|
+
const payload = JSON.parse(raw);
|
|
1108
|
+
if (!isRecord(payload) || !EVIDENCE_STATUSES.includes(payload.status)) {
|
|
1109
|
+
return { found: true, malformed: true, truncated, payload: null, raw };
|
|
1110
|
+
}
|
|
1111
|
+
return { found: true, malformed: false, truncated, payload, raw };
|
|
1112
|
+
}
|
|
1113
|
+
catch {
|
|
1114
|
+
return { found: true, malformed: true, truncated, payload: null, raw };
|
|
1115
|
+
}
|
|
1116
|
+
}
|
|
1117
|
+
const BLOCKED_LINE = /^\s*(BLOCKED|受阻|无法完成)\s*[::]\s*/i;
|
|
1118
|
+
/**
|
|
1119
|
+
* Deterministic verdict for one child result.
|
|
1120
|
+
*
|
|
1121
|
+
* This is the single place that decides done vs blocked, so the eight cases in
|
|
1122
|
+
* the acceptance table cannot drift apart between the runtime and the replay.
|
|
1123
|
+
* It never invents evidence and never upgrades a failed self-check to done.
|
|
1124
|
+
*/
|
|
1125
|
+
export function adjudicateResult({ output, strict = true }) {
|
|
1126
|
+
const text = typeof output === 'string' ? output : '';
|
|
1127
|
+
const parsed = parseEvidenceBlock(text);
|
|
1128
|
+
if (!strict) {
|
|
1129
|
+
if (BLOCKED_LINE.test(text)) {
|
|
1130
|
+
return {
|
|
1131
|
+
status: 'blocked',
|
|
1132
|
+
verification: 'legacy',
|
|
1133
|
+
acceptance: [],
|
|
1134
|
+
artifacts: [],
|
|
1135
|
+
needs: [],
|
|
1136
|
+
error: text.replace(BLOCKED_LINE, '').trim() || '子 Agent 报告受阻',
|
|
1137
|
+
};
|
|
1138
|
+
}
|
|
1139
|
+
return { status: 'done', verification: 'legacy', acceptance: [], artifacts: [], needs: [], error: null };
|
|
1140
|
+
}
|
|
1141
|
+
if (parsed.malformed) {
|
|
1142
|
+
return {
|
|
1143
|
+
status: 'blocked',
|
|
1144
|
+
verification: 'unparsable',
|
|
1145
|
+
acceptance: [],
|
|
1146
|
+
artifacts: [],
|
|
1147
|
+
needs: [],
|
|
1148
|
+
error: '结果块无法解析,请主 Agent 核对',
|
|
1149
|
+
};
|
|
1150
|
+
}
|
|
1151
|
+
if (!parsed.found) {
|
|
1152
|
+
if (BLOCKED_LINE.test(text)) {
|
|
1153
|
+
return {
|
|
1154
|
+
status: 'blocked',
|
|
1155
|
+
verification: 'legacy',
|
|
1156
|
+
acceptance: [],
|
|
1157
|
+
artifacts: [],
|
|
1158
|
+
needs: [],
|
|
1159
|
+
error: text.replace(BLOCKED_LINE, '').trim() || '子 Agent 报告受阻',
|
|
1160
|
+
};
|
|
1161
|
+
}
|
|
1162
|
+
return { status: 'done', verification: 'legacy', acceptance: [], artifacts: [], needs: [], error: null };
|
|
1163
|
+
}
|
|
1164
|
+
const payload = parsed.payload;
|
|
1165
|
+
const acceptance = readEvidenceAcceptance(payload.acceptance);
|
|
1166
|
+
const artifacts = readEvidenceArtifacts(payload.artifacts);
|
|
1167
|
+
const needs = readEvidenceNeeds(payload.needs);
|
|
1168
|
+
const blockedReason = truncate(String(payload.blockedReason ?? payload.error ?? ''), 2000);
|
|
1169
|
+
if (payload.status === 'blocked') {
|
|
1170
|
+
return {
|
|
1171
|
+
status: 'blocked',
|
|
1172
|
+
verification: 'structured',
|
|
1173
|
+
acceptance,
|
|
1174
|
+
artifacts,
|
|
1175
|
+
needs,
|
|
1176
|
+
error: blockedReason || '子 Agent 报告受阻',
|
|
1177
|
+
};
|
|
1178
|
+
}
|
|
1179
|
+
if (payload.status === 'partial') {
|
|
1180
|
+
const detail = truncate(String(payload.summary ?? payload.blockedReason ?? ''), 2000);
|
|
1181
|
+
return {
|
|
1182
|
+
status: 'blocked',
|
|
1183
|
+
verification: 'structured',
|
|
1184
|
+
acceptance,
|
|
1185
|
+
artifacts,
|
|
1186
|
+
needs,
|
|
1187
|
+
error: detail ? `部分完成:${detail}` : '部分完成',
|
|
1188
|
+
};
|
|
1189
|
+
}
|
|
1190
|
+
const failed = acceptance.filter((item) => item.result === 'fail');
|
|
1191
|
+
if (failed.length > 0) {
|
|
1192
|
+
return {
|
|
1193
|
+
status: 'blocked',
|
|
1194
|
+
verification: 'failed',
|
|
1195
|
+
acceptance,
|
|
1196
|
+
artifacts,
|
|
1197
|
+
needs,
|
|
1198
|
+
error: `自检未通过:${failed.map((item) => item.criterion).join(';')}`,
|
|
1199
|
+
};
|
|
1200
|
+
}
|
|
1201
|
+
const hasUnverified = acceptance.some((item) => item.result === 'unverified');
|
|
1202
|
+
return {
|
|
1203
|
+
status: 'done',
|
|
1204
|
+
verification: hasUnverified ? 'unverified' : 'structured',
|
|
1205
|
+
acceptance,
|
|
1206
|
+
artifacts,
|
|
1207
|
+
needs,
|
|
1208
|
+
error: null,
|
|
1209
|
+
};
|
|
1210
|
+
}
|
|
1211
|
+
export function buildUpdateMessage(update) {
|
|
1212
|
+
const payload = {
|
|
1213
|
+
kind: 'workplan-update',
|
|
1214
|
+
version: PLAN_VERSION,
|
|
1215
|
+
planId: update.planId,
|
|
1216
|
+
subtaskId: update.subtaskId,
|
|
1217
|
+
status: update.status,
|
|
1218
|
+
...(update.progress === undefined ? {} : { progress: update.progress }),
|
|
1219
|
+
...(update.note === undefined ? {} : { note: update.note }),
|
|
1220
|
+
...(update.evidence === undefined ? {} : { evidence: update.evidence }),
|
|
1221
|
+
...(update.revision === undefined ? {} : { revision: update.revision }),
|
|
1222
|
+
at: update.at ?? Date.now(),
|
|
1223
|
+
};
|
|
1224
|
+
const summary = truncate(`【状态改判】${update.subtaskId} → ${update.status}`, 300);
|
|
1225
|
+
const lines = [
|
|
1226
|
+
summary,
|
|
1227
|
+
'',
|
|
1228
|
+
'这条记录是主 Agent 的人工改判,刷新/重启后按同一顺序回放,不会丢失。',
|
|
1229
|
+
'',
|
|
1230
|
+
UPDATE_MARKER_BEGIN,
|
|
1231
|
+
JSON.stringify(payload),
|
|
1232
|
+
UPDATE_MARKER_END,
|
|
1233
|
+
];
|
|
1234
|
+
return makeUserMessage(lines.join('\n'), { kind: 'workplan-update', form: 'notice', summary });
|
|
1235
|
+
}
|
|
1236
|
+
export function parseUpdateMessage(message) {
|
|
1237
|
+
const body = extractBetween(messageText(message), UPDATE_MARKER_BEGIN, UPDATE_MARKER_END);
|
|
1238
|
+
if (!body)
|
|
1239
|
+
return null;
|
|
1240
|
+
try {
|
|
1241
|
+
const payload = JSON.parse(body);
|
|
1242
|
+
if (!isRecord(payload) || payload.kind !== 'workplan-update')
|
|
1243
|
+
return null;
|
|
1244
|
+
return payload;
|
|
1245
|
+
}
|
|
1246
|
+
catch {
|
|
1247
|
+
return null;
|
|
1248
|
+
}
|
|
1249
|
+
}
|
|
1250
|
+
/**
|
|
1251
|
+
* Read-only sibling briefing for one child.
|
|
1252
|
+
*
|
|
1253
|
+
* Departments cannot message each other directly (see collaboration docs), so
|
|
1254
|
+
* "紧密联系" is delivered as visibility: every child sees what its siblings are
|
|
1255
|
+
* producing and the status they reached. Only `done` siblings expose a summary,
|
|
1256
|
+
* which keeps half-finished work from leaking into another department's prompt.
|
|
1257
|
+
*/
|
|
1258
|
+
export function buildTeamBrief(plan, statuses, subtask) {
|
|
1259
|
+
if (!plan || !Array.isArray(statuses))
|
|
1260
|
+
return '';
|
|
1261
|
+
const byId = new Map(statuses.map((item) => [item.subtaskId, item]));
|
|
1262
|
+
const lines = [];
|
|
1263
|
+
for (const { subtask: sibling } of flattenSubtasks(plan)) {
|
|
1264
|
+
if (sibling.id === subtask?.id)
|
|
1265
|
+
continue;
|
|
1266
|
+
const status = byId.get(sibling.id);
|
|
1267
|
+
const state = typeof status?.status === 'string' ? status.status : 'pending';
|
|
1268
|
+
const outputHint = Array.isArray(sibling.outputs) && sibling.outputs.length > 0
|
|
1269
|
+
? `;产出 ${truncate(sibling.outputs.join('、'), 120)}`
|
|
1270
|
+
: '';
|
|
1271
|
+
const summary = state === 'done' && typeof status?.summary === 'string' && status.summary
|
|
1272
|
+
? `|摘要:${truncate(status.summary, 200)}`
|
|
1273
|
+
: '';
|
|
1274
|
+
lines.push(`- ${sibling.id} ${departmentLabel(sibling.department)}:目标 ${truncate(sibling.objective, 120)}${outputHint}|状态:${state}${summary}`);
|
|
1275
|
+
}
|
|
1276
|
+
if (lines.length === 0)
|
|
1277
|
+
return '';
|
|
1278
|
+
return truncate(lines.join('\n'), 2000);
|
|
1279
|
+
}
|
|
940
1280
|
/*
|
|
941
1281
|
* Replay a durable result message into statuses. Dashboard reconstruction used
|
|
942
1282
|
* to read only the plan message, so after a page refresh every finished child
|
|
@@ -952,7 +1292,16 @@ export function applyResultStatuses(statuses, result) {
|
|
|
952
1292
|
continue;
|
|
953
1293
|
if (!STATUSES.includes(entry.status))
|
|
954
1294
|
continue;
|
|
955
|
-
|
|
1295
|
+
const current = next.find((item) => item.subtaskId === entry.subtaskId);
|
|
1296
|
+
if (!current)
|
|
1297
|
+
continue;
|
|
1298
|
+
/*
|
|
1299
|
+
* A manually re-adjudicated status (durable `workplan-update`) must not be
|
|
1300
|
+
* rolled back by an older result snapshot. Only comparable revisions are
|
|
1301
|
+
* ordered; legacy entries without `revision` keep the old "last wins" rule.
|
|
1302
|
+
*/
|
|
1303
|
+
if (Number.isInteger(entry.revision) && Number.isInteger(current.revision)
|
|
1304
|
+
&& Number(entry.revision) < Number(current.revision))
|
|
956
1305
|
continue;
|
|
957
1306
|
try {
|
|
958
1307
|
next = applyStatus(next, entry.subtaskId, {
|
|
@@ -963,6 +1312,14 @@ export function applyResultStatuses(statuses, result) {
|
|
|
963
1312
|
finishedAt: entry.finishedAt ?? null,
|
|
964
1313
|
summary: typeof entry.summary === 'string' ? entry.summary : undefined,
|
|
965
1314
|
error: entry.error ?? null,
|
|
1315
|
+
verification: entry.verification,
|
|
1316
|
+
acceptance: entry.acceptance,
|
|
1317
|
+
artifacts: entry.artifacts,
|
|
1318
|
+
missingArtifacts: entry.missingArtifacts,
|
|
1319
|
+
needs: entry.needs,
|
|
1320
|
+
blockedBy: entry.blockedBy,
|
|
1321
|
+
revision: entry.revision,
|
|
1322
|
+
updatedBy: entry.updatedBy,
|
|
966
1323
|
});
|
|
967
1324
|
}
|
|
968
1325
|
catch {
|
|
@@ -1015,6 +1372,46 @@ export function applyStatus(statuses, subtaskId, patch) {
|
|
|
1015
1372
|
next.summary = truncate(String(patch.summary), 3000);
|
|
1016
1373
|
if (patch.error !== undefined)
|
|
1017
1374
|
next.error = patch.error === null ? null : truncate(String(patch.error), 2000);
|
|
1375
|
+
if (patch.verification !== undefined) {
|
|
1376
|
+
if (!VERIFICATIONS.includes(patch.verification)) {
|
|
1377
|
+
throw new PlanError(`非法 verification:${String(patch.verification)}`, 'INVALID_VERIFICATION');
|
|
1378
|
+
}
|
|
1379
|
+
next.verification = patch.verification;
|
|
1380
|
+
}
|
|
1381
|
+
if (patch.acceptance !== undefined)
|
|
1382
|
+
next.acceptance = readEvidenceAcceptance(patch.acceptance);
|
|
1383
|
+
if (patch.artifacts !== undefined)
|
|
1384
|
+
next.artifacts = readEvidenceArtifacts(patch.artifacts);
|
|
1385
|
+
if (patch.missingArtifacts !== undefined) {
|
|
1386
|
+
let budget = 2000;
|
|
1387
|
+
next.missingArtifacts = (Array.isArray(patch.missingArtifacts) ? patch.missingArtifacts : [])
|
|
1388
|
+
.slice(0, MAX_EVIDENCE_ARTIFACTS)
|
|
1389
|
+
.map((ref) => truncate(String(ref ?? ''), 300))
|
|
1390
|
+
.filter((ref) => {
|
|
1391
|
+
if (!ref || budget <= 0)
|
|
1392
|
+
return false;
|
|
1393
|
+
budget -= ref.length;
|
|
1394
|
+
return true;
|
|
1395
|
+
});
|
|
1396
|
+
}
|
|
1397
|
+
if (patch.needs !== undefined)
|
|
1398
|
+
next.needs = readEvidenceNeeds(patch.needs);
|
|
1399
|
+
if (patch.blockedBy !== undefined) {
|
|
1400
|
+
next.blockedBy = (Array.isArray(patch.blockedBy) ? patch.blockedBy : [])
|
|
1401
|
+
.slice(0, 10)
|
|
1402
|
+
.filter((item) => isRecord(item) && typeof item.id === 'string')
|
|
1403
|
+
.map((item) => ({ id: item.id, reason: truncate(String(item.reason ?? ''), 300) }));
|
|
1404
|
+
}
|
|
1405
|
+
/*
|
|
1406
|
+
* [1.7.0] Monotonic revision + author.
|
|
1407
|
+
*
|
|
1408
|
+
* Every write bumps the revision, so a stale page (or an older replay entry)
|
|
1409
|
+
* can be told apart from a newer manual re-adjudication. `updatedBy` records
|
|
1410
|
+
* who wrote it: the child, the main Agent, or the system.
|
|
1411
|
+
*/
|
|
1412
|
+
const revision = Number.isInteger(patch.revision) ? Number(patch.revision) : Number(current.revision ?? 0) + 1;
|
|
1413
|
+
next.revision = Math.max(revision, Number(current.revision ?? 0) + 1);
|
|
1414
|
+
next.updatedBy = ['child', 'agent', 'system'].includes(patch.updatedBy) ? patch.updatedBy : 'system';
|
|
1018
1415
|
if (patch.status === 'done') {
|
|
1019
1416
|
next.progress = 100;
|
|
1020
1417
|
if (next.finishedAt === null)
|
|
@@ -1038,6 +1435,19 @@ export function applyStatus(statuses, subtaskId, patch) {
|
|
|
1038
1435
|
next.summary = '';
|
|
1039
1436
|
if (patch.error === undefined)
|
|
1040
1437
|
next.error = null;
|
|
1438
|
+
// The evidence of the failed attempt must not survive a reset either.
|
|
1439
|
+
if (patch.verification === undefined)
|
|
1440
|
+
next.verification = undefined;
|
|
1441
|
+
if (patch.acceptance === undefined)
|
|
1442
|
+
next.acceptance = undefined;
|
|
1443
|
+
if (patch.artifacts === undefined)
|
|
1444
|
+
next.artifacts = undefined;
|
|
1445
|
+
if (patch.missingArtifacts === undefined)
|
|
1446
|
+
next.missingArtifacts = undefined;
|
|
1447
|
+
if (patch.needs === undefined)
|
|
1448
|
+
next.needs = undefined;
|
|
1449
|
+
if (patch.blockedBy === undefined)
|
|
1450
|
+
next.blockedBy = undefined;
|
|
1041
1451
|
}
|
|
1042
1452
|
if (patch.status === 'in_progress') {
|
|
1043
1453
|
if (next.startedAt === null)
|
|
@@ -1404,22 +1814,33 @@ export function nextReadyInStage(plan, statuses, stageId) {
|
|
|
1404
1814
|
* Readiness across the whole plan, not per stage. A stage is only a grouping
|
|
1405
1815
|
* label; making every later stage wait for every earlier stage lets one slow
|
|
1406
1816
|
* child turn an entire plan red. Only real dependsOn edges gate a subtask.
|
|
1817
|
+
*
|
|
1818
|
+
* [1.7.0] A `done` dependency only counts when its declared file artifacts
|
|
1819
|
+
* actually exist. `dependencyOk` is injectable so the rule stays pure and can
|
|
1820
|
+
* be turned off for compatibility (`artifactGate:false`).
|
|
1407
1821
|
*/
|
|
1408
|
-
export function readySubtasks(plan, statuses) {
|
|
1822
|
+
export function readySubtasks(plan, statuses, options = {}) {
|
|
1409
1823
|
const byId = new Map(statuses.map((item) => [item.subtaskId, item]));
|
|
1824
|
+
const dependencyOk = typeof options.dependencyOk === 'function'
|
|
1825
|
+
? options.dependencyOk
|
|
1826
|
+
: (dependency) => Boolean(dependency) && dependency.status === 'done';
|
|
1410
1827
|
return flattenSubtasks(plan)
|
|
1411
1828
|
.map((entry) => entry.subtask)
|
|
1412
1829
|
.filter((subtask) => {
|
|
1413
1830
|
const status = byId.get(subtask.id);
|
|
1414
1831
|
if (!status || status.status !== 'pending')
|
|
1415
1832
|
return false;
|
|
1416
|
-
return subtask.dependsOn.every((dependency) => byId.get(dependency)
|
|
1833
|
+
return subtask.dependsOn.every((dependency) => dependencyOk(byId.get(dependency), dependency));
|
|
1417
1834
|
});
|
|
1418
1835
|
}
|
|
1419
|
-
export function markDependentsBlocked(plan, statuses, blockedId) {
|
|
1836
|
+
export function markDependentsBlocked(plan, statuses, blockedId, cause = null) {
|
|
1420
1837
|
let next = statuses.slice();
|
|
1421
1838
|
let changed = true;
|
|
1422
1839
|
const blocked = new Set([blockedId]);
|
|
1840
|
+
const upstreamLabel = (id) => {
|
|
1841
|
+
const title = findSubtask(plan, id)?.subtask?.title;
|
|
1842
|
+
return title ? `${id}「${title}」` : String(id);
|
|
1843
|
+
};
|
|
1423
1844
|
while (changed) {
|
|
1424
1845
|
changed = false;
|
|
1425
1846
|
for (const { subtask } of flattenSubtasks(plan)) {
|
|
@@ -1429,9 +1850,22 @@ export function markDependentsBlocked(plan, statuses, blockedId) {
|
|
|
1429
1850
|
if (!status || status.status !== 'pending')
|
|
1430
1851
|
continue;
|
|
1431
1852
|
if (subtask.dependsOn.some((dependency) => blocked.has(dependency))) {
|
|
1853
|
+
const direct = subtask.dependsOn.filter((id) => blocked.has(id));
|
|
1854
|
+
/*
|
|
1855
|
+
* Name the upstream and the concrete cause. "上游子任务受阻" alone sent
|
|
1856
|
+
* the main Agent back to the plan to guess which child failed and why;
|
|
1857
|
+
* the reason and the missing artifacts belong in the message.
|
|
1858
|
+
*/
|
|
1859
|
+
const parts = [`上游子任务受阻:${direct.map(upstreamLabel).join('、')}`];
|
|
1860
|
+
if (cause?.reason)
|
|
1861
|
+
parts.push(`原因:${truncate(String(cause.reason), 300)}`);
|
|
1862
|
+
if (Array.isArray(cause?.missingArtifacts) && cause.missingArtifacts.length > 0) {
|
|
1863
|
+
parts.push(`缺失产物:${cause.missingArtifacts.slice(0, 10).join('、')}`);
|
|
1864
|
+
}
|
|
1432
1865
|
next = applyStatus(next, subtask.id, {
|
|
1433
1866
|
status: 'blocked',
|
|
1434
|
-
error:
|
|
1867
|
+
error: parts.join(';'),
|
|
1868
|
+
blockedBy: [{ id: blockedId, reason: cause?.reason ? truncate(String(cause.reason), 300) : `上游 ${upstreamLabel(blockedId)} 受阻` }],
|
|
1435
1869
|
});
|
|
1436
1870
|
blocked.add(subtask.id);
|
|
1437
1871
|
changed = true;
|
|
@@ -1541,7 +1975,7 @@ export function findSubtask(plan, subtaskId) {
|
|
|
1541
1975
|
}
|
|
1542
1976
|
return null;
|
|
1543
1977
|
}
|
|
1544
|
-
export function buildChildPrompt({ plan, subtask, stage, dependencyResults, cwd, conversationContext = '' }) {
|
|
1978
|
+
export function buildChildPrompt({ plan, subtask, stage, dependencyResults, cwd, conversationContext = '', statuses = null, previousFailure = null, }) {
|
|
1545
1979
|
/*
|
|
1546
1980
|
* Every field below is read defensively.
|
|
1547
1981
|
*
|
|
@@ -1557,11 +1991,28 @@ export function buildChildPrompt({ plan, subtask, stage, dependencyResults, cwd,
|
|
|
1557
1991
|
: results
|
|
1558
1992
|
.map((item) => `- ${item.id} ${item.title}:${item.status}${item.summary ? `|${item.summary}` : ''}`)
|
|
1559
1993
|
.join('\n');
|
|
1560
|
-
|
|
1994
|
+
/*
|
|
1995
|
+
* [1.7.0] No second truncation here.
|
|
1996
|
+
*
|
|
1997
|
+
* The background was cut to 5000 chars *after* the caller had already built
|
|
1998
|
+
* it to 7000, so a fresh conversation could lose its most recent turns. The
|
|
1999
|
+
* text now arrives already capped by `recentConversation`.
|
|
2000
|
+
*/
|
|
2001
|
+
const background = typeof conversationContext === 'string' ? conversationContext : '';
|
|
1561
2002
|
const understanding = plan?.taskUnderstanding ?? {};
|
|
1562
2003
|
const contradiction = plan?.contradictions?.primary?.statement ?? '(未记录)';
|
|
1563
2004
|
const stageName = stage?.name ?? '(未命名阶段)';
|
|
1564
2005
|
const stageGoal = stage?.goal ?? '(未记录目标)';
|
|
2006
|
+
const team = statuses ? buildTeamBrief(plan, statuses, subtask) : '';
|
|
2007
|
+
const failure = previousFailure && typeof previousFailure === 'object'
|
|
2008
|
+
? [
|
|
2009
|
+
'',
|
|
2010
|
+
'上一次尝试失败(这不是新的任务,请先判断上次为什么失败):',
|
|
2011
|
+
`- 失败类型:${previousFailure.code ?? 'UNKNOWN'}${previousFailure.attempt ? `(第 ${previousFailure.attempt} 次尝试)` : ''}`,
|
|
2012
|
+
`- 失败说明:${truncate(String(previousFailure.message ?? '(无说明)'), 600)}`,
|
|
2013
|
+
'请针对上面这个原因调整做法,不要重复相同的失败路径;如果仍然无法完成,第一行输出 `BLOCKED: 原因` 并说明缺少什么。',
|
|
2014
|
+
].join('\n')
|
|
2015
|
+
: '';
|
|
1565
2016
|
return [
|
|
1566
2017
|
`你是「${departmentLabel(subtask.department)}」部门的执行 Agent,只负责下面这一个子任务。`,
|
|
1567
2018
|
'',
|
|
@@ -1585,6 +2036,8 @@ export function buildChildPrompt({ plan, subtask, stage, dependencyResults, cwd,
|
|
|
1585
2036
|
'',
|
|
1586
2037
|
'依赖子任务的已知结果:',
|
|
1587
2038
|
dependencies,
|
|
2039
|
+
...(team ? ['', '兄弟部门进展(同一计划内的其他子任务;不要直接联系它们,需要协作请写进 needs 由主 Agent 转达):', team] : []),
|
|
2040
|
+
...(failure ? [failure] : []),
|
|
1588
2041
|
'',
|
|
1589
2042
|
'执行要求:',
|
|
1590
2043
|
'- 只完成本子任务,不擅自扩大范围;不要派生新的 Agent。',
|
|
@@ -1595,5 +2048,15 @@ export function buildChildPrompt({ plan, subtask, stage, dependencyResults, cwd,
|
|
|
1595
2048
|
'- 控制工具调用次数,证据足够就立即汇报;不要反复搜索或等待长时间任务。',
|
|
1596
2049
|
'- 如果确实无法完成,第一行输出 `BLOCKED: 原因`,然后简要说明。',
|
|
1597
2050
|
'- 完成后用简洁中文汇报:做了什么、证据/文件、验收结果、遗留问题。',
|
|
2051
|
+
'',
|
|
2052
|
+
'结果回传(必填):在汇报的最后附上一个结构化结果块,主 Agent 会按它逐项核对,不再只依赖自述。',
|
|
2053
|
+
EVIDENCE_MARKER_BEGIN,
|
|
2054
|
+
'{"status":"done","blockedReason":"","acceptance":[{"criterion":"把上面的验收标准原文抄在这里","result":"pass","evidence":"用命令输出、文件路径或引用证明"}],"artifacts":[{"kind":"file","ref":"相对工作目录的路径"}],"needs":[]}',
|
|
2055
|
+
EVIDENCE_MARKER_END,
|
|
2056
|
+
'- status 只能是 done / blocked / partial;partial 会被当作受阻处理。',
|
|
2057
|
+
'- acceptance 必须逐条覆盖上面的验收标准;result 只能是 pass / fail / unverified。无法确认就写 unverified,不要写 pass。',
|
|
2058
|
+
'- artifacts 写你实际产出或修改的文件(kind=file,ref 用相对路径)、链接(kind=url)或说明(kind=note)。',
|
|
2059
|
+
'- 需要其他部门配合时写进 needs(每条一句话),主 Agent 会转达;不要直连其他子 Agent。',
|
|
2060
|
+
'- 整块不超过 8000 字符;不要把这段模板本身抄进结果块。',
|
|
1598
2061
|
].join('\n');
|
|
1599
2062
|
}
|