@evomap/evolver-cli 2.0.33 → 2.0.34

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/dist/index.js CHANGED
@@ -4,10 +4,10 @@ import { runGeneValue } from './geneValue.js';
4
4
  import { assetstore, algo, signals, material as materialNs } from '@evomap/evolver-core';
5
5
  import { loadPriceTable } from '@evomap/evolver-adapter-public';
6
6
  import { loadEnvFileFromEnv } from '@evomap/evolver-mcp';
7
- import { makeInjectEmitter } from './autoexec.js';
7
+ import { injectEvent, makeInjectEmitter } from './autoexec.js';
8
8
  import { listApprovedGenes, pendingGeneReviewRecords, provenanceStoreForStore, reviewLedgerForStore } from './reviewFilter.js';
9
9
  import { ADAPTERS, parseJsonlLines } from '@evomap/evolver-runtime-adapters';
10
- import { draftGeneCandidate } from './distillPrimitives.js';
10
+ import { assessGeneDraft } from './distillPrimitives.js';
11
11
  import { assessDraftAdmissionFromStore } from './distillAdmission.js';
12
12
  import { isSyncCommandName, renderCommandGroups } from './commandCatalog.js';
13
13
  import { parseRuntimeSessionSourcesWithDiagnostics } from './runtimeSessionSource.js';
