Merge pull request #1788 from entireio/fix-dispatch-local · Entire

Merge pull request #1788 from entireio/fix-dispatch-local

e32c16b→main·

fix(dispatch): make dispatch --local surface recent merged work (ENT-1188)

Changes

2

11 unmodified lines

12
13
14
15
16
17
18
143 unmodified lines

162
163
164
164
165
166
166
167
168
169
170
171
172
173
174
17 unmodified lines

192
193
194
195
196
197
198
16 unmodified lines

215
216
217
212
213
214
215
216
217
218
219
220
221
222
218
219
220
1 unmodified line

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
237
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
2 unmodified lines

331
332
333
334
335
336
248
337
338
339
340
341
342
343
255
256
257
258
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
3 unmodified lines

369
370
371
268
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389

11 unmodified lines

"github.com/entireio/cli/cmd/entire/cli/auth"
    "github.com/entireio/cli/cmd/entire/cli/checkpoint"
    checkpointid "github.com/entireio/cli/cmd/entire/cli/checkpoint/id"
    "github.com/entireio/cli/cmd/entire/cli/gitrepo"
    "github.com/entireio/cli/cmd/entire/cli/logging"
    "github.com/entireio/cli/cmd/entire/cli/paths"
143 unmodified lines

for _, branch := range branches {
        branchSet[branch] = struct{}{}
    }
    reachableCheckpointIDs := map[string]struct{}{}
    reachableCheckpointIDs := map[string]time.Time{}
    if opts.ImplicitCurrentBranch && !opts.AllBranches {
        reachableCheckpointIDs, err = reachableCheckpointIDsInRange(ctx, repoRoot, branchLocalRevRange(ctx, repoRoot), since)
        currentBranch := ""
        if len(branches) > 0 {
            currentBranch = branches[0]
        }
        reachableCheckpointIDs, err = reachableCheckpointIDsInRange(ctx, repoRoot, branchLocalRevRange(ctx, repoRoot, currentBranch), since, until)
        if err != nil {
            return nil, err
        }
17 unmodified lines

}

candidates := make([]candidate, 0, len(infos))
    seen := make(map[string]struct{}, len(infos))
    for _, info := range infos {
        if info.CreatedAt.Before(since) || !info.CreatedAt.Before(until) {
            continue
        }
16 unmodified lines

}

localSummary := ""
        if len(summary.Sessions) > 0 {
            latestIndex := len(summary.Sessions) - 1
            if metadata, err := store.ReadSessionMetadata(ctx, info.CheckpointID, latestIndex); err == nil && metadata != nil && metadata.Summary != nil {
                localSummary = strings.TrimSpace(metadata.Summary.Outcome)
                if localSummary == "" {
                    localSummary = strings.TrimSpace(metadata.Summary.Intent)
                }
            }
        }

commitSubject := commitSubjectsByCheckpoint[info.CheckpointID.String()]
        candidates = append(candidates, candidate{
            CheckpointID:      info.CheckpointID.String(),
            Branch:            summary.Branch,
            CreatedAt:         info.CreatedAt,
            CommitSubject:     commitSubject,
            LocalSummaryTitle: readLocalSummaryTitle(ctx, store, info.CheckpointID, summary),
        })
        seen[info.CheckpointID.String()] = struct{}{}
    }

// Second pass: checkpoints referenced by branch commit trailers in the
    // window that store.List did not surface. store.List only enumerates
    // checkpoints present in the local checkout, but on a checkout that has not
    // fetched recent checkpoints (the common case — checkpoints are pushed to
    // the remote from other worktrees) the recent work is missing locally even
    // though it is reachable from HEAD. The commit subject is always available
    // from git log, so we can summarize that work from the trailer + subject
    // without a (slow) per-checkpoint network fetch; when the checkpoint does
    // happen to be local we still prefer its richer session summary. Windowed
    // by commit ("landed on branch") time, since a CheckpointSummary carries no
    // CreatedAt of its own.
    for idStr, commitTime := range reachableCheckpointIDs {
        if _, ok := seen[idStr]; ok {
            continue
        }
        if commitTime.Before(since) || !commitTime.Before(until) {
            continue
        }
        commitSubject := commitSubjectsByCheckpoint[idStr]

// Opportunistic local read for a richer title/branch — no fetcher is
        // wired, so this never touches the network; a checkpoint absent locally
        // resolves to nil and we fall back to the commit subject.
        branch := ""
        localSummary := ""
        if cid, cidErr := checkpointid.NewCheckpointID(idStr); cidErr == nil {
            if summary, readErr := store.Read(ctx, cid); readErr == nil && summary != nil {
                branch = summary.Branch
                localSummary = readLocalSummaryTitle(ctx, store, cid, summary)
            }
        }

if strings.TrimSpace(localSummary) == "" && strings.TrimSpace(commitSubject) == "" {
            continue
        }
        candidates = append(candidates, candidate{
            CheckpointID:      idStr,
            RepoFullName:      repoFullName,
            Branch:            branch,
            CreatedAt:         commitTime,
            CommitSubject:     commitSubject,
            LocalSummaryTitle: localSummary,
        })
        seen[idStr] = struct{}{}
    }

