Skip to content
Merged
27 changes: 20 additions & 7 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,13 +73,14 @@ Syncs the whole H2 file. OAuth client credentials live in
`bootstrap/PendingDownloadApplier` swaps it in at the next launch, before
Spring opens H2. There is no live reload, and nothing is downloaded
automatically at startup.
- Startup maintenance (marking delayed tasks, sweeping overdue goal attempts)
- Startup maintenance (marking delayed tasks, sweeping overdue goal attempts,
normalizing achieved goal checklists)
is derived data every machine recomputes, so it must not set the dirty flag:
otherwise merely opening the app looks like unsaved edits and raises a false
sync conflict. `StudySyncUI.runStartupMaintenance` wraps it in
`GoogleDriveService.runStartupMaintenanceWithoutDirtyTracking`, and the goal
sweep saves through `StudyService.saveLocallyWithoutDirtyFlag` (its javadoc
says why the wrapper alone is not enough). It runs only once the startup
sweep and checklist repair save through `StudyService.saveLocallyWithoutDirtyFlag`
(its javadoc says why the wrapper alone is not enough). It runs only once the startup
Drive check reports up to date, local newer, unknown or disabled; never with
a newer Drive copy, a conflict, or a staged download pending. Reading goals
also sweeps overdue attempts, so `StudySyncUI` holds that sweep
Expand Down Expand Up @@ -186,10 +187,22 @@ Syncs the whole H2 file. OAuth client credentials live in
(not the attempt) so a retry continues from earlier ticks. Only
`StudyGoal.parseCriteria` / `serializeCriteria` know its `[x] ` / `[ ] `
line format.
- Ticking the last criterion achieves the current attempt through the same path
as the checkbox (`StudyService.setGoalCriterionDone`); unticking one reopens
an achieved goal. The checkbox also works alone, so a goal can be achieved
with criteria open or with no checklist. There is no partial credit.
- The checkbox and the checklist mirror each other, so a goal with a checklist
is achieved exactly when every line is ticked. Ticking the last criterion
achieves the current attempt and unticking one reopens it, keeping the other
ticks (`StudyService.setGoalCriterionDone`). Ticking the checkbox ticks every
line and unticking it clears them (`updateStudyGoalAchievement`); a goal it
cannot change keeps its ticks. A checklist edit re-applies the rule. An
earlier day's achieved goal stays achieved with its lines ticked
(`StudyGoal.isAchievedBefore`): reopening it would leave a past pending
attempt that is swept to missed, so unticking it changes nothing, the planner
shows it read-only, and a checklist edit ticks its new lines instead. A
missed or dropped attempt can be neither achieved nor ticked; a retry
continues from its ticks. When those ticks are already complete, a retry or
reopen must say what to do (`StudyService.CompletedChecklist`): start the
checklist over, or mark the goal done with an attempt dated today. The
planner asks in the retry row; date dialogs use `GoalActions.ChecklistChoice`.
A goal without a checklist uses the checkbox alone. There is no partial credit.
- Goal forms reuse `GoalEditFields` and `TaskStyleUtils.criteriaArea` /
`CRITERIA_LABEL` / `criteriaChecklist` / `criteriaProgress`. A task's
`done_criteria` is plain text, not a checklist.
Expand Down
67 changes: 65 additions & 2 deletions src/main/java/com/studysync/domain/entity/StudyGoal.java
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,14 @@ public void setAchieved(boolean achieved) {
}
}

/**
* Achieved on a day before {@code today}. That achievement is history: reopening it would leave a
* pending attempt in the past that the next refresh sweeps to missed, so nothing reopens it.
*/
public boolean isAchievedBefore(LocalDate today) {
return achieved && date != null && date.isBefore(today);
}

