-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCleanupRunService.php
More file actions
463 lines (418 loc) · 16.1 KB
/
Copy pathCleanupRunService.php
File metadata and controls
463 lines (418 loc) · 16.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
<?php
/**
* DB-backed cleanup run service.
*
* @package DataMachineCode\Workspace
*/
namespace DataMachineCode\Workspace;
use DataMachineCode\Cleanup\CleanupRemainingWorkSummary;
use DataMachineCode\Storage\CleanupRunRepository;
defined('ABSPATH') || exit;
class CleanupRunService {
private const DEFAULT_APPLY_LIMIT = 25;
private const MAX_APPLY_LIMIT = 100;
private const WORKTREE_APPLY_BATCH_LIMIT = 1;
public function __construct(
private ?CleanupRunRepository $repository = null,
private ?Workspace $workspace = null
) {
$this->repository ??= new CleanupRunRepository();
$this->workspace ??= new Workspace();
}
/**
* Create and persist a cleanup plan run.
*
* @param array<string,mixed> $opts Plan options.
* @return array<string,mixed>|\WP_Error
*/
public function plan( array $opts = array() ): array|\WP_Error {
$plan = $this->workspace->workspace_cleanup_plan($opts);
if ( $plan instanceof \WP_Error ) {
return $plan;
}
$items = $this->plan_items($plan);
$run_id = $this->repository->create_run(
array(
'mode' => (string) ( $opts['mode'] ?? $plan['mode'] ?? 'cleanup_plan' ),
'status' => 'planned',
'policy' => $plan['safety_policy'] ?? array(),
'requested_by_user_id' => isset($opts['user_id']) ? (int) $opts['user_id'] : null,
'requested_by_agent_id' => isset($opts['agent_id']) ? (int) $opts['agent_id'] : null,
'summary' => $plan['summary'] ?? array(),
)
);
if ( $run_id instanceof \WP_Error ) {
return $run_id;
}
$inserted = $this->repository->add_items($run_id, $items);
if ( $inserted instanceof \WP_Error ) {
return $inserted;
}
$plan['run_id'] = $run_id;
$plan['cleanup_storage'] = array(
'type' => 'database',
'item_count' => $inserted,
'plan_id' => $plan['plan_id'] ?? null,
'escape_hatch' => 'filesystem apply-plan import remains available on lower-level worktree commands only',
);
return $plan;
}
/**
* Apply pending rows from a DB-backed run.
*
* @param string $run_id Run ID.
* @param array<string,mixed> $opts Apply options.
* @return array<string,mixed>|\WP_Error
*/
public function apply( string $run_id, array $opts = array() ): array|\WP_Error {
$run = $this->repository->get_run($run_id);
if ( null === $run ) {
return new \WP_Error('cleanup_run_not_found', sprintf('Cleanup run not found: %s', $run_id), array( 'status' => 404 ));
}
$limit = $this->apply_limit($opts);
$this->repository->update_run(
$run_id, array(
'status' => 'applying',
'started_at' => gmdate('Y-m-d H:i:s'),
)
);
$items = $this->repository->get_items($run_id);
$artifact_rows = $this->pending_rows_of_type($items, 'artifact_cleanup');
$worktree_rows = $this->pending_rows_of_type($items, 'worktree_removal');
$batch_type = '';
$processed_rows = 0;
$remaining_rows = max(0, count($artifact_rows) + count($worktree_rows));
$results = array();
if ( array() !== $artifact_rows ) {
$artifact_batch = array_slice($artifact_rows, 0, $limit);
$processed_rows += count($artifact_batch);
$batch_type = 'artifact_cleanup';
$this->mark_batch_applying($artifact_batch, $run_id, $batch_type, $limit, $remaining_rows);
$results['artifact_cleanup'] = $this->workspace->worktree_cleanup_artifacts(
array(
'apply_plan' => array( 'candidates' => array_map(fn( $item ) => $item['evidence'], $artifact_batch) ),
'force' => ! empty($opts['force']),
'limit' => count($artifact_batch),
)
);
$this->record_apply_result($artifact_batch, $results['artifact_cleanup'], 'removed');
}
$remaining_capacity = max(0, $limit - $processed_rows);
if ( $remaining_capacity > 0 && array() !== $worktree_rows ) {
$worktree_batch = array_slice($worktree_rows, 0, min($remaining_capacity, self::WORKTREE_APPLY_BATCH_LIMIT));
$processed_rows += count($worktree_batch);
$batch_type = '' === $batch_type ? 'worktree_removal' : 'mixed';
$this->mark_batch_applying($worktree_batch, $run_id, $batch_type, $limit, $remaining_rows);
$results['worktree_removal'] = $this->workspace->worktree_cleanup_merged(
array(
'apply_plan' => array( 'candidates' => array_map(fn( $item ) => $item['evidence'], $worktree_batch) ),
'skip_github' => true,
)
);
$this->record_apply_result($worktree_batch, $results['worktree_removal'], 'removed');
}
$status = $this->status($run_id);
$summary = $status instanceof \WP_Error ? array() : ( $status['summary'] ?? array() );
$pending_or_fail = (int) ( $summary['pending_or_failed'] ?? 0 );
$next_status = $pending_or_fail > 0 ? 'needs_resume' : 'completed';
$completed_at = 'completed' === $next_status ? gmdate('Y-m-d H:i:s') : null;
$this->repository->update_run(
$run_id, array(
'status' => $next_status,
'completed_at' => $completed_at,
'summary' => $summary,
)
);
$status = $this->status($run_id);
if ( $status instanceof \WP_Error ) {
return $status;
}
return array(
'success' => true,
'state' => $next_status,
'run_id' => $run_id,
'status' => $next_status,
'batch' => array(
'type' => $batch_type,
'limit' => $limit,
'processed_rows' => $processed_rows,
'remaining_before' => $remaining_rows,
'remaining_after' => $pending_or_fail,
),
'results' => $results,
'summary' => $status['summary'] ?? array(),
'remaining_work_summary' => $status['remaining_work_summary'] ?? array(),
'next' => $pending_or_fail > 0 ? array(
'resume_command' => sprintf('studio wp datamachine-code workspace cleanup resume %s --limit=%d', $run_id, $limit),
'pending_rows' => $pending_or_fail,
) : null,
);
}
/**
* Return aggregate run status.
*
* @param string $run_id Run ID.
* @return array<string,mixed>|\WP_Error
*/
public function status( string $run_id ): array|\WP_Error {
$run = $this->repository->get_run($run_id);
if ( null === $run ) {
return new \WP_Error('cleanup_run_not_found', sprintf('Cleanup run not found: %s', $run_id), array( 'status' => 404 ));
}
$items = $this->repository->get_items($run_id);
$summary = array(
'total_items' => count($items),
'items_by_status' => array(),
'items_by_type' => array(),
'bytes_reclaimed' => 0,
'pending_or_failed' => 0,
);
foreach ( $items as $item ) {
$status = (string) ( $item['status'] ?? 'unknown' );
$type = (string) ( $item['item_type'] ?? 'unknown' );
$summary['items_by_status'][ $status ] = ( $summary['items_by_status'][ $status ] ?? 0 ) + 1;
$summary['items_by_type'][ $type ] = ( $summary['items_by_type'][ $type ] ?? 0 ) + 1;
$summary['bytes_reclaimed'] += max(0, (int) ( $item['bytes_reclaimed'] ?? 0 ));
if ( in_array($status, array( 'pending', 'failed', 'applying' ), true) ) {
++$summary['pending_or_failed'];
}
}
ksort($summary['items_by_status']);
ksort($summary['items_by_type']);
$progress = $this->run_progress($run, $items, $summary);
return array(
'success' => true,
'state' => (string) ( $run['status'] ?? 'unknown' ),
'run_id' => $run_id,
'status' => $run['status'] ?? 'unknown',
'mode' => $run['mode'] ?? '',
'run' => $run,
'summary' => $summary,
'progress' => $progress,
'remaining_work_summary' => $this->remaining_work_summary($run_id, $items, $progress),
);
}
/**
* Return bounded evidence for a run.
*
* @param string $run_id Run ID.
* @return array<string,mixed>|\WP_Error
*/
public function evidence( string $run_id ): array|\WP_Error {
$status = $this->status($run_id);
if ( $status instanceof \WP_Error ) {
return $status;
}
$status['items'] = $this->repository->get_items($run_id);
return $status;
}
/**
* Mark pending rows cancelled.
*
* @param string $run_id Run ID.
* @return array<string,mixed>|\WP_Error
*/
public function cancel( string $run_id ): array|\WP_Error {
$items = $this->repository->get_items($run_id);
foreach ( $items as $item ) {
if ( 'pending' === (string) ( $item['status'] ?? '' ) ) {
$this->repository->update_item( (int) $item['id'], array( 'status' => 'cancelled' ));
}
}
$this->repository->update_run(
$run_id, array(
'status' => 'cancelled',
'completed_at' => gmdate('Y-m-d H:i:s'),
)
);
return $this->status($run_id);
}
/**
* Resume by applying pending/failed rows.
*
* @param string $run_id Run ID.
* @param array<string,mixed> $opts Options.
* @return array<string,mixed>|\WP_Error
*/
public function resume( string $run_id, array $opts = array() ): array|\WP_Error {
return $this->apply($run_id, $opts);
}
private function plan_items( array $plan ): array {
$items = array();
foreach ( (array) ( $plan['rows'] ?? array() ) as $type => $rows ) {
foreach ( (array) $rows as $row ) {
if ( ! is_array($row) ) {
continue;
}
$items[] = array(
'handle' => (string) ( $row['handle'] ?? '' ),
'item_type' => (string) $type,
'planned_action' => $this->planned_action_for_type( (string) $type),
'reason_code' => (string) ( $row['reason_code'] ?? '' ),
'reason' => (string) ( $row['reason'] ?? '' ),
'evidence' => $row,
'status' => 'resolver' === $type ? 'blocked' : 'pending',
);
}
}
return $items;
}
private function pending_rows_of_type( array $items, string $type ): array {
return array_values(array_filter($items, fn( $item ) => (string) ( $item['item_type'] ?? '' ) === $type && in_array( (string) ( $item['status'] ?? '' ), array( 'pending', 'failed', 'applying' ), true)));
}
/**
* Mark rows as in-progress before invoking destructive cleanup so interrupted
* operator runs leave a visible, resumable checkpoint instead of silent state.
*
* @param array<int,array<string,mixed>> $items Batch rows.
* @param string $run_id Run ID.
* @param string $batch_type Batch type label.
* @param int $limit Requested apply limit.
* @param int $remaining_rows Rows remaining before this batch.
*/
private function mark_batch_applying( array $items, string $run_id, string $batch_type, int $limit, int $remaining_rows ): void {
$started_at = gmdate('Y-m-d H:i:s');
foreach ( $items as $item ) {
$this->repository->update_item(
(int) $item['id'],
array(
'status' => 'applying',
'evidence' => array_merge(
(array) ( $item['evidence'] ?? array() ),
array(
'applying_started_at' => $started_at,
'applying_batch_type' => $batch_type,
)
),
)
);
}
$this->repository->update_run(
$run_id,
array(
'summary' => array(
'applying_batch' => array(
'type' => $batch_type,
'limit' => $limit,
'row_count' => count($items),
'remaining_before' => $remaining_rows,
'started_at' => $started_at,
),
),
)
);
}
/**
* Build operator progress metadata for status/evidence output.
*
* @param array<string,mixed> $run Run row.
* @param array<int,array<string,mixed>> $items Item rows.
* @param array<string,mixed> $summary Aggregate summary.
* @return array<string,mixed>
*/
private function run_progress( array $run, array $items, array $summary ): array {
$applying = array_values(array_filter($items, fn( $item ) => 'applying' === (string) ( $item['status'] ?? '' )));
$examples = array_slice(array_map(fn( $item ) => array(
'handle' => (string) ( $item['handle'] ?? '' ),
'type' => (string) ( $item['item_type'] ?? '' ),
), $applying), 0, 3);
$started_at = (string) ( $run['started_at'] ?? '' );
$age = '' !== $started_at ? max(0, time() - strtotime($started_at)) : 0;
$run_status = (string) ( $run['status'] ?? '' );
$resumable = (int) ( $summary['pending_or_failed'] ?? 0 ) > 0 && in_array($run_status, array( 'applying', 'needs_resume' ), true);
return array(
'applying_rows' => count($applying),
'applying_examples' => $examples,
'pending_or_failed' => (int) ( $summary['pending_or_failed'] ?? 0 ),
'started_at' => $started_at,
'age_seconds' => $age,
'resumable' => $resumable,
'note' => count($applying) > 0 ? 'Rows marked applying are safe to retry with workspace cleanup resume if the previous apply process was interrupted.' : '',
);
}
/**
* Build remaining-work summary and prepend the current run resume command.
*
* @param string $run_id Run ID.
* @param array<int,array<string,mixed>> $items Item rows.
* @param array<string,mixed> $progress Progress metadata.
* @return array<string,mixed>
*/
private function remaining_work_summary( string $run_id, array $items, array $progress ): array {
$summary = CleanupRemainingWorkSummary::from_items($items);
if ( ! empty($progress['resumable']) ) {
array_unshift(
$summary['recommended_commands'],
array(
'bucket' => 'current_run_resume',
'command' => sprintf('studio wp datamachine-code workspace cleanup status %s --format=json', $run_id),
'apply' => sprintf('studio wp datamachine-code workspace cleanup resume %s --limit=%d', $run_id, self::DEFAULT_APPLY_LIMIT),
'destructive' => false,
'apply_destructive' => true,
'why' => 'Resume the reviewed DB-backed cleanup run from persisted pending/failed/applying rows.',
)
);
}
return $summary;
}
private function apply_limit( array $opts ): int {
$limit = isset($opts['limit']) ? (int) $opts['limit'] : self::DEFAULT_APPLY_LIMIT;
return max(1, min(self::MAX_APPLY_LIMIT, $limit));
}
private function record_apply_result( array $items, mixed $result, string $applied_key ): void {
if ( $result instanceof \WP_Error ) {
foreach ( $items as $item ) {
$this->repository->update_item(
(int) $item['id'], array(
'status' => 'failed',
'reason_code' => $result->get_error_code(),
'reason' => $result->get_error_message(),
)
);
}
return;
}
$applied_by_handle = array();
foreach ( (array) ( $result[ $applied_key ] ?? array() ) as $row ) {
$applied_by_handle[ (string) ( $row['handle'] ?? '' ) ] = is_array($row) ? $row : array();
}
$skipped_by_handle = array();
foreach ( (array) ( $result['skipped'] ?? array() ) as $skip ) {
$skipped_by_handle[ (string) ( $skip['handle'] ?? '' ) ] = $skip;
}
foreach ( $items as $item ) {
$handle = (string) ( $item['handle'] ?? '' );
if ( isset($applied_by_handle[ $handle ]) ) {
$applied = $applied_by_handle[ $handle ];
$this->repository->update_item(
(int) $item['id'],
array(
'status' => 'applied',
'applied_at' => gmdate('Y-m-d H:i:s'),
'bytes_reclaimed' => max(0, (int) ( $applied['artifact_size_bytes'] ?? $applied['size_bytes'] ?? $item['evidence']['artifact_size_bytes'] ?? $item['evidence']['size_bytes'] ?? 0 )),
'evidence' => array_merge( (array) $item['evidence'], array( 'applied' => $applied )),
)
);
continue;
}
$skip = $skipped_by_handle[ $handle ] ?? null;
$this->repository->update_item(
(int) $item['id'],
array(
'status' => 'skipped',
'reason_code' => is_array($skip) ? (string) ( $skip['reason_code'] ?? 'apply_skipped' ) : 'apply_skipped',
'reason' => is_array($skip) ? (string) ( $skip['reason'] ?? '' ) : 'row was not applied',
'evidence' => is_array($skip) ? $skip : $item['evidence'],
)
);
}
}
private function planned_action_for_type( string $type ): string {
return match ( $type ) {
'artifact_cleanup' => 'remove_artifacts',
'worktree_removal' => 'remove_worktree',
'resolver' => 'resolve_signal',
default => 'review',
};
}
}