@fitlab-ai/agent-infra 0.12.0 → 0.12.1

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.
Files changed (46) hide show
  1. package/dist/lib/internal/manual-validation.js +11 -17
  2. package/dist/lib/internal/platform-comment.js +56 -7
  3. package/dist/lib/platform/issue-comments.js +373 -267
  4. package/dist/lib/platform/issue-summary-content.js +112 -0
  5. package/dist/lib/platform/pr-change-report.js +175 -26
  6. package/dist/lib/platform/pr-summary-content.js +54 -0
  7. package/dist/lib/platform/pr-summary.js +318 -284
  8. package/dist/lib/platform/summary-content-pipeline.js +18 -0
  9. package/dist/lib/sandbox/removal.js +59 -2
  10. package/dist/lib/task/finalization.js +16 -7
  11. package/dist/lib/task/platform-operation-recovery.js +87 -87
  12. package/dist/lifecycle-build-manifest.json +3 -3
  13. package/lib/internal/manual-validation.ts +12 -18
  14. package/lib/internal/platform-comment.ts +46 -4
  15. package/lib/platform/issue-comments.ts +478 -280
  16. package/lib/platform/issue-summary-content.ts +132 -0
  17. package/lib/platform/pr-change-report.ts +165 -20
  18. package/lib/platform/pr-summary-content.ts +60 -0
  19. package/lib/platform/pr-summary.ts +364 -257
  20. package/lib/platform/summary-content-pipeline.ts +23 -0
  21. package/lib/sandbox/removal.ts +57 -1
  22. package/lib/task/finalization.ts +11 -6
  23. package/lib/task/platform-operation-recovery.ts +70 -81
  24. package/package.json +1 -1
  25. package/templates/.agents/rules/pr-sync.en.md +4 -2
  26. package/templates/.agents/rules/pr-sync.zh-CN.md +6 -9
  27. package/templates/.agents/skills/cancel-task/SKILL.en.md +1 -1
  28. package/templates/.agents/skills/cancel-task/SKILL.zh-CN.md +1 -1
  29. package/templates/.agents/skills/commit/reference/pr-summary-sync.en.md +1 -1
  30. package/templates/.agents/skills/commit/reference/pr-summary-sync.zh-CN.md +1 -1
  31. package/templates/.agents/skills/complete-manual-validation/reference/summary-update.en.md +2 -2
  32. package/templates/.agents/skills/complete-manual-validation/reference/summary-update.zh-CN.md +2 -2
  33. package/templates/.agents/skills/complete-task/SKILL.en.md +10 -25
  34. package/templates/.agents/skills/complete-task/SKILL.zh-CN.md +11 -26
  35. package/templates/.agents/skills/create-pr/SKILL.en.md +1 -1
  36. package/templates/.agents/skills/create-pr/SKILL.zh-CN.md +1 -1
  37. package/templates/.agents/skills/create-pr/reference/change-report.en.md +9 -2
  38. package/templates/.agents/skills/create-pr/reference/change-report.zh-CN.md +9 -2
  39. package/templates/.agents/skills/create-pr/reference/comment-publish.en.md +2 -2
  40. package/templates/.agents/skills/create-pr/reference/comment-publish.zh-CN.md +2 -2
  41. package/templates/.agents/skills/create-task/SKILL.en.md +0 -18
  42. package/templates/.agents/skills/create-task/SKILL.zh-CN.md +0 -18
  43. package/templates/.agents/skills/watch-pr/SKILL.en.md +1 -1
  44. package/templates/.agents/skills/watch-pr/SKILL.zh-CN.md +1 -1
  45. package/templates/.agents/skills/watch-pr/reference/monitor-and-heal.en.md +3 -3
  46. package/templates/.agents/skills/watch-pr/reference/monitor-and-heal.zh-CN.md +3 -3
@@ -16,6 +16,16 @@ import { canonicalizeCommentBody, escapeHtmlText, fenceRanges, renderSafeCodeFen
16
16
  function isRetryable(error) {
17
17
  return error.retryable ?? providerErrorRetryable(error.code);
18
18
  }
19
+ async function syncCommentPlan(strategy, operation, queuedOperation) {
20
+ const execute = () => executeCommentPlan(strategy, strategy.client);
21
+ if (strategy.dryRun)
22
+ return execute();
23
+ if (queuedOperation)
24
+ return execute();
25
+ return coordinatePlatformWrite({ operation, agent: strategy.agent, client: strategy.client, execute,
26
+ block: (error) => platformResult('blocked', { error }),
27
+ persistenceFailure: (error) => platformResult('failed', { error }) });
28
+ }
19
29
  function providerCommentId(id, provider) {
20
30
  return provider.identity?.comment === 'number' && /^\d+$/.test(id) ? Number(id) : id;
21
31
  }
@@ -378,38 +388,285 @@ function relatedComments(comments, prefix) {
378
388
  return first === base || (first.startsWith(chunkNamespace) && first.endsWith(' -->'));
379
389
  });
380
390
  }