@@ -903,8 +903,10 @@ export async function runIngest(argv, store, deps = {}, review) {
903
903
  let candidateCount = 0;
904
904
  let admissionSkipped = 0;
905
905
  let lastAdmissionSkipReason = '';
906
- for (const { source, sigs } of sourceSignalPairs) {
907
- const candidate = draftGeneCandidate(source.turns, sigs, source.agent);
906
+ for (const [sourceIndex, { source, sigs }] of sourceSignalPairs.entries()) {
907
+ const { candidate, diagnostics } = assessGeneDraft(source.turns, sigs, source.agent);
908
+ // 只输出有界位置、计数和固定原因,不回显未脱敏的原文片段。
909
+ process.stdout.write(` distill strategy: ${JSON.stringify({ sourceIndex, ...diagnostics })}\n`);
908
910
  if (!candidate)
909
911
  continue;
910
912
  candidateCount += 1;
@@ -923,7 +925,7 @@ export async function runIngest(argv, store, deps = {}, review) {
923
925
  process.stderr.write(`\ningest --distill rejected: ${r.errors.join('; ')}\n`);
924
926
  return 1;
925
927
  }
926
- accepted.push({ source, candidate, gene: r.gene });
928
+ accepted.push({ source, candidate, gene: r.gene, strategyDraft: diagnostics, sourceIndex });
927
929
  acceptedSignals.push({ id: r.gene.id, signals_match: r.gene.signals_match });
928
930
  }
929
931
  if (accepted.length === 0) {
@@ -932,13 +934,13 @@ export async function runIngest(argv, store, deps = {}, review) {
932
934
  process.stdout.write(`\ningest: all ${candidateCount} draft candidate(s) skipped by admission gate.${reason} Nothing stored.\n`);
933
935
  return 0;
934
936
  }
935
- process.stdout.write('\ningest: not enough to distill — need ≥1 strong signal and ≥1 substantive assistant step. Nothing stored.\n');
937
+ process.stdout.write('\ningest: not enough to distill - need eligible signals and complete actionable units. Nothing stored.\n');
936
938
  return 0;
937
939
  }
938
940
  const reviewDir = s instanceof assetstore.LocalJsonlProvider ? s.baseDir : events.assetsDir();
939
941
  const rev = review ?? new assetstore.ReviewLedger(reviewDir);
940
942
  const { ingestor } = resolveIngestDeps(deps);
941
- for (const { source, candidate, gene } of accepted) {
943
+ for (const { source, candidate, gene, strategyDraft, sourceIndex } of accepted) {
942
944
  // Quarantine the draft: its auto-extracted strategy must not be embedded into a real autonomous run until a
943
945
  // human approves it (`evolver review --approve <id>`). The gate lives in makeTrustedGeneResolver (#45+review).
944
946
  // Co-locate the sidecar with the RESOLVED store so an injected store quarantines in its own dir (not the real
@@ -955,7 +957,7 @@ export async function runIngest(argv, store, deps = {}, review) {
955
957
  // AE (#91 item 1): auto-distill mints a quarantined draft — record it on the audit spine.
956
958
  await ingestor.ingest({
957
959
  type: 'gene.distilled',
958
- payload: { geneId: gene.id, assetId: gene.asset_id, category: gene.category, source: 'ingest', ...(source.sessionId ? { sessionId: source.sessionId } : {}) },
960
+ payload: { geneId: gene.id, assetId: gene.asset_id, category: gene.category, source: 'ingest', sourceIndex, strategyDraft, ...(source.sessionId ? { sessionId: source.sessionId } : {}) },
959
961
  human: { title: `distilled gene ${gene.id}`, severity: 'info' },
960
962
  actor: { kind: 'machine', id: 'ingest' },
961
963
  });
@@ -1458,6 +1460,89 @@ export function formatGeneInjectionLine(g) {
1458
1460
  const hint = summary || (Array.isArray(g['signals_match']) ? g['signals_match'].slice(0, 4).join(', ') : '');
1459
1461
  return `- ${id}${cat ? ` [${cat}]` : ''}${hint ? `: ${hint.slice(0, 160)}` : ''}`;
1460
1462
  }
1463
+ function sessionContentMode(argv) {
1464
+ let value = process.env['EVOLVER_SESSION_INJECT_CONTENT'] ?? 'summary';
1465
+ for (let index = 1; index < argv.length; index++) {
1466
+ const arg = argv[index];
1467
+ if (arg === '--content')
1468
+ value = argv[++index] ?? '';
1469
+ else if (arg.startsWith('--content='))
1470
+ value = arg.slice('--content='.length);
1471
+ }
1472
+ return value === 'summary' || value === 'strategy' ? value : undefined;
1473
+ }
1474
+ /** 整条策略作为预算原子单元;不在句中截断,也不把缺失策略当作已经送达。 */
1475
+ function renderSessionGene(g, mode, maxChars) {
1476
+ const summary = hubNs.redactString(formatGeneInjectionLine(g));
1477
+ const geneId = typeof g['id'] === 'string' ? g['id'] : String(g.asset_id);
1478
+ const base = { geneId, assetId: g.asset_id, mode: 'summary', strategySteps: 0 };
1479
+ const omitted = (omissionReason, detail) => ({
1480
+ text: `${summary}\n [策略未注入:${detail};以上仅为摘要]`,
1481
+ content: { ...base, omissionReason },
1482
+ });
1483
+ if (mode === 'summary')
1484
+ return { text: summary, content: { ...base, omissionReason: 'summary_mode' } };
1485
+ const raw = g['strategy'];
1486
+ if (raw === undefined || (Array.isArray(raw) && raw.length === 0))
1487
+ return omitted('empty_strategy', '没有可用步骤');
1488
+ if (!Array.isArray(raw))
1489
+ return omitted('invalid_strategy', '步骤格式无效');
1490
+ const steps = [];
1491
+ let size = summary.length + '\n strategy:'.length;
1492
+ for (const value of raw) {
1493
+ if (typeof value !== 'string' || !value.trim())
1494
+ return omitted('invalid_strategy', '步骤格式无效');
1495
+ // 先限制输入,再脱敏;超大的记录不进入正则处理或生成残缺命令。
1496
+ if (value.length > maxChars || size + value.length > maxChars)
1497
+ return omitted('budget', '超过本次预算');
1498
+ const prefix = ` ${steps.length + 1}. `;
1499
+ const step = `\n${prefix}${hubNs.redactString(value).replace(/\r?\n/g, '\n' + ' '.repeat(prefix.length))}`;
1500
+ size += step.length;
1501
+ if (size > maxChars)
1502
+ return omitted('budget', '超过本次预算');
1503
+ steps.push(step);
1504
+ }
1505
+ return {
1506
+ text: `${summary}\n strategy:${steps.join('')}`,
1507
+ content: { geneId, assetId: g.asset_id, mode: 'strategy', strategySteps: steps.length },
1508
+ };
1509
+ }
1510
+ /** 输出callback确认前不记录交付;调用者最多等待一秒,底层write仍可能迟到完成。 */
1511
+ function writeSessionPrompt(text) {
1512
+ const stdout = process.stdout;
1513
+ return new Promise((resolve, reject) => {
1514
+ let settled = false;
1515
+ const settle = (error) => {
1516
+ if (settled)
1517
+ return;
1518
+ settled = true;
1519
+ clearTimeout(timer);
1520
+ if (error)
1521
+ reject(new Error('session_prompt_write_unconfirmed'));
1522
+ else
1523
+ resolve();
1524
+ };
1525
+ const finish = (error) => {
1526
+ // 即使等待已超时,真正的write callback仍负责释放本次listener;不得迟到记账。
1527
+ // Node在失败callback之后发送error,等到下一轮再移除监听,避免EPIPE成为未处理异常。
1528
+ if (error)
1529
+ setImmediate(() => stdout.removeListener('error', onError));
1530
+ else
1531
+ stdout.removeListener('error', onError);
1532
+ settle(error);
1533
+ };
1534
+ const onError = (error) => settle(error);
1535
+ // deadline不是底层write的终点;once listener保留到实际error或callback,而非下一轮事件循环。
1536
+ const timer = setTimeout(() => settle(new Error('write_timeout')), 1_000);
1537
+ stdout.once('error', onError);
1538
+ try {
1539
+ stdout.write(text, finish);
1540
+ }
1541
+ catch {
1542
+ finish(new Error('write_failed'));
1543
+ }
1544
+ });
1545
+ }
1461
1546
  /** Read the SessionStart hook's stdin payload, bounded so it can NEVER hang the agent's critical path: skipped on a
1462
1547
  * TTY (a manual run), and capped by a short timeout so a runtime that leaves stdin open without sending EOF still
1463
1548
  * proceeds. Resolves to '' when nothing is available. Only called when the hook opts in (--hook-stdin). */
@@ -1541,9 +1626,14 @@ export async function runInject(argv, deps = {}) {
1541
1626
  });
1542
1627
  }
1543
1628
  if (sub !== 'session-start') {
1544
- process.stderr.write('用法: evolver inject session-start | evolver inject prompt-recall --hook-stdin\n');
1629
+ process.stderr.write('用法: evolver inject session-start [--content=summary|strategy] | evolver inject prompt-recall --hook-stdin\n');
1545
1630
  return sub === undefined ? 0 : 1;
1546
1631
  }
1632
+ const contentMode = sessionContentMode(argv);
1633
+ if (!contentMode) {
1634
+ process.stderr.write('inject session-start: content必须为summary或strategy;未执行注入。\n');
1635
+ return 1;
1636
+ }
1547
1637
  const fromHookStdin = argv.includes('--hook-stdin');
1548
1638
  if (fromHookStdin) {
1549
1639
  try {
@@ -1570,7 +1660,8 @@ export async function runInject(argv, deps = {}) {
1570
1660
  // compact hint lines. The provenance gate keeps untrusted hub assets out until promotion; the review gate (A2a)
1571
1661
  // keeps auto-distilled UNPROVEN drafts out until approval.
1572
1662
  const genes = await listApprovedGenes(store, review, maxGenes, provenance);
1573
- const geneLines = genes.map(formatGeneInjectionLine);
1663
+ const rendered = genes.map((g) => renderSessionGene(g, contentMode, hardCap * 4));
1664
+ const geneLines = rendered.map((gene) => gene.text);
1574
1665
  const geneIds = genes.map((g) => (typeof g['id'] === 'string' ? String(g['id']) : String(g.asset_id)));
1575
1666
  // Value recap (#113): same load path as `evolver value`, over the default recap window (7d).
1576
1667
  const now = deps.now ? deps.now() : Date.now();
@@ -1581,23 +1672,64 @@ export async function runInject(argv, deps = {}) {
1581
1672
  // Inject emission seam (#123): wire the ingestor so core's onInject lands a `value.inject` root_event. The
1582
1673
  // composition (Ingestor ↔ core's sink-agnostic seam) lives HERE in the CLI — core never imports the Ingestor.
1583
1674
  const emitter = makeInjectEmitter(ingestor);
1675
+ let injectedInfo;
1584
1676
  // Capture the runtime session id (#205) only when the installed hook opts in via --hook-stdin, or a test wires
1585
1677
  // readHookInput. Default (no flag, no seam) never touches stdin — so a plain `evolver inject session-start` and
1586
1678
  // the test suite can never block on a stdin read (the Windows CI hang this guards against).
1587
1679
  const sessionId = deps.sessionId ?? ((fromHookStdin || deps.readHookInput) ? await readHookSessionId(deps.readHookInput) : undefined);
1588
- const inj = hooks.composeSessionStartWithRecap({ tokenBudgetHardCap: hardCap, preamble: SESSION_START_PREAMBLE }, { injectGenes: geneLines, geneIds, successCount: summary.topGenes.length, summary }, {
1589
- ...(emitter ? { onInject: emitter.onInject } : {}),
1590
- ...(deps.cycleId ? { cycleId: deps.cycleId } : {}),
1591
- ...(sessionId ? { sessionId } : {}),
1592
- });
1593
- // Await durability (emit never rejects) so the value.inject event is on disk before we return without ever
1594
- // letting a sink error surface.
1595
- if (emitter)
1596
- await emitter.flush();
1680
+ const compose = (count) => {
1681
+ injectedInfo = undefined;
1682
+ return hooks.composeSessionStartWithRecap({ tokenBudgetHardCap: hardCap, preamble: SESSION_START_PREAMBLE }, { injectGenes: geneLines.slice(0, count), geneIds: geneIds.slice(0, count), successCount: summary.topGenes.length, summary }, {
1683
+ onInject: (info) => { injectedInfo = info; },
1684
+ ...(deps.cycleId ? { cycleId: deps.cycleId } : {}),
1685
+ ...(sessionId ? { sessionId } : {}),
1686
+ });
1687
+ };
1688
+ const recordFor = (count) => {
1689
+ const content = rendered.slice(0, count).map((gene) => gene.content);
1690
+ return { ...injectedInfo, geneIds: geneIds.slice(0, count), contentSchema: 'session-gene-content.v1', content,
1691
+ omittedByBudget: rendered.length - count + content.filter((gene) => gene.omissionReason === 'budget').length,
1692
+ };
1693
+ };
1694
+ let inj = compose(rendered.length);
1695
+ const tokenLimitedCount = inj.genes.length;
1696
+ let low = 0;
1697
+ let high = inj.genes.length;
1698
+ // Find the largest whole-gene prefix whose content receipts fit
1699
+ // the actual writer envelope, before any prompt bytes reach the runtime.
1700
+ while (low < high) {
1701
+ const count = Math.ceil((low + high) / 2);
1702
+ if (events.fitsRootEventLine(injectEvent(recordFor(count))))
1703
+ low = count;
1704
+ else
1705
+ high = count - 1;
1706
+ }
1707
+ if (low < inj.genes.length) {
1708
+ const omitted = inj.genes.length - low;
1709
+ inj = compose(low);
1710
+ process.stderr.write(`inject session-start: 本次注入记录超过大小上限,省略${omitted}条经验。\n`);
1711
+ }
1597
1712
  // Keep SessionStart quiet when there is no usable memory payload. When genes do land, the model still receives
1598
1713
  // them, but the preamble explicitly tells it not to narrate routine Evolver work to the user.
1599
- if (inj.genes.length > 0 && inj.systemPrompt.trim().length > 0)
1600
- process.stdout.write(inj.systemPrompt + '\n');
1714
+ if (inj.genes.length > 0 && inj.systemPrompt.trim().length > 0) {
1715
+ try {
1716
+ await writeSessionPrompt(inj.systemPrompt + '\n');
1717
+ }
1718
+ catch {
1719
+ process.stderr.write('inject session-start: 输出未确认完成,未记录策略交付。\n');
1720
+ return 1;
1721
+ }
1722
+ }
1723
+ const record = recordFor(inj.genes.length);
1724
+ const tokenOmitted = rendered.length - tokenLimitedCount + (record.content?.filter((gene) => gene.omissionReason === 'budget').length ?? 0);
1725
+ if (contentMode === 'strategy' && tokenOmitted > 0) {
1726
+ process.stderr.write(`inject session-start: ${tokenOmitted}条Gene的完整策略因token预算未注入。\n`);
1727
+ }
1728
+ // 仅在stdout callback确认成功后记账;事件不复制策略正文,也不声称runtime已经执行。
1729
+ if (injectedInfo && emitter) {
1730
+ emitter.onInject(record);
1731
+ await emitter.flush();
1732
+ }
1601
1733
  // Legacy v1 Windows scheduled-task sweep (#956): runs AFTER the injection is on stdout so a worst-case
1602
1734
  // sweep (probe 20s + lock wait 3s + 2×(export 20s + mutation 40s) ≈ 143s) can never push the injection
1603
1735
  // past the host SessionStart hook timeout and lose it — injection lands first, sweep is trailing.
@@ -69,9 +69,23 @@ function assertWindowsAclChecksTrusted(checks) {
69
69
  bootstrapWindowsAclTrustForTest(checks);
70
70
  return;
71
71
  }
72
- const serializedChecks = checks.map((check) => (`@{ Path = '${check.path.replaceAll("'", "''")}'; ParentOnly = $${check.parentOnly ? 'true' : 'false'}; OwnerCurrentOnly = $${check.ownerCurrentOnly ? 'true' : 'false'} }`)).join(', ');
72
+ if (checks.length === 0) {
73
+ throw new Error('bootstrap Windows ACL chain is not trusted: <empty>');
74
+ }
75
+ const encodedChecks = checks.map((check) => (`${Buffer.from(check.path, 'utf8').toString('base64')}|${check.parentOnly ? '1' : '0'}|${check.ownerCurrentOnly ? '1' : '0'}`)).join('\n');
76
+ if (encodedChecks.length > 24 * 1024) {
77
+ throw new Error(`bootstrap Windows ACL chain is not trusted: ${checks[0]?.path ?? '<empty>'}`);
78
+ }
73
79
  const script = [
74
- `$checks = @(${serializedChecks})`,
80
+ "$ErrorActionPreference = 'Stop'",
81
+ 'trap { exit 24 }',
82
+ '$checks = @()',
83
+ 'foreach ($row in $env:EVOLVER_BOOTSTRAP_ACL_CHECKS.Split([char]10, [System.StringSplitOptions]::RemoveEmptyEntries)) {',
84
+ " $parts = $row.Split('|')",
85
+ " if ($parts.Count -ne 3 -or ($parts[1] -ne '0' -and $parts[1] -ne '1') -or ($parts[2] -ne '0' -and $parts[2] -ne '1')) { exit 24 }",
86
+ ' try { $path = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($parts[0])) } catch { exit 24 }',
87
+ " $checks += [pscustomobject]@{ Path = $path; ParentOnly = ($parts[1] -eq '1'); OwnerCurrentOnly = ($parts[2] -eq '1') }",
88
+ '}',
75
89
  '$userSid = [System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value',
76
90
  "$trustedInstaller = 'S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464'",
77
91
  "$trustedOwners = @($userSid, 'S-1-5-18', 'S-1-5-32-544', $trustedInstaller)",
@@ -79,31 +93,115 @@ function assertWindowsAclChecksTrusted(checks) {
79
93
  '$parentDanger = [System.Security.AccessControl.FileSystemRights]::Delete -bor [System.Security.AccessControl.FileSystemRights]::DeleteSubdirectoriesAndFiles -bor [System.Security.AccessControl.FileSystemRights]::ChangePermissions -bor [System.Security.AccessControl.FileSystemRights]::TakeOwnership',
80
94
  '$contentDanger = [System.Security.AccessControl.FileSystemRights]::WriteData -bor [System.Security.AccessControl.FileSystemRights]::AppendData -bor [System.Security.AccessControl.FileSystemRights]::CreateFiles -bor [System.Security.AccessControl.FileSystemRights]::CreateDirectories',
81
95
  'foreach ($check in $checks) {',
82
- ' $acl = Get-Acl -LiteralPath $check.Path',
96
+ ' try { $attributes = [System.IO.File]::GetAttributes($check.Path) } catch { exit 24 }',
97
+ ' try {',
98
+ ' $acl = if (($attributes -band [System.IO.FileAttributes]::Directory) -ne 0) {',
99
+ ' [System.IO.Directory]::GetAccessControl($check.Path)',
100
+ ' } else {',
101
+ ' [System.IO.File]::GetAccessControl($check.Path)',
102
+ ' }',
103
+ ' } catch { exit 24 }',
83
104
  ' $owner = $acl.GetOwner([System.Security.Principal.SecurityIdentifier]).Value',
84
105
  ' if (($check.OwnerCurrentOnly -and $owner -ne $userSid) -or (-not $check.OwnerCurrentOnly -and $trustedOwners -notcontains $owner)) { exit 21 }',
85
106
  ' $danger = if ($check.ParentOnly) { $parentDanger } else { $parentDanger -bor $contentDanger }',
86
- ' foreach ($rule in @($acl.Access)) {',
107
+ ' $rules = @($acl.GetAccessRules($true, $true, [System.Security.Principal.SecurityIdentifier]))',
108
+ ' foreach ($rule in $rules) {',
87
109
  ' if ($rule.AccessControlType -ne [System.Security.AccessControl.AccessControlType]::Allow) { continue }',
88
110
  ' if (($rule.PropagationFlags -band [System.Security.AccessControl.PropagationFlags]::InheritOnly) -ne 0) { continue }',
89
111
  ' if (($rule.FileSystemRights -band $danger) -eq 0) { continue }',
90
- ' try { $sid = $rule.IdentityReference.Translate([System.Security.Principal.SecurityIdentifier]).Value } catch { exit 22 }',
112
+ ' if (-not ($rule.IdentityReference -is [System.Security.Principal.SecurityIdentifier])) { exit 22 }',
113
+ ' $sid = $rule.IdentityReference.Value',
91
114
  ' if ($trustedWriters -notcontains $sid) { exit 23 }',
92
115
  ' }',
93
116
  '}',
94
- ].join('; ');
117
+ ].join('\n');
95
118
  try {
96
119
  execFileSync(trustedWindowsSystemExecutable('WindowsPowerShell\\v1.0\\powershell.exe'), ['-NoProfile', '-NonInteractive', '-Command', script], {
120
+ env: {
121
+ SystemRoot: HOST_WINDOWS_SYSTEM_ROOT,
122
+ WINDIR: HOST_WINDOWS_SYSTEM_ROOT,
123
+ EVOLVER_BOOTSTRAP_ACL_CHECKS: encodedChecks,
124
+ },
125
+ shell: false,
97
126
  stdio: 'ignore', timeout: 10_000, windowsHide: true,
98
127
  });
99
128
  }
100
129
  catch (error) {
101
- throw new Error(`bootstrap Windows ACL chain is not trusted: ${checks[0]?.path ?? '<empty>'}`, { cause: error });
130
+ const status = typeof error === 'object' && error !== null
131
+ ? error.status
132
+ : undefined;
133
+ const reason = status === 21
134
+ ? 'owner_untrusted'
135
+ : status === 22
136
+ ? 'identity_unresolved'
137
+ : status === 23
138
+ ? 'writer_untrusted'
139
+ : status === 24
140
+ ? 'input_or_acl_read_failed'
141
+ : 'process_failed';
142
+ throw new Error(`bootstrap Windows ACL chain is not trusted (${reason}): ${checks[0]?.path ?? '<empty>'}`, { cause: error });
102
143
  }
103
144
  }
104
145
  function assertWindowsAclTrusted(path, ownerCurrentOnly = false) {
105
146
  assertWindowsAclChecksTrusted([{ path, parentOnly: false, ownerCurrentOnly }]);
106
147
  }
148
+ function hardenWindowsOwnedFile(path, expected) {
149
+ if (process.platform !== 'win32' || bootstrapWindowsAclTrustForTest)
150
+ return;
151
+ const assertIdentity = () => {
152
+ const current = lstatSync(path, { bigint: true });
153
+ if (!current.isFile() || current.isSymbolicLink() || current.nlink !== 1n
154
+ || current.dev !== expected.dev || current.ino !== expected.ino || current.size !== expected.size) {
155
+ throw new Error(`bootstrap Windows owned file changed before hardening: ${path}`);
156
+ }
157
+ };
158
+ assertIdentity();
159
+ // Only normalize a file we just created in a trusted directory. An unsafe
160
+ // existing owner or writer must be rejected before changing its permissions.
161
+ assertWindowsAclTrusted(path);
162
+ assertIdentity();
163
+ const encodedPath = Buffer.from(path, 'utf8').toString('base64');
164
+ if (encodedPath.length > 8 * 1024) {
165
+ throw new Error(`bootstrap Windows owned file hardening failed: ${path}`);
166
+ }
167
+ const script = [
168
+ "$ErrorActionPreference = 'Stop'",
169
+ 'trap { exit 31 }',
170
+ 'try { $target = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($env:EVOLVER_BOOTSTRAP_OWNED_FILE)) } catch { exit 31 }',
171
+ 'try { $attributes = [System.IO.File]::GetAttributes($target) } catch { exit 31 }',
172
+ 'if (($attributes -band [System.IO.FileAttributes]::Directory) -ne 0 -or ($attributes -band [System.IO.FileAttributes]::ReparsePoint) -ne 0) { exit 31 }',
173
+ '$sid = [System.Security.Principal.WindowsIdentity]::GetCurrent().User',
174
+ 'try { $acl = [System.IO.File]::GetAccessControl($target) } catch { exit 31 }',
175
+ '$acl.SetOwner($sid)',
176
+ '$acl.SetAccessRuleProtection($true, $false)',
177
+ '$rules = @($acl.GetAccessRules($true, $true, [System.Security.Principal.SecurityIdentifier]))',
178
+ 'foreach ($rule in $rules) { [void]$acl.RemoveAccessRuleSpecific($rule) }',
179
+ '$access = [System.Security.AccessControl.FileSystemAccessRule]::new($sid, [System.Security.AccessControl.FileSystemRights]::FullControl, [System.Security.AccessControl.AccessControlType]::Allow)',
180
+ '[void]$acl.AddAccessRule($access)',
181
+ 'try { [System.IO.File]::SetAccessControl($target, $acl); $verified = [System.IO.File]::GetAccessControl($target) } catch { exit 31 }',
182
+ '$verifiedRules = @($verified.GetAccessRules($true, $true, [System.Security.Principal.SecurityIdentifier]))',
183
+ 'if (-not $verified.AreAccessRulesProtected -or $verified.GetOwner([System.Security.Principal.SecurityIdentifier]).Value -ne $sid.Value -or $verifiedRules.Count -ne 1) { exit 31 }',
184
+ '$verifiedRule = $verifiedRules[0]',
185
+ 'if ($verifiedRule.IdentityReference.Value -ne $sid.Value -or $verifiedRule.AccessControlType -ne [System.Security.AccessControl.AccessControlType]::Allow -or $verifiedRule.FileSystemRights -ne [System.Security.AccessControl.FileSystemRights]::FullControl -or $verifiedRule.IsInherited) { exit 31 }',
186
+ ].join('\n');
187
+ try {
188
+ execFileSync(trustedWindowsSystemExecutable('WindowsPowerShell\\v1.0\\powershell.exe'), ['-NoProfile', '-NonInteractive', '-Command', script], {
189
+ env: {
190
+ SystemRoot: HOST_WINDOWS_SYSTEM_ROOT,
191
+ WINDIR: HOST_WINDOWS_SYSTEM_ROOT,
192
+ EVOLVER_BOOTSTRAP_OWNED_FILE: encodedPath,
193
+ },
194
+ shell: false,
195
+ stdio: 'ignore',
196
+ timeout: 10_000,
197
+ windowsHide: true,
198
+ });
199
+ }
200
+ catch (error) {
201
+ throw new Error(`bootstrap Windows owned file hardening failed: ${path}`, { cause: error });
202
+ }
203
+ assertIdentity();
204
+ }
107
205
  function assertWindowsAclChainTrusted(path) {
108
206
  const checks = [];
109
207
  let current = resolve(path);
@@ -280,6 +378,9 @@ export function writeDurableText(path, content, mode = 0o600) {
280
378
  writeFileSync(descriptor, content, { encoding: 'utf8' });
281
379
  fchmodSync(descriptor, mode);
282
380
  fsyncSync(descriptor);
381
+ if (process.platform === 'win32') {
382
+ hardenWindowsOwnedFile(temporary, fstatSync(descriptor, { bigint: true }));
383
+ }
283
384
  closeSync(descriptor);
284
385
  descriptor = undefined;
285
386
  renameSync(temporary, path);
@@ -335,9 +436,12 @@ function writeDurableExclusive(path, content, mode, publication) {
335
436
  writeFileSync(descriptor, content);
336
437
  fchmodSync(descriptor, mode);
337
438
  fsyncSync(descriptor);
439
+ const opened = fstatSync(descriptor, { bigint: true });
440
+ if (process.platform === 'win32') {
441
+ hardenWindowsOwnedFile(temporary, opened);
442
+ }
338
443
  if (publication && claimPath && ownershipReceipt) {
339
444
  syncDirectory(directory);
340
- const opened = fstatSync(descriptor, { bigint: true });
341
445
  const receipt = lstatSync(ownershipReceipt, { bigint: true });
342
446
  if (!opened.isFile() || opened.dev <= 0n || opened.ino <= 0n
343
447
  || receipt.dev !== opened.dev || receipt.ino !== opened.ino) {
@@ -429,6 +533,17 @@ function bootstrapLockHandle(path, owner) {
429
533
  })}\n`, 'utf8');
430
534
  let receipt;
431
535
  try {
536
+ if (process.platform === 'win32') {
537
+ const published = readBootstrapArtifactFile(path, util.MAX_LOCK_OWNER_BYTES);
538
+ if (!published.bytes.equals(expectedBytes)) {
539
+ throw new Error('bootstrap owner lock acquisition did not publish the exact owner');
540
+ }
541
+ hardenWindowsOwnedFile(path, {
542
+ dev: BigInt(published.identity.device),
543
+ ino: BigInt(published.identity.inode),
544
+ size: BigInt(published.identity.size),
545
+ });
546
+ }
432
547
  receipt = readBootstrapArtifactFile(path, util.MAX_LOCK_OWNER_BYTES, { role: 'owned' });
433
548
  if (!receipt.bytes.equals(expectedBytes)) {
434
549
  throw new Error('bootstrap owner lock acquisition did not publish the exact owner');
@@ -1,4 +1,5 @@
1
1
  import { assetstore, events, material as materialNs, schema } from '@evomap/evolver-core';
2
+ import { type StrategyDraftDiagnostics } from './distillPrimitives.js';
2
3
  declare const GROUP = "material.package_gene";
3
4
  type PackageBlocker = 'usage' | 'material_not_found' | 'unsupported_material' | 'source_unavailable' | 'draft_unavailable' | 'gene_intake_rejected' | 'missing_capsule_evidence' | 'gene_not_found' | 'capsule_not_found' | 'capsule_gene_mismatch' | 'publish_bundle_invalid' | 'publish_bundle_blocked' | 'cycle_not_solidified' | 'write_failed';
4
5
  interface MaterialPackageOptions {
@@ -41,6 +42,9 @@ interface MaterialGenePackageResult {
41
42
  publishCommand?: string;
42
43
  sourceCount?: number;
43
44
  signalCount?: number;
45
+ strategyDraft?: StrategyDraftDiagnostics & {
46
+ sourceIndex: number;
47
+ };
44
48
  message?: string;
45
49
  }
46
50
  type MaterialGenePackageBuildResult = {
@@ -1,7 +1,7 @@
1
1
  import { readFileSync } from 'node:fs';
2
2
  import { assetstore, algo, events, hub, material as materialNs, schema, signals } from '@evomap/evolver-core';
3
3
  import { runtimeSessionSourcesForMaterial, runtimeSessionSourcesFromMaterialPayload } from './materialSnapshot.js';
4
- import { draftGeneCandidate } from './distillPrimitives.js';
4
+ import { assessGeneDraft } from './distillPrimitives.js';
5
5
  import { assessDraftAdmissionFromStore } from './distillAdmission.js';
6
6
  import { reviewLedgerForStore } from './reviewFilter.js';
7
7
  import { buildPublishBundle } from './cliContracts.js';
@@ -169,12 +169,26 @@ async function draftGeneFromMaterial(material, store, readSource) {
169
169
  let signalCount = 0;
170
170
  let sawCandidate = false;
171
171
  let lastIntakeError = '';
172
- for (const source of sources) {
172
+ let strategyDraft;
173
+ let lastCandidateStrategyDraft;
174
+ let mostSpecificNoCandidate;
175
+ let noCandidateSpecificity = -1;
176
+ for (const [sourceIndex, source] of sources.entries()) {
173
177
  const sigs = signals.extractSignals(source.turns);
174
178
  signalCount += sigs.length;
175
- const candidate = draftGeneCandidate(source.turns, sigs, source.agent);
176
- if (!candidate)
179
+ const { candidate, diagnostics } = assessGeneDraft(source.turns, sigs, source.agent);
180
+ strategyDraft = { ...diagnostics, sourceIndex };
181
+ if (!candidate) {
182
+ // 实际单元拒绝比已有操作证据更具体,两者均优于空巡视;同级仍使用最后source。
183
+ const specificity = diagnostics.rejected.length > 0 ? 2 : diagnostics.evidence.length > 0 ? 1 : 0;
184
+ if (specificity >= noCandidateSpecificity) {
185
+ mostSpecificNoCandidate = strategyDraft;
186
+ noCandidateSpecificity = specificity;
187
+ }
177
188
  continue;
189
+ }
190
+ // 候选拒绝与无候选分别保留来源;后续空 source 不得覆盖 lastIntakeError 对应的诊断。
191
+ lastCandidateStrategyDraft = strategyDraft;
178
192
  sawCandidate = true;
179
193
  const normalized = algo.intakeGene(candidate, []);
180
194
  if (!normalized.ok || !normalized.gene) {
@@ -183,7 +197,7 @@ async function draftGeneFromMaterial(material, store, readSource) {
183
197
  }
184
198
  const alreadyStored = await store.get(normalized.gene.asset_id);
185
199
  if (alreadyStored?.type === 'Gene') {
186
- return { gene: alreadyStored, sourceCount: sources.length, signalCount, stored: true };
200
+ return { gene: alreadyStored, sourceCount: sources.length, signalCount, stored: true, strategyDraft };
187
201
  }
188
202
  const { admission, existing } = await assessDraftAdmissionFromStore(store, candidate);
189
203
  if (!admission.admit) {
@@ -195,7 +209,7 @@ async function draftGeneFromMaterial(material, store, readSource) {
195
209
  lastIntakeError = intake.errors.join('; ') || 'gene intake rejected the candidate';
196
210
  continue;
197
211
  }
198
- return { gene: intake.gene, sourceCount: sources.length, signalCount, stored: false };
212
+ return { gene: intake.gene, sourceCount: sources.length, signalCount, stored: false, strategyDraft };
199
213
  }
200
214
  if (sawCandidate) {
201
215
  return {
@@ -203,9 +217,11 @@ async function draftGeneFromMaterial(material, store, readSource) {
203
217
  message: lastIntakeError || 'gene intake rejected every candidate',
204
218
  sourceCount: sources.length,
205
219
  signalCount,
220
+ ...(lastCandidateStrategyDraft ? { strategyDraft: lastCandidateStrategyDraft } : {}),
206
221
  };
207
222
  }
208
- return { blocker: 'draft_unavailable', message: 'material does not contain enough strong signals and strategy turns', sourceCount: sources.length, signalCount };
223
+ return { blocker: 'draft_unavailable', message: `material draft unavailable: ${mostSpecificNoCandidate?.reason ?? 'no_actionable_units'}`, sourceCount: sources.length, signalCount,
224
+ ...(mostSpecificNoCandidate ? { strategyDraft: mostSpecificNoCandidate } : {}) };
209
225
  }
210
226
  async function alreadyAudited(ingestor, assetId) {
211
227
  return ingestor.readAll().some((event) => {
@@ -215,7 +231,7 @@ async function alreadyAudited(ingestor, assetId) {
215
231
  return payload?.['assetId'] === assetId;
216
232
  });
217
233
  }
218
- async function writeDraftGene(gene, material, store, review, ingestor) {
234
+ async function writeDraftGene(gene, material, store, review, ingestor, strategyDraft) {
219
235
  const assetId = String(gene.asset_id);
220
236
  const existing = await store.get(assetId);
221
237
  if (existing?.type === 'Gene') {
@@ -230,6 +246,7 @@ async function writeDraftGene(gene, material, store, review, ingestor) {
230
246
  category: gene['category'],
231
247
  source: 'material-package',
232
248
  materialId: material.materialId,
249
+ ...(strategyDraft ? { strategyDraft } : {}),
233
250
  },
234
251
  human: { title: `material-packaged gene ${String(gene['id'] ?? assetId)} (UNPROVEN - awaiting review)`, severity: 'info' },
235
252
  actor: { kind: 'machine', id: 'material-package' },
@@ -319,6 +336,7 @@ export async function buildMaterialGenePackage(opts, deps = {}) {
319
336
  message: draft.message,
320
337
  ...(draft.sourceCount !== undefined ? { sourceCount: draft.sourceCount } : {}),
321
338
  ...(draft.signalCount !== undefined ? { signalCount: draft.signalCount } : {}),
339
+ ...(draft.strategyDraft ? { strategyDraft: draft.strategyDraft } : {}),
322
340
  },
323
341
  };
324
342
  }
@@ -326,7 +344,7 @@ export async function buildMaterialGenePackage(opts, deps = {}) {
326
344
  let written;
327
345
  if (opts.write) {
328
346
  try {
329
- const write = await writeDraftGene(gene, material, store, review, ingestor);
347
+ const write = await writeDraftGene(gene, material, store, review, ingestor, draft.strategyDraft);
330
348
  gene = write.gene;
331
349
  written = write.written;
332
350
  }
@@ -344,6 +362,7 @@ export async function buildMaterialGenePackage(opts, deps = {}) {
344
362
  blockers: ['missing_capsule_evidence'],
345
363
  sourceCount: draft.sourceCount,
346
364
  signalCount: draft.signalCount,
365
+ ...(draft.strategyDraft ? { strategyDraft: draft.strategyDraft } : {}),
347
366
  message: 'Gene draft is available, but publish requires terminal Capsule evidence from cycle',
348
367
  },
349
368
  };
@@ -366,6 +385,8 @@ function emitResult(result, json, stdout) {
366
385
  }
367
386
  if (result.publishCommand)
368
387
  stdout(` publish: ${result.publishCommand}`);
388
+ if (result.strategyDraft)
389
+ stdout(` distill strategy: ${JSON.stringify(result.strategyDraft)}`);
369
390
  if (result.message)
370
391
  stdout(` note: ${result.message}`);
371
392
  }
@@ -8,6 +8,7 @@ interface SnapshotTurn {
8
8
  isMeta?: boolean;
9
9
  toolName?: string;
10
10
  errorMessage?: string;
11
+ textTruncated?: boolean;
11
12
  }
12
13
  interface SnapshotSource {
13
14
  agent: string;
@@ -28,6 +29,8 @@ export interface RuntimeSessionMaterialSnapshotV1 {
28
29
  omittedSourceCount: number;
29
30
  omittedEvidenceAggregate?: RuntimeSessionEvidenceAggregate;
30
31
  truncated: boolean;
32
+ /** 新 writer 保留文本布局并逐 turn 标注截断;旧 v1 缺少该字段。 */
33
+ preservesTextLayout?: boolean;
31
34
  maxChars: number;
32
35
  }
33
36
  export interface RuntimeSessionEvidenceSummarySource {