// The second pass ranges over a map (randomized iteration order), so sort
    // before returning to keep bullet order — and therefore the LLM-authored
    // summary — stable across runs. Newest first, with the checkpoint ID as a
    // deterministic tiebreak for equal timestamps.
sortCandidatesByRecency(candidates)
return candidates, nil
}

func reachableCheckpointIDsInRange(ctx context.Context, repoRoot, revRange string, since time.Time) (map[string]struct{}, error) {
// sortCandidatesByRecency orders candidates most-recent-first by CreatedAt,
// breaking ties by checkpoint ID so the order is fully deterministic.
func sortCandidatesByRecency(candidates []candidate) {
sort.SliceStable(candidates, func(i, j int) bool {
    if !candidates[i].CreatedAt.Equal(candidates[j].CreatedAt) {
        return candidates[i].CreatedAt.After(candidates[j].CreatedAt)
    }
    return candidates[i].CheckpointID < candidates[j].CheckpointID
})
}

// readLocalSummaryTitle returns the latest session's outcome (falling back to
// its intent) for use as a bullet title, or "" when no session summary is
// available.
func readLocalSummaryTitle(ctx context.Context, store checkpoint.PersistentStore, cid checkpointid.CheckpointID, summary *checkpoint.CheckpointSummary) string {
    if summary == nil || len(summary.Sessions) == 0 {
        return ""
    }
    latestIndex := len(summary.Sessions) - 1
    metadata, err := store.ReadSessionMetadata(ctx, cid, latestIndex)
    if err != nil || metadata == nil || metadata.Summary == nil {
        return ""
    }
    if outcome := strings.TrimSpace(metadata.Summary.Outcome); outcome != "" {
        return outcome
    }
    return strings.TrimSpace(metadata.Summary.Intent)
}

// reachableCheckpointIDsInRange maps each checkpoint ID referenced by a commit
// trailer in revRange, within the window [since, until), to the most recent\
// referencing commit time *that falls inside the window*. The commit time is\
// the "landed on this branch" timestamp, used both for membership checks and to\
// window checkpoints that are fetched on demand by ID (whose CheckpointSummary\
// carries no CreatedAt of its own).\
//\
// Commits outside the window are ignored entirely, so a checkpoint referenced\
// by both an in-window commit and a later out-of-window commit still records\
// its in-window time (and is therefore not dropped by the caller's window\
// check). git's --since/--until only bound the scan; the explicit in-loop check\
// is authoritative for the half-open [since, until) boundary.\
func reachableCheckpointIDsInRange(ctx context.Context, repoRoot, revRange string, since, until time.Time) (map[string]time.Time, error) {\
    cmd := exec.CommandContext(\
        ctx,\
        "git",\
        "log",\
        revRange,\
        "--since="+since.UTC().Format(time.RFC3339),\
        "--until="+until.UTC().Format(time.RFC3339),\
        "--grep",\
        "Entire-Checkpoint:",\
        "--format=%B%x00",\
        "--format=%cI%x00%B%x00%x00",\
    )
    output, err := cmd.Output()\
    if err != nil {\
        return nil, fmt.Errorf("list HEAD checkpoint trailers: %w", err)\
    } \n
    reachable := make(map[string]struct{})\
    for _, message := range strings.Split(string(output), "\x00") {\
        for _, checkpointID := range trailers.ParseAllCheckpoints(message) {\
            reachable[checkpointID.String()] = struct{}{}\
        }
    }
    reachable := make(map[string]time.Time)\
    for _, record := range strings.Split(string(output), "\x00\x00") {\
        record = strings.TrimLeft(record, "\n")\
        parts := strings.SplitN(record, "\x00", 2)\
        if len(parts) != 2 {\
            continue\
        }\
        commitTime, parseErr := time.Parse(time.RFC3339, strings.TrimSpace(parts[0]))\
        if parseErr != nil {\
            continue\
        }\
        if commitTime.Before(since) || !commitTime.Before(until) {\
            continue\
        }\
        for _, checkpointID := range trailers.ParseAllCheckpoints(parts[1]) {\
            idStr := checkpointID.String()\
            if existing, ok := reachable[idStr]; !ok || commitTime.After(existing) {\
                reachable[idStr] = commitTime\
            }\
        }\
    }
    return reachable, nil\
}

// those unique to the current branch — reachable from HEAD but not from the\
// repository's default branch. Falls back to "HEAD" when no default branch\
// can be resolved (e.g. a fresh repo with no main/master ref).\
func branchLocalRevRange(ctx context.Context, repoRoot string) string {\
//\
// When the current branch IS the default branch there is no parent history to\
// exclude: base..HEAD is empty on an up-to-date default branch, which would\
// drop every checkpoint whose summary.Branch is a (now-merged) feature branch\
// and leave the dispatch effectively empty. In that case we summarize\
// everything reachable from HEAD in the window, matching the server-side\
// dispatch. The base..HEAD exclusion only applies to feature branches.\
func branchLocalRevRange(ctx context.Context, repoRoot, currentBranch string) string {\
    base := defaultBranchRef(ctx, repoRoot)\
    if base == "" {\
        return "HEAD"\
    } \n	if currentBranch != "" && strings.TrimPrefix(base, "origin/") == currentBranch {\
        return "HEAD"\
    } \n	return base + "..HEAD"\
}