381
- function taskManagedComment(comment, taskId) {
382
- const marker = normalizeCommentContent(comment.body).split('\n', 1)[0] || '';
383
- return marker === MARKERS.task(taskId)
384
- || marker === MARKERS.summary(taskId)
385
- || marker.startsWith(`<!-- sync-issue:${taskId}:`);
386
- }
387
- function summaryPosition(comments, taskId) {
388
- const managed = comments.filter((comment) => taskManagedComment(comment, taskId));
389
- const summary = managed.filter((comment) => normalizeCommentContent(comment.body).split('\n', 1)[0] === MARKERS.summary(taskId));
390
- if (summary.length !== 1)
391
- return { ok: false, known: false, summary: null };
392
- if (managed.some((comment) => !Number.isSafeInteger(comment.createdSequence) || Number(comment.createdSequence) < 1)) {
393
- return { ok: false, known: false, summary: summary[0] };
394
- }
395
- const sequence = summary[0].createdSequence;
396
- return { ok: managed.every((comment) => sequence >= comment.createdSequence), known: true, summary: summary[0] };
397
- }
398
391
  async function listedComments(provider, loaded, parent) {
399
392
  return provider.comments?.list
400
393
  ? provider.comments.list({ context: providerOperationContext(loaded), parent }).then((response) => response.ok
401
- ? {
402
- ok: true,
403
- value: response.value.map((comment) => ({
404
- id: providerCommentId(comment.id, provider),
405
- body: comment.body,
406
- user: comment.author?.name ? { login: comment.author.name } : undefined,
407
- createdSequence: comment.createdSequence
408
- }))
409
- }
410
- : response)
394
+ ? { ok: true, value: response.value.map((comment) => parentComment(comment, provider)) }
395
+ : { ...response, error: { ...response.error, retryable: isRetryable(response.error) } })
411
396
  : unsupportedProviderOperation(provider, 'comments.list');
412
397
  }