public String getReasonIfNotAchieved() { return reasonIfNotAchieved; }
public void setReasonIfNotAchieved(String reasonIfNotAchieved) {
this.reasonIfNotAchieved = reasonIfNotAchieved;
Expand Down Expand Up @@ -284,6 +292,12 @@ public void setFailed(boolean failed) {
/** The checklist behind {@link #getDoneCriteria()}; empty when none was written. */
public List<Criterion> getCriteria() { return parseCriteria(doneCriteria); }

/** True when the goal has a checklist and every line of it is ticked. */
public boolean isChecklistComplete() {
List<Criterion> criteria = getCriteria();
return !criteria.isEmpty() && criteria.stream().allMatch(Criterion::done);
}

// ponytail: checklist stored as "[x] line" text on the parent goal, not a
// table - move to a study_goal_criteria table only if criteria ever need
// ids or history.
Expand Down Expand Up @@ -321,6 +335,11 @@ public static String serializeCriteria(List<Criterion> criteria) {
// ponytail: ticks re-matched by exact trimmed text; a reworded done
// criterion comes back unticked.
public static String criteriaFromLines(String plainLines, String previousStored) {
return criteriaFromLines(plainLines, previousStored, true);
}

/** When typed ticks are disallowed, only matching previously stored ticks survive an edit. */
public static String criteriaFromLines(String plainLines, String previousStored, boolean allowTypedTicks) {
if (plainLines == null) {
return null;
}
Expand All @@ -334,7 +353,7 @@ public static String criteriaFromLines(String plainLines, String previousStored)
// Always consume the matching previous tick, even when the typed line
// is already "[x]", or it would leak to the next duplicate line.
boolean previouslyDone = ticks != null && !ticks.isEmpty() && ticks.poll();
out.add(new Criterion(typed.text(), typed.done() || previouslyDone));
out.add(new Criterion(typed.text(), (allowTypedTicks && typed.done()) || previouslyDone));
}
return serializeCriteria(out);
}
Expand Down Expand Up @@ -837,13 +856,57 @@ public static Optional<List<Criterion>> setCriterionDone(String goalId, int inde
return Optional.of(criteria);
}

/** Ticks or clears every checklist line; returns whether the stored checklist changed. */
public static boolean setAllCriteriaDone(String goalId, boolean done) {
if (jdbcTemplate == null || goalId == null || goalId.isBlank()) {
return false;
}
String stored = jdbcTemplate.query("""
SELECT done_criteria FROM study_goals WHERE id = ?
""", rs -> rs.next() ? rs.getString("done_criteria") : null, goalId);
return markAllCriteria(goalId, parseCriteria(stored), done);
}

/**
* Repairs pre-mirroring achieved goals without changing their outcome or completion history.
* Runs at every startup, so it reads all achieved checklists at once and writes only the rows
* that still have an open line.
*/
public static int normalizeAchievedChecklists() {
requireJdbcTemplate();
List<Map.Entry<String, String>> checklists = jdbcTemplate.query("""
SELECT id, done_criteria FROM study_goals WHERE status = 'ACHIEVED' AND done_criteria IS NOT NULL
""", (rs, row) -> Map.entry(rs.getString("id"), rs.getString("done_criteria")));
int changed = 0;
for (Map.Entry<String, String> checklist : checklists) {
if (markAllCriteria(checklist.getKey(), parseCriteria(checklist.getValue()), true)) {
changed++;
}
}
return changed;
}

private static boolean markAllCriteria(String goalId, List<Criterion> criteria, boolean done) {
if (criteria.isEmpty() || criteria.stream().allMatch(criterion -> criterion.done() == done)) {
return false;
}
return jdbcTemplate.update("""
UPDATE study_goals
SET done_criteria = ?, updated_at = CURRENT_TIMESTAMP
WHERE id = ?
""", serializeCriteria(criteria.stream().map(criterion -> new Criterion(criterion.text(), done))
.toList()), goalId) > 0;
}

public static boolean markCurrentAttemptAchieved(String goalId, String reasonIfNot) {
Optional<StudyGoal> goalOpt = findById(goalId);
if (goalOpt.isEmpty()) {
return false;
}
StudyGoal goal = goalOpt.get();
if (goal.attemptId == null || goal.isDropped() || goal.isDroppedAttempt()) {
// A missed attempt is history; achieving the goal means planning a retry first.
if (goal.attemptId == null || goal.isDropped() || goal.isDroppedAttempt()
|| goal.attemptOutcome == AttemptOutcome.MISSED) {
return false;
}
jdbcTemplate.update("""
Expand Down
Loading
Loading