398
+ function markerSetError(strategy, context, resource, existing) {
399
+ if (validateRelatedMarkerSet(existing, strategy.markerPrefix).ok)
400
+ return null;
401
+ return platformResult('failed', { ...contextFields(context), resource, error: {
402
+ code: strategy.parentKind === 'pull-request' ? 'PR_SUMMARY_MARKER_AMBIGUOUS' : 'COMMENT_MARKER_CONFLICT',
403
+ message: strategy.parentKind === 'pull-request' ? 'Multiple PR comments contain the summary marker' : 'Multiple comments use the same registered marker', retryable: false
404
+ } });
405
+ }
406
+ function taskCommentOwnerError(strategy, context, resource, existing) {
407
+ if (strategy.kind !== 'task' || existing.length !== 1)
408
+ return null;
409
+ const owner = existing[0].user?.login;
410
+ return owner && context.platform.currentUser && owner === context.platform.currentUser ? null : platformResult('blocked', {
411
+ ...contextFields(context), resource, error: {
412
+ code: 'COMMENT_OWNER_CONFLICT', message: owner ? `Task comment is owned by '${owner}'` : 'Task comment owner is unavailable', retryable: false
413
+ }
414
+ });
415
+ }
416
+ async function strategyValidationError(strategy, context, resource) {
417
+ const error = strategy.validate ? await strategy.validate() : null;
418
+ if (!error)
419
+ return null;
420
+ return platformResult(error.retryable ? 'blocked' : 'failed', { ...contextFields(context), resource, error });
421
+ }
422
+ function artifactBackfillResult(strategy, context, resource, existing, desired) {
423
+ if (!strategy.backfill || strategy.kind !== 'artifact' || existing.length === 0)
424
+ return null;
425
+ const operations = existing.map((comment) => ({
426
+ name: `comment:${normalizeCommentContent(comment.body).split('\n', 1)[0]}`,
427
+ status: 'no-op',
428
+ reasonCode: 'BACKFILL_ALREADY_PRESENT'
429
+ }));
430
+ return platformResult('no-op', {
431
+ ...contextFields(context),
432
+ resource,
433
+ operations,
434
+ comment: {
435
+ kind: strategy.kind,
436
+ marker: desired[0]?.marker ?? strategy.markerPrefix,
437
+ ids: existing.map((item) => item.id),
438
+ parts: existing.length
439
+ },
440
+ error: null
441
+ });
442
+ }
443
+ function repositionAuthorizationError(strategy, context, resource, comments, byMarker, desired) {
444
+ const marker = desired[0]?.marker;
445
+ const current = marker ? byMarker.get(marker) : undefined;
446
+ const position = strategy.summaryPosition && current
447
+ ? issueSummaryPosition(strategy.taskId, comments, marker)
448
+ : true;
449
+ if (position === null)
450
+ return {
451
+ error: platformResult('blocked', { ...contextFields(context), resource, error: {
452
+ code: 'SUMMARY_POSITION_UNVERIFIED', message: 'Summary comment ordering cannot be proven from the provider snapshot', retryable: true
453
+ } }),
454
+ reposition: false
455
+ };
456
+ const reposition = Boolean(strategy.summaryPosition && current && !position);
457
+ if (!reposition || !current)
458
+ return { error: null, reposition: false };
459
+ const error = strategy.authorizeReposition
460
+ ? strategy.authorizeReposition(current, context.platform.currentUser ?? null)
461
+ : { code: 'SUMMARY_REPOSITION_UNAUTHORIZED', message: 'summary reposition requires current authorization and an owned summary comment', retryable: false };
462
+ return {
463
+ error: error ? platformResult(error.retryable ? 'blocked' : 'failed', { ...contextFields(context), resource, error }) : null,
464
+ reposition: true
465
+ };
466
+ }
467
+ async function inspectCommentPlan(strategy, context, resource, comments, desired) {
468
+ const existing = relatedComments(comments, strategy.markerPrefix);
469
+ const markerError = markerSetError(strategy, context, resource, existing);
470
+ if (markerError)
471
+ return { ok: false, result: markerError };
472
+ const ownerError = taskCommentOwnerError(strategy, context, resource, existing);
473
+ if (ownerError)
474
+ return { ok: false, result: ownerError };
475
+ const validationError = await strategyValidationError(strategy, context, resource);
476
+ if (validationError)
477
+ return { ok: false, result: validationError };
478
+ const backfill = artifactBackfillResult(strategy, context, resource, existing, desired);
479
+ if (backfill)
480
+ return { ok: true, value: { existing, byMarker: new Map(), reposition: false }, result: backfill };
481
+ const byMarker = new Map(existing.map((comment) => [normalizeCommentContent(comment.body).split('\n', 1)[0], comment]));
482
+ const reposition = repositionAuthorizationError(strategy, context, resource, comments, byMarker, desired);
483
+ if (reposition.error)
484
+ return { ok: false, result: reposition.error };
485
+ return { ok: true, value: { existing, byMarker, reposition: reposition.reposition } };
486
+ }
487
+ async function repositionSummaryComment(strategy, loaded, context, parent, resource, current, operations) {
488
+ if (!current)
489
+ return null;
490
+ const deleted = loaded.provider.comments?.delete
491
+ ? await loaded.provider.comments.delete({ context: providerOperationContext(loaded), parent,
492
+ comment: providerResourceToken(loaded.provider, 'comment', String(current.id)),
493
+ mutation: { idempotencyKey: `comment-reposition-delete:${strategy.taskId}:${current.id}` } })
494
+ : unsupportedProviderOperation(loaded.provider, 'comments.delete');
495
+ if (!deleted.ok)
496
+ return platformResult(isRetryable(deleted.error) ? 'blocked' : 'failed', {
497
+ ...contextFields(context), resource, error: deleted.error
498
+ });
499
+ operations.push({
500
+ name: `comment:${current.id}`,
501
+ status: 'applied',
502
+ reasonCode: 'SUMMARY_REPOSITIONED'
503
+ });
504
+ return null;
505
+ }
506
+ async function observeCommentWrite(strategy, loaded, parent, item) {
507
+ const after = await listedComments(loaded.provider, loaded, parent);
508
+ const comments = after.ok ? after.value : [];
509
+ const found = comments.filter((comment) => normalizeCommentContent(comment.body).split('\n', 1)[0] === item.marker);
510
+ const positionOk = !strategy.summaryPosition || issueSummaryPosition(strategy.taskId, comments, item.marker) === true;
511
+ const validation = strategy.validate ? await strategy.validate() : null;
512
+ if (after.ok
513
+ && found.length === 1
514
+ && normalizeCommentContent(found[0].body) === normalizeCommentContent(item.body)
515
+ && positionOk
516
+ && !validation)
517
+ return { valid: true };
518
+ const error = validation ?? {
519
+ code: strategy.kind === 'summary' || strategy.kind === 'cancel' ? 'SUMMARY_BODY_READBACK_FAILED' : 'COMMENT_READBACK_FAILED',
520
+ message: after.ok ? 'Remote comment did not match the requested body' : after.error.message,
521
+ retryable: after.ok || isRetryable(after.error)
522
+ };
523
+ return { valid: false, error };
524
+ }
525
+ async function verifyIssueSummaryReadback(strategy, loaded, context, parent, resource, desired, operations) {
526
+ if (strategy.parentKind !== 'issue' || (strategy.kind !== 'summary' && strategy.kind !== 'cancel'))
527
+ return null;
528
+ const after = await listedComments(loaded.provider, loaded, parent);
529
+ if (!after.ok)
530
+ return platformResult(isRetryable(after.error) ? 'blocked' : 'failed', {
531
+ ...contextFields(context), resource, operations, error: after.error
532
+ });
533
+ const item = desired[0];
534
+ const matching = item
535
+ ? after.value.filter((comment) => normalizeCommentContent(comment.body).split('\n', 1)[0] === item.marker)
536
+ : [];
537
+ if (!item || matching.length !== 1 || normalizeCommentContent(matching[0].body) !== normalizeCommentContent(item.body)) {
538
+ return platformResult('blocked', { ...contextFields(context), resource, operations, error: {
539
+ code: 'SUMMARY_BODY_READBACK_FAILED',
540
+ message: strategy.kind === 'cancel' ? 'Remote cancellation body did not match the rendered cancellation summary' : 'Remote summary body did not match the rendered delivery summary',
541
+ retryable: true
542
+ } });
543
+ }
544
+ if (strategy.summaryPosition && issueSummaryPosition(strategy.taskId, after.value, item.marker) !== true) {
545
+ return platformResult('blocked', { ...contextFields(context), resource, operations, error: {
546
+ code: 'SUMMARY_POSITION_UNVERIFIED', message: 'Summary comment is not provably last among task-managed comments', retryable: true
547
+ } });
548
+ }
549
+ return null;
550
+ }
551
+ async function compensatePullRequestComment(strategy, loaded, parent, current, id, cause) {
552
+ const compensation = current
553
+ ? await loaded.provider.comments?.write?.({ context: providerOperationContext(loaded), parent, body: current.body,
554
+ existingComment: providerResourceToken(loaded.provider, 'comment', String(current.id)),
555
+ mutation: { idempotencyKey: `pr-summary-restore:${strategy.taskId}` } })
556
+ : await loaded.provider.comments?.delete?.({ context: providerOperationContext(loaded), parent,
557
+ comment: providerResourceToken(loaded.provider, 'comment', String(id)),
558
+ mutation: { idempotencyKey: `pr-summary-delete:${strategy.taskId}:${id}` } });
559
+ if (!compensation?.ok)
560
+ return {
561
+ code: 'PR_SUMMARY_RACE_COMPENSATION_FAILED',
562
+ message: compensation?.error?.message ?? 'Provider does not support comment compensation',
563
+ retryable: true
564
+ };
565
+ if (cause?.code === 'PR_SUMMARY_HEAD_RACE')
566
+ return cause;
567
+ return {
568
+ code: 'PR_SUMMARY_POSTWRITE_VERIFY_FAILED',
569
+ message: cause?.message ?? 'Post-write summary verification failed',
570
+ retryable: true
571
+ };
572
+ }
573
+ async function verifyCommentWrite(strategy, loaded, parent, item, current, id) {
574
+ if (!strategy.verifyReadback || strategy.parentKind === 'issue')
575
+ return null;
576
+ const observed = await observeCommentWrite(strategy, loaded, parent, item);
577
+ if (observed.valid)
578
+ return null;
579
+ if (strategy.parentKind === 'pull-request') {
580
+ return compensatePullRequestComment(strategy, loaded, parent, current, id, observed.error);
581
+ }
582
+ return observed.error;
583
+ }
584
+ async function writeDesiredComments(strategy, loaded, context, parent, resource, desired, selection, operations) {
585
+ const ids = [];
586
+ for (const item of desired) {
587
+ const current = selection.reposition && item === desired[0] ? undefined : selection.byMarker.get(item.marker);
588
+ if (current && normalizeCommentContent(current.body) === normalizeCommentContent(item.body)) {
589
+ ids.push(current.id);
590
+ operations.push({ name: `comment:${item.marker}`, status: 'no-op', reasonCode: null });
591
+ continue;
592
+ }
593
+ const written = loaded.provider.comments?.write
594
+ ? await loaded.provider.comments.write({ context: providerOperationContext(loaded), parent, body: item.body,
595
+ ...(current ? { existingComment: providerResourceToken(loaded.provider, 'comment', String(current.id)) } : {}),
596
+ mutation: { idempotencyKey: `comment:${strategy.taskId}:${item.marker}` } })
597
+ : unsupportedProviderOperation(loaded.provider, 'comments.write');
598
+ if (!written.ok)
599
+ return { ok: false, result: platformResult(isRetryable(written.error) ? 'blocked' : 'failed', {
600
+ ...contextFields(context), resource, operations, error: written.error
601
+ }) };
602
+ const id = providerCommentId(written.value.remoteId, loaded.provider);
603
+ ids.push(id);
604
+ operations.push({ name: `comment:${item.marker}`, status: 'applied', reasonCode: null });
605
+ const error = await verifyCommentWrite(strategy, loaded, parent, item, current, id);
606
+ if (error)
607
+ return { ok: false, result: platformResult(error.retryable ? 'blocked' : 'failed', {
608
+ ...contextFields(context), resource, operations, error
609
+ }) };
610
+ }
611
+ return { ok: true, ids };
612
+ }
613
+ async function deleteStaleComments(strategy, loaded, context, parent, resource, existing, desired, operations) {
614
+ const markers = new Set(desired.map((item) => item.marker));
615
+ for (const stale of existing.filter((comment) => !markers.has(normalizeCommentContent(comment.body).split('\n', 1)[0]))) {
616
+ const deleted = loaded.provider.comments?.delete
617
+ ? await loaded.provider.comments.delete({ context: providerOperationContext(loaded), parent,
618
+ comment: providerResourceToken(loaded.provider, 'comment', String(stale.id)),
619
+ mutation: { idempotencyKey: `comment-delete:${strategy.taskId}:${stale.id}` } })
620
+ : unsupportedProviderOperation(loaded.provider, 'comments.delete');
621
+ if (!deleted.ok)
622
+ return platformResult(isRetryable(deleted.error) ? 'blocked' : 'failed', {
623
+ ...contextFields(context), resource, operations, error: deleted.error
624
+ });
625
+ operations.push({ name: `comment:${stale.id}`, status: 'applied', reasonCode: 'STALE_CHUNK_DELETED' });
626
+ }
627
+ return null;
628
+ }
629
+ async function prepareCommentExecution(strategy, client) {
630
+ const resolved = strategy.resolved
631
+ ? { ok: true, value: strategy.resolved.loaded }
632
+ : await resolvePlatformProviderContext({ cwd: strategy.cwd, client });
633
+ const loaded = resolved;
634
+ const context = strategy.resolved?.context ?? (loaded.ok ? loaded.value.context : loaded.context);
635
+ if (!loaded.ok || !hasResolvedPlatformContext(context))
636
+ return { ok: false, result: context };
637
+ let parent;
638
+ let desired;
639
+ try {
640
+ ({ parent, items: desired } = await strategy.prepare());
641
+ }
642
+ catch (error) {
643
+ const value = error;
644
+ return { ok: false, result: platformResult('failed', { ...contextFields(context), error: {
645
+ code: value.code || 'COMMENT_PAYLOAD_INVALID', message: value.message || String(error), retryable: false
646
+ } }) };
647
+ }
648
+ const resource = { kind: strategy.parentKind, number: resourceIdentityNumber(parent), identity: parent };
649
+ const listed = await listedComments(loaded.value.provider, loaded.value, parent);
650
+ if (!listed.ok)
651
+ return { ok: false, result: platformResult(isRetryable(listed.error) ? 'blocked' : 'failed', {
652
+ ...contextFields(context), resource, error: listed.error
653
+ }) };
654
+ const selection = await inspectCommentPlan(strategy, context, resource, listed.value, desired);
655
+ if (!selection.ok)
656
+ return selection;
657
+ return {
658
+ ok: true,
659
+ value: {
660
+ loaded: loaded.value,
661
+ context,
662
+ parent,
663
+ desired,
664
+ resource,
665
+ selection: selection.value,
666
+ result: selection.result
667
+ }
668
+ };
669
+ }
413
670
  function validateRelatedMarkerSet(comments, prefix) {
414
671
  const markers = comments.map((comment) => normalizeCommentContent(comment.body).split('\n', 1)[0] || '');
415
672
  if (new Set(markers).size !== markers.length)
@@ -433,259 +690,108 @@ function validateRelatedMarkerSet(comments, prefix) {
433
690
  const complete = total > 0 && parts.length === total && parts.every((part, index) => part === index + 1);
434
691
  return complete ? { ok: true, code: null } : { ok: false, code: 'COMMENT_MARKER_CONFLICT' };
435
692
  }
436
- function writeComment(client, repo, issue, cwd, body, id) {
437
- const endpoint = id ? `repos/${repo}/issues/comments/${id}` : `repos/${repo}/issues/${issue}/comments`;
438
- return client.json(['api', endpoint, '-X', id ? 'PATCH' : 'POST', '--input', '-'], { cwd, method: id ? 'PATCH' : 'POST', input: JSON.stringify({ body }) });
693
+ function parentComment(comment, provider) {
694
+ return {
695
+ id: providerCommentId(comment.id, provider), body: comment.body,
696
+ user: comment.author?.name ? { login: comment.author.name } : undefined,
697
+ createdSequence: comment.createdSequence
698
+ };
439
699
  }
440
- async function syncPlatformCommentImpl(taskRef, options) {
441
- const resolved = resolveTaskRef(taskRef, options.cwd ? { repoRoot: options.cwd } : {});
442
- if (!resolved.ok) {
443
- return platformResult('failed', {
444
- error: { code: resolved.code, message: resolved.message, retryable: false }
445
- });
446
- }
447
- const taskContent = fs.readFileSync(resolved.taskMdPath, 'utf8');
448
- let issueIdentityFromTask;
449
- try {
450
- issueIdentityFromTask = taskIssueIdentity(parseTaskFrontmatter(taskContent));
451
- }
452
- catch (error) {
453
- return platformResult('failed', { error: { ...taskIssueIdentityError(error), retryable: false } });
454
- }
455
- if (!issueIdentityFromTask) {
456
- return platformResult('no-op', {
457
- error: { code: 'ISSUE_NOT_LINKED', message: 'Task has no valid platform issue identity', retryable: false }
458
- });
459
- }
460
- let desired;
461
- try {
462
- const projectedContent = options.kind === 'task' && options.taskProjection ? options.taskProjection.content : taskContent;
463
- if (options.kind === 'task' && options.taskProjection
464
- && createHash('sha256').update(projectedContent).digest('hex') !== options.taskProjection.sha256) {
465
- throw Object.assign(new Error('finalization task projection digest does not match content'), { code: 'FINALIZATION_PROJECTION_INVALID' });
466
- }
467
- desired = expectedComments(resolved.taskId, projectedContent, resolved.taskDir, resolved.repoRoot, options);
468
- }
469
- catch (error) {
470
- return platformResult('failed', {
471
- resource: { kind: 'issue', number: resourceIdentityNumber(issueIdentityFromTask) },
472
- error: { code: 'COMMENT_PAYLOAD_INVALID', message: error instanceof Error ? error.message : String(error), retryable: false }
473
- });
474
- }
475
- if (options.kind === 'task' && Buffer.byteLength(desired[0].body, 'utf8') > COMMENT_BYTE_LIMIT) {
476
- return platformResult('failed', {
477
- resource: { kind: 'issue', number: resourceIdentityNumber(issueIdentityFromTask), identity: issueIdentityFromTask },
478
- operations: [{ name: `comment:${MARKERS.task(resolved.taskId)}`, status: 'skipped', reasonCode: 'COMMENT_PAYLOAD_TOO_LARGE' }],
479
- error: { code: 'COMMENT_PAYLOAD_TOO_LARGE', message: 'Projected task comment exceeds the platform byte limit', retryable: false }
480
- });
481
- }
482
- const loaded = await resolvePlatformProviderContext({ cwd: resolved.repoRoot, client: options.client });
483
- const context = loaded.ok ? loaded.value.context : loaded.context;
484
- if (!hasResolvedPlatformContext(context) || !loaded.ok)
485
- return context;
486
- const issue = resourceIdentityNumber(issueIdentityFromTask);
487
- const listed = await listedComments(loaded.value.provider, loaded.value, issueIdentityFromTask);
488
- if (!listed.ok) {
489
- return platformResult(isRetryable(listed.error) ? 'blocked' : 'failed', {
490
- ...contextFields(context), resource: { kind: 'issue', number: issue }, error: listed.error
491
- });
492
- }
493
- const existing = relatedComments(listed.value, markerPrefix(resolved.taskId, options));
494
- if (!validateRelatedMarkerSet(existing, markerPrefix(resolved.taskId, options)).ok) {
495
- return platformResult('failed', {
496
- ...contextFields(context),
497
- resource: { kind: 'issue', number: issue },
498
- error: { code: 'COMMENT_MARKER_CONFLICT', message: 'Multiple comments use the same registered marker', retryable: false }
499
- });
500
- }
501
- if (options.kind === 'task' && existing.length === 1) {
502
- const owner = existing[0].user?.login;
503
- if (!owner || !context.platform.currentUser || owner !== context.platform.currentUser) {
504
- return platformResult('blocked', {
505
- ...contextFields(context),
506
- resource: { kind: 'issue', number: issue, identity: issueIdentityFromTask },
507
- error: {
508
- code: 'COMMENT_OWNER_CONFLICT',
509
- message: owner ? `Task comment is owned by '${owner}'` : 'Task comment owner is unavailable',
510
- retryable: false
511
- }
512
- });
513
- }
514
- }
515
- // Backfill only supplies missing artifact comments; valid existing marker sets stay untouched.
516
- if (options.kind === 'artifact' && options.backfill && existing.length > 0) {
517
- const operations = existing.map((comment) => ({
518
- name: `comment:${normalizeCommentContent(comment.body).split('\n', 1)[0]}`,
519
- status: 'no-op',
520
- reasonCode: 'BACKFILL_ALREADY_PRESENT'
521
- }));
522
- return platformResult('no-op', {
523
- ...contextFields(context),
524
- changed: false,
525
- resource: { kind: 'issue', number: issue },
526
- operations,
527
- comment: {
528
- kind: options.kind,
529
- marker: desired[0].marker,
530
- ids: existing.map((comment) => comment.id),
531
- parts: existing.length
532
- },
533
- error: null
700
+ function issueSummaryPosition(taskId, comments, marker) {
701
+ const managed = comments.filter((comment) => comment.body.split('\n', 1)[0]?.startsWith(`<!-- sync-issue:${taskId}:`));
702
+ const summary = managed.filter((comment) => comment.body.split('\n', 1)[0] === marker);
703
+ if (summary.length !== 1 || managed.some((comment) => !Number.isSafeInteger(comment.createdSequence) || comment.createdSequence === null))
704
+ return null;
705
+ return managed.every((comment) => summary[0].createdSequence >= comment.createdSequence);
706
+ }
707
+ async function executeCommentPlan(strategy, client) {
708
+ const prepared = await prepareCommentExecution(strategy, client);
709
+ if (!prepared.ok)
710
+ return prepared.result;
711
+ const { loaded, context, parent, desired, resource, selection, result } = prepared.value;
712
+ if (result)
713
+ return result;
714
+ if (strategy.dryRun)
715
+ return platformResult('planned', {
716
+ ...contextFields(context), resource,
717
+ operations: desired.map((item) => ({ name: `comment:${item.marker}`, status: 'planned', reasonCode: null })), error: null
534
718
  });
535
- }
536
719
  const operations = [];
537
- const ids = [];
538
- for (const item of desired) {
539
- const current = existing.find((comment) => normalizeCommentContent(comment.body).split('\n', 1)[0] === item.marker);
540
- if (current && normalizeCommentContent(current.body) === normalizeCommentContent(item.body)) {
541
- ids.push(current.id);
542
- operations.push({ name: `comment:${item.marker}`, status: 'no-op', reasonCode: null });
543
- continue;
544
- }
545
- const written = loaded.value.provider.comments?.write
546
- ? await loaded.value.provider.comments.write({
547
- context: providerOperationContext(loaded.value),
548
- parent: issueIdentityFromTask,
549
- body: item.body,
550
- ...(current ? { existingComment: { kind: 'id', value: String(current.id) } } : {}),
551
- mutation: { idempotencyKey: `comment:${resolved.taskId}:${item.marker}` }
552
- })
553
- : unsupportedProviderOperation(loaded.value.provider, 'comments.write');
554
- if (!written.ok) {
555
- if (!current && isRetryable(written.error)) {
556
- // A provider owns reconciliation because only it knows how to address the resource.
557
- }
558
- return platformResult(isRetryable(written.error) ? 'blocked' : 'failed', {
559
- ...contextFields(context),
560
- resource: { kind: 'issue', number: issue },
561
- operations,
562
- error: written.error
563
- });
564
- }
565
- ids.push(providerCommentId(written.value.remoteId, loaded.value.provider));
566
- operations.push({ name: `comment:${item.marker}`, status: 'applied', reasonCode: null });
567
- }
568
- const desiredMarkers = new Set(desired.map((item) => item.marker));
569
- const stale = existing.filter((comment) => !desiredMarkers.has(normalizeCommentContent(comment.body).split('\n', 1)[0]));
570
- for (const comment of stale) {
571
- const deleted = loaded.value.provider.comments?.delete
572
- ? await loaded.value.provider.comments.delete({
573
- context: providerOperationContext(loaded.value),
574
- parent: issueIdentityFromTask,
575
- comment: { kind: 'id', value: String(comment.id) },
576
- mutation: { idempotencyKey: `comment-delete:${resolved.taskId}:${comment.id}` }
577
- })
578
- : unsupportedProviderOperation(loaded.value.provider, 'comments.delete');
579
- if (!deleted.ok) {
580
- return platformResult(isRetryable(deleted.error) ? 'blocked' : 'failed', {
581
- ...contextFields(context),
582
- resource: { kind: 'issue', number: issue },
583
- operations,
584
- error: deleted.error
585
- });
586
- }
587
- operations.push({ name: `comment:${comment.id}`, status: 'applied', reasonCode: 'STALE_CHUNK_DELETED' });
588
- }
589
- if (options.kind === 'summary') {
590
- const refreshed = await listedComments(loaded.value.provider, loaded.value, issueIdentityFromTask);
591
- if (!refreshed.ok) {
592
- return platformResult(isRetryable(refreshed.error) ? 'blocked' : 'failed', {
593
- ...contextFields(context), resource: { kind: 'issue', number: issue }, operations, error: refreshed.error
594
- });
595
- }
596
- const position = summaryPosition(refreshed.value, resolved.taskId);
597
- if (!position.ok && !position.known) {
598
- return platformResult('blocked', {
599
- ...contextFields(context), resource: { kind: 'issue', number: issue }, operations,
600
- error: { code: 'SUMMARY_POSITION_UNVERIFIED', message: 'Summary comment ordering cannot be proven from the provider snapshot', retryable: true }
601
- });
602
- }
603
- if (!position.ok && position.summary) {
604
- const owner = position.summary.user?.login;
605
- if (!options.summaryAuthorization || options.summaryAuthorization.sha256 !== createHash('sha256').update(options.body ?? '').digest('hex')
606
- || !owner || owner !== context.platform.currentUser) {
607
- return platformResult('failed', {
608
- ...contextFields(context), resource: { kind: 'issue', number: issue }, operations,
609
- error: { code: 'SUMMARY_REPOSITION_UNAUTHORIZED', message: 'summary reposition requires current finalization authorization and an owned durable summary', retryable: false }
610
- });
611
- }
612
- const deleted = loaded.value.provider.comments?.delete
613
- ? await loaded.value.provider.comments.delete({
614
- context: providerOperationContext(loaded.value), parent: issueIdentityFromTask,
615
- comment: { kind: 'id', value: String(position.summary.id) },
616
- mutation: { idempotencyKey: `summary-reposition-delete:${resolved.taskId}:${position.summary.id}` }
617
- })
618
- : unsupportedProviderOperation(loaded.value.provider, 'comments.delete');
619
- if (!deleted.ok) {
620
- return platformResult(isRetryable(deleted.error) ? 'blocked' : 'failed', {
621
- ...contextFields(context), resource: { kind: 'issue', number: issue }, operations, error: deleted.error
622
- });
623
- }
624
- const written = loaded.value.provider.comments?.write
625
- ? await loaded.value.provider.comments.write({
626
- context: providerOperationContext(loaded.value), parent: issueIdentityFromTask, body: desired[0].body,
627
- mutation: { idempotencyKey: `summary-reposition-write:${resolved.taskId}` }
628
- })
629
- : unsupportedProviderOperation(loaded.value.provider, 'comments.write');
630
- if (!written.ok) {
631
- return platformResult(isRetryable(written.error) ? 'blocked' : 'failed', {
632
- ...contextFields(context), resource: { kind: 'issue', number: issue }, operations, error: written.error
633
- });
634
- }
635
- ids.splice(0, ids.length, providerCommentId(written.value.remoteId, loaded.value.provider));
636
- operations.push({ name: `comment:${desired[0].marker}`, status: 'applied', reasonCode: 'SUMMARY_REPOSITIONED' });
637
- const reconciled = await listedComments(loaded.value.provider, loaded.value, issueIdentityFromTask);
638
- if (!reconciled.ok || !summaryPosition(reconciled.value, resolved.taskId).ok) {
639
- const error = reconciled.ok
640
- ? { code: 'SUMMARY_POSITION_UNVERIFIED', message: 'Summary comment is not provably last among task-managed comments', retryable: true }
641
- : reconciled.error;
642
- return platformResult(isRetryable(error) ? 'blocked' : 'failed', {
643
- ...contextFields(context), resource: { kind: 'issue', number: issue }, operations, error
644
- });
645
- }
646
- }
647
- }
720
+ const currentSummary = desired[0] ? selection.byMarker.get(desired[0].marker) : undefined;
721
+ if (selection.reposition) {
722
+ const repositioned = await repositionSummaryComment(strategy, loaded, context, parent, resource, currentSummary, operations);
723
+ if (repositioned)
724
+ return repositioned;
725
+ }
726
+ const written = await writeDesiredComments(strategy, loaded, context, parent, resource, desired, selection, operations);
727
+ if (!written.ok)
728
+ return written.result;
729
+ const deleted = await deleteStaleComments(strategy, loaded, context, parent, resource, selection.existing, desired, operations);
730
+ if (deleted)
731
+ return deleted;
732
+ const readback = await verifyIssueSummaryReadback(strategy, loaded, context, parent, resource, desired, operations);
733
+ if (readback)
734
+ return readback;
648
735
  const changed = operations.some((operation) => operation.status === 'applied');
649
- const result = platformResult(changed ? 'applied' : 'no-op', {
650
- ...contextFields(context),
651
- changed,
652
- resource: { kind: 'issue', number: issue },
653
- operations,
654
- comment: { kind: options.kind, marker: desired[0]?.marker ?? markerPrefix(resolved.taskId, options), ids, parts: desired.length },
736
+ return platformResult(changed ? 'applied' : 'no-op', {
737
+ ...contextFields(context), changed, resource, operations,
738
+ comment: {
739
+ kind: strategy.kind,
740
+ marker: desired[0]?.marker ?? strategy.markerPrefix,
741
+ ids: written.ids,
742
+ parts: desired.length
743
+ },
655
744
  error: null
656
745
  });
657
- return result;
658
746
  }
659
- async function syncPlatformComment(taskRef, options) {
747
+ function syncPlatformComment(taskRef, options) {
660
748
  const resolved = resolveTaskRef(taskRef, options.cwd ? { repoRoot: options.cwd } : {});
661
749
  if (!resolved.ok)
662
- return syncPlatformCommentImpl(taskRef, options);
663
- const taskContent = fs.readFileSync(resolved.taskMdPath, 'utf8');
664
- if (!taskIssueIdentity(parseTaskFrontmatter(taskContent)))
665
- return syncPlatformCommentImpl(taskRef, options);
750
+ return Promise.resolve(platformResult('failed', { error: { code: resolved.code, message: resolved.message, retryable: false } }));
751
+ const readStrategy = () => {
752
+ const prefix = markerPrefix(resolved.taskId, options);
753
+ return {
754
+ taskId: resolved.taskId, cwd: resolved.repoRoot, agent: options.agent, client: options.client,
755
+ parentKind: 'issue', kind: options.kind, markerPrefix: prefix,
756
+ backfill: options.backfill,
757
+ prepare: async () => {
758
+ const taskContent = fs.readFileSync(resolved.taskMdPath, 'utf8');
759
+ const parent = taskIssueIdentity(parseTaskFrontmatter(taskContent));
760
+ if (!parent)
761
+ throw Object.assign(new Error('Task has no valid platform issue identity'), { code: 'ISSUE_NOT_LINKED' });
762
+ const source = options.kind === 'task' && options.taskProjection ? options.taskProjection.content : taskContent;
763
+ if (options.kind === 'task' && options.taskProjection && createHash('sha256').update(source).digest('hex') !== options.taskProjection.sha256) {
764
+ throw Object.assign(new Error('finalization task projection digest does not match content'), { code: 'FINALIZATION_PROJECTION_INVALID' });
765
+ }
766
+ const items = expectedComments(resolved.taskId, source, resolved.taskDir, resolved.repoRoot, options);
767
+ if (options.kind === 'task' && Buffer.byteLength(items[0].body, 'utf8') > COMMENT_BYTE_LIMIT)
768
+ throw Object.assign(new Error('Projected task comment exceeds the platform byte limit'), { code: 'COMMENT_PAYLOAD_TOO_LARGE' });
769
+ return { parent, items };
770
+ },
771
+ summaryPosition: options.kind === 'summary',
772
+ verifyReadback: options.kind === 'summary' || options.kind === 'cancel',
773
+ authorizeReposition: (comment, currentUser) => options.summaryAuthorization
774
+ && options.summaryAuthorization.sha256 === createHash('sha256').update(options.body ?? '').digest('hex')
775
+ && comment.user?.login && currentUser && comment.user.login === currentUser
776
+ ? null : { code: 'SUMMARY_REPOSITION_UNAUTHORIZED', message: 'summary reposition requires current finalization authorization and an owned durable summary', retryable: false }
777
+ };
778
+ };
779
+ let strategy;
666
780
  let operation;
667
781
  try {
668
- const sourceContent = options.kind === 'task' && options.taskProjection ? options.taskProjection.content : taskContent;
669
- const desired = expectedComments(resolved.taskId, sourceContent, resolved.taskDir, resolved.repoRoot, options);
670
- const content = desired.map((chunk) => chunk.content).join('\0');
671
- const kind = options.kind === 'task' ? 'task-comment' : options.kind === 'summary' ? 'summary-comment'
672
- : options.kind === 'cancel' ? 'cancel-comment' : 'artifact-comment';
782
+ strategy = readStrategy();
783
+ const source = options.kind === 'task' && options.taskProjection ? options.taskProjection.content : fs.readFileSync(resolved.taskMdPath, 'utf8');
784
+ const expected = expectedComments(resolved.taskId, source, resolved.taskDir, resolved.repoRoot, options);
785
+ const digest = createHash('sha256').update(expected.map((item) => item.content).join('\0')).digest('hex');
786
+ const kind = options.kind === 'task' ? 'task-comment' : options.kind === 'artifact' ? 'artifact-comment' : options.kind === 'summary' ? 'summary-comment' : 'cancel-comment';
673
787
  const target = options.kind === 'artifact' ? options.artifact : options.kind;
674
- operation = { kind, target, expectedDigest: createHash('sha256').update(content).digest('hex') };
788
+ operation = { taskRef: resolved.taskId, cwd: resolved.repoRoot, kind, target, expectedDigest: digest, dependency: options.dependency ?? 'deferred' };
675
789
  }
676
- catch {
677
- return syncPlatformCommentImpl(taskRef, options);
790
+ catch (error) {
791
+ const value = error;
792
+ return Promise.resolve(platformResult('failed', { error: { code: value.code || 'COMMENT_PAYLOAD_INVALID', message: value.message || String(error), retryable: false } }));
678
793
  }
679
- const execute = () => syncPlatformCommentImpl(taskRef, options);
680
- if (options.skipQueue)
681
- return execute();
682
- return coordinatePlatformWrite({
683
- operation: { taskRef: resolved.taskId, cwd: resolved.repoRoot, ...operation, dependency: options.dependency ?? 'deferred' },
684
- agent: options.agent,
685
- execute,
686
- block: (error) => platformResult('blocked', { error }),
687
- persistenceFailure: (error) => platformResult('failed', { error })
688
- });
794
+ return syncCommentPlan(strategy, operation, options.queuedOperation);
689
795
  }
690
796
  function inspectPlatformCommentOperation(taskRef, options) {
691
797
  const resolved = resolveTaskRef(taskRef, options.cwd ? { repoRoot: options.cwd } : {});
@@ -766,5 +872,5 @@ async function checkPlatformCommentOwner(taskRef, options = {}) {
766
872
  }
767
873
  return platformResult('no-op', { ...contextFields(context), resource: { kind: 'issue', number: resourceIdentityNumber(issueIdentity), identity: issueIdentity }, error: null });
768
874
  }
769
- export { COMMENT_BYTE_LIMIT, MARKERS, chunkArtifactComment, inspectPlatformCommentOperation, findMarkerComments, listRemoteComments, checkPlatformCommentOwner, listPlatformComments, normalizeCommentContent, renderTaskComment, renderTaskCommentResult, isTaskCommentTooLarge, syncPlatformComment, validateRelatedMarkerSet, writeComment };
875
+ export { COMMENT_BYTE_LIMIT, MARKERS, chunkArtifactComment, inspectPlatformCommentOperation, findMarkerComments, listRemoteComments, checkPlatformCommentOwner, listPlatformComments, normalizeCommentContent, renderTaskComment, renderTaskCommentResult, syncCommentPlan, isTaskCommentTooLarge, syncPlatformComment, validateRelatedMarkerSet };
770
876
  //# sourceMappingURL=issue-comments.